diff --git a/.github/workflows/art-fieldwatch-phase1.yml b/.github/workflows/art-fieldwatch-phase1.yml new file mode 100644 index 0000000..64d34f6 --- /dev/null +++ b/.github/workflows/art-fieldwatch-phase1.yml @@ -0,0 +1,177 @@ +name: ART Fieldwatch phase 1 +on: + pull_request: + paths: ['art-fieldwatch-phase1/**', '.github/workflows/art-fieldwatch-phase1.yml'] + workflow_dispatch: + inputs: + arm64: + description: 'Run experimental arm64 JIT hook test' + type: boolean + default: false +permissions: + contents: read +# Older PR test matrices were overlapping on hosted runners, repeatedly +# getting Maven Central HTTP 429. Only the newest run is authoritative. +concurrency: + group: art-fieldwatch-${{ github.event.pull_request.number || github.ref }} + cancel-in-progress: true +jobs: + static: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - run: node --check art-fieldwatch-phase1/jit-boundary-probe.js + - run: python3 -m py_compile art-fieldwatch-phase1/ci/smoke_test.py + - run: python3 -m py_compile art-fieldwatch-phase1/ci/dex_method_index.py + - run: python3 art-fieldwatch-phase1/ci/dex_method_index.py --self-test + - run: python3 art-fieldwatch-phase1/ci/dex_field_sites.py --self-test + - run: python3 art-fieldwatch-phase1/ci/resolve_field_events.py --self-test + - run: bash -n art-fieldwatch-phase1/ci/run-emulator-smoke.sh + - run: bash -n art-fieldwatch-phase1/ci/dex-inventory.sh + - run: bash -n art-fieldwatch-phase1/ci/build-passive-shim.sh + android: + runs-on: ubuntu-latest + timeout-minutes: 35 + strategy: + fail-fast: false + # Avoid three fresh Gradle/AGP dependency resolutions sharing the + # runner egress/IP at once, which triggers Maven Central HTTP 429. + max-parallel: 1 + matrix: + include: + - api: 33 + variant: debug + - api: 33 + variant: release + - api: 34 + variant: debug + env: + FRIDA_VERSION: '17.27.1' + ARTWATCH_BUILD_VARIANT: ${{ matrix.variant }} + ARTWATCH_LOG_DIR: /tmp/artwatch-logs + ARTWATCH_REQUIRE_JIT: '1' + ARTWATCH_SHADOW_SHIM: ${{ matrix.api == 33 && '1' || '0' }} + ARTWATCH_P3_INJECT: ${{ matrix.api == 33 && matrix.variant == 'debug' && '1' || '0' }} + steps: + - uses: actions/checkout@v4 + # Emulator 37.3+ refuses -accel off without an explicit TCG override. + # GitHub-hosted Ubuntu runners support KVM once the device is accessible. + - name: Enable and verify KVM before installing the emulator + shell: bash + run: | + set -euo pipefail + if [ ! -c /dev/kvm ]; then + echo "::error::No /dev/kvm device: cannot boot accelerated x86_64 emulator on this runner." + exit 1 + fi + echo 'KERNEL=="kvm", GROUP="kvm", MODE="0666", OPTIONS+="static_node=kvm"' | + sudo tee /etc/udev/rules.d/99-kvm4all.rules + sudo udevadm control --reload-rules + sudo udevadm trigger --name-match=kvm + ls -l /dev/kvm + if [ ! -r /dev/kvm ] || [ ! -w /dev/kvm ]; then + echo "::error::/dev/kvm is not readable/writable by the runner." + exit 1 + fi + echo "KVM device is accessible" + - uses: actions/setup-java@v4 + with: + distribution: temurin + java-version: '17' + - uses: actions/setup-python@v5 + with: + python-version: '3.12' + - uses: android-actions/setup-android@v4 + with: + packages: 'platform-tools platforms;android-35 build-tools;35.0.0' + - uses: gradle/actions/setup-gradle@v4 + with: + gradle-version: '8.10.2' + - name: Build API33 passive shadow shim + if: matrix.api == 33 + run: bash art-fieldwatch-phase1/ci/build-passive-shim.sh + - name: Build selected APK variant + shell: bash + run: | + case "$ARTWATCH_BUILD_VARIANT" in + debug) task=assembleDebug ;; + release) task=assembleRelease ;; + *) exit 1 ;; + esac + # Maven/Google repositories occasionally return incomplete metadata + # on hosted runners. Retry the whole build, but fail normally after + # exhausting attempts; never suppress real compilation errors. + for attempt in 1 2 3; do + if gradle -p art-fieldwatch-phase1/test ":app:$task" --no-daemon; then + exit 0 + fi + if (( attempt == 3 )); then + echo "::error::Gradle APK build failed after 3 attempts" + exit 1 + fi + echo "::warning::Gradle build attempt $attempt/3 failed; retrying repository resolution" + sleep "$((attempt * 10))" + done + - name: Verify packaged native shadow library + if: matrix.api == 33 + run: | + apk="art-fieldwatch-phase1/test/app/build/outputs/apk/$ARTWATCH_BUILD_VARIANT/app-$ARTWATCH_BUILD_VARIANT.apk" + unzip -l "$apk" | grep 'lib/x86_64/libartwatch_shadow.so' + unzip -l "$apk" | grep 'lib/x86_64/libartwatch_events.so' + unzip -l "$apk" | grep 'lib/x86_64/libartwatch_jvmti.so' + - name: Record compiled fixture DEX for D8 comparison + run: bash art-fieldwatch-phase1/ci/dex-inventory.sh + - run: python3 -m pip install 'frida==17.27.1' + - uses: reactivecircus/android-emulator-runner@v2 + with: + api-level: ${{ matrix.api }} + target: default + arch: x86_64 + profile: pixel_2 + disable-linux-hw-accel: false + emulator-boot-timeout: 300 + script: bash art-fieldwatch-phase1/ci/run-emulator-smoke.sh + - uses: actions/upload-artifact@v4 + if: always() + with: + name: artwatch-api${{ matrix.api }}-x86_64-${{ matrix.variant }} + path: /tmp/artwatch-logs/ + if-no-files-found: ignore + android-arm64: + if: github.event_name == 'workflow_dispatch' && inputs.arm64 + runs-on: macos-15 + timeout-minutes: 45 + env: + FRIDA_VERSION: '17.27.1' + ARTWATCH_LOG_DIR: /tmp/artwatch-logs + ARTWATCH_REQUIRE_JIT: '1' + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-java@v4 + with: + distribution: temurin + java-version: '17' + - uses: actions/setup-python@v5 + with: + python-version: '3.12' + - uses: android-actions/setup-android@v4 + with: + packages: 'platform-tools platforms;android-35 build-tools;35.0.0' + - uses: gradle/actions/setup-gradle@v4 + with: + gradle-version: '8.10.2' + - run: gradle -p art-fieldwatch-phase1/test :app:assembleDebug --no-daemon + - run: python3 -m pip install 'frida==17.27.1' + - uses: reactivecircus/android-emulator-runner@v2 + with: + api-level: 34 + target: google_apis + arch: arm64-v8a + profile: pixel_2 + script: bash art-fieldwatch-phase1/ci/run-emulator-smoke.sh + - uses: actions/upload-artifact@v4 + if: always() + with: + name: artwatch-api34-arm64 + path: /tmp/artwatch-logs/ + if-no-files-found: ignore diff --git a/art-fieldwatch-phase1/README.md b/art-fieldwatch-phase1/README.md new file mode 100644 index 0000000..298d476 --- /dev/null +++ b/art-fieldwatch-phase1/README.md @@ -0,0 +1,555 @@ +# ART Fieldwatch Phase 1 — JIT and HGraph research + +**Read-only diagnostic:** field interception, graph mutation, DEX rewriting, +deoptimization and native compiled-code patching are NOT implemented. + +## Verified compiler interface + +GitHub Actions run [44590572013](https://github.com/mnalmahmud/frida-scripts/actions/runs/44590572013) +observed 11 successful JIT compilations on each Android API 33 and 34 x86_64 +emulator. API 33 used the exported JitCompiler::CompileMethod; API 34 used +the existing JitCompilerInterface vtable's slot 2. API 34 also exposed +the internal runtime dispatch symbol. ARM64 is unverified. + +## New read-only graph boundary experiment (API 33 x86_64) + +The actual API 33 `libart-compiler.so` dynamic ELF symbol table includes: +- `art::HGraphBuilder::BuildGraph()` +- `art::OptimizingCompiler::RunOptimizations(HGraph*, CodeGenerator*, const DexCompilationUnit&, PassObserver*)` + +The probe now hooks these exact exports, tags callbacks with the currently +compiled ArtMethod pointer and compilation kind on the same native thread, +and compares the candidate `HGraphBuilder::graph_` pointer against the +`HGraph*` argument at the start of `RunOptimizations()`. The CI smoke test +requires hooks, callbacks, and at least one matching graph pointer on API 33. + +The `graph_` offset is based on the AOSP `HGraphBuilder` C++ class layout +(`ValueObject` base, `graph_` first member), and MUST be validated on device. +The pointer is never traversed or retained after compilation. This +experiment does not preserve field events yet. + +API 34 lacks the corresponding dynamic compiler exports in run 44590572013. +It continues the verified JIT-only smoke, pending a version-specific +pre-optimization interception adapter. + +## CI and constraints + +Workflow: `.github/workflows/art-fieldwatch-phase1.yml` +Results: `/tmp/artwatch-logs/art-elf-inventory.txt`, Frida messages, +and Android logcat uploaded as artifacts. + +Pinned Frida server/client: 17.27.1. Target ultimately API 21–37 and +ARM/ARM64/x86/x86_64; no compatibility claim beyond tested profiles. +No global or selective deoptimization, Stalker or watchpoints. + +Source: https://android.googlesource.com/platform/art/ +Frida: https://github.com/frida/frida-java-bridge + +## First field-builder experiment (API 33 x86_64) + +ART instruction builder has non-inline `BuildInstanceFieldAccess` and +`BuildStaticFieldAccess` methods in AOSP. The probe now resolves the exact +candidate mangled exports; only addresses actually found in the device's +compiler library are hooked. It records DEX PC, read/write direction, +the raw field-index code unit (not a resolved field identity), the +active ArtMethod pointer, compilation kind, and builder graph pointer. + +A minimal Java fixture performs `value = x; return value;` and runs hot +enough to induce JIT compilation. CI requires an actual instance read and +write compiler callback tied to a live graph. This is read-only: +there is no actual run-time Java field event and no IR mutation. + +No field-builder hooks or event counts have been validated until this +commit's emulator jobs complete. + +## API 33 read-only node identity experiment + +Source: [AOSP instruction_builder.cc](https://android.googlesource.com/platform/art/+/master/compiler/optimizing/instruction_builder.cc) +shows `BuildInstanceFieldAccess` creating either a resolved +`HInstanceFieldGet/Set` or an `HUnresolvedInstanceFieldGet/Set`, then +calling `AppendInstruction`. The latter forwards the actual +`HInstruction*` to `HBasicBlock::AddInstruction`. + +A new *optional* API 33 x86_64 probe looks for exact exported +`HInstructionBuilder::AppendInstruction(HInstruction*)`, falling back +to `HBasicBlock::AddInstruction(HInstruction*)`. During an active field +build, it records the passed IR node pointer and its primary vtable +address. If vtable export symbols exist, it compares their Itanium ABI +address points to label the concrete class. No node fields are traversed, +no graph is modified, and no raw pointer is retained past compilation. + +The CI test fails if the append hook attaches but does not execute +within field-building context. Missing export symbols are reported as +an explicit *research gap* rather than falsely asserting unsupported ART +or crashing the process. This is not yet a runtime access event. + +## Follow-up: out-of-line append versus virtual visitor + +Run 44708162512 verified both the `AppendInstruction` export and field +node vtable exports, but zero callbacks reached `AppendInstruction` +while `BuildInstanceFieldAccess` was active. This is consistent with an +inlined call site, not proof that the instruction never enters the graph. + +This patch observes `HBasicBlock::AddInstruction` independently and hooks +the exported `HInstanceFieldGet/Set::Accept(HGraphVisitor*)`, plus +static/unresolved variants when available. The latter exposes actual IR +object pointers during ordinary ART visitor passes; per-thread correlation +ties them to JIT compilation without traversing arbitrary graph memory. + +It asserts that at least one field IR node is observed via either +insertion or virtual visitor callbacks. Vtable matching distinguishes +the actual node kind, but a visitor event alone does not establish that +a particular DEX instruction survived a specific optimization pass. + +## Targeted field IR lifecycle (new experiment) + +The 2026-11-20 run 44709847484 passed on API 33 and API 34. +API 33 observed 180 field IR `Accept` callbacks, all matching +their exported class vtables. The two insertion symbols remained silent +during active field-builder hooks, confirming that merely finding their +exports was insufficient. + +A new probe identifies `FieldIRTarget.test(int)` through the verified +DEX pattern `iput@0` and `iget@2` (field_idx 0) and independently +records each unique field IR object/class/visitor phase for that method. +It avoids losing the small fixture to the earlier 180-callback sample cap. + +AOSP load/store elimination can replace redundant field loads and remove +unnecessary stores. This commit adds **read-only**, opt-in interception +candidates for `HInstruction::ReplaceWith`, +`HBasicBlock::RemoveInstruction`, and `LoadStoreElimination::Run` +if those exact exports exist on the API 33 binary. Offline ELF symbol +inventory records the actual signatures for follow-up corrections. + +The test strictly requires the target method and both get/set IR node +types. It does *not* require an elimination event before one is observed, +does not assume pass identity from an arbitrary visitor, and does not +modify compiler memory or deoptimize any Java method. + +AOSP sources: +- https://android.googlesource.com/platform/art/+/master/compiler/optimizing/load_store_elimination.cc +- https://android.googlesource.com/platform/art/+/master/compiler/optimizing/nodes.cc + +## Test non-debuggable release JIT/LSE — November 2026 + +Run 44711997095 passed on both API 33 and 34. In the API 33 +debug APK, the exact `HInstanceFieldSet` and `HInstanceFieldGet` objects +were observed during the target method's baseline JIT build. Three +mutation/LSE symbol hooks were installed but reported zero target mutations. +Do not interpret this as a negative ART result: AOSP +`LoadStoreElimination::Run` explicitly returns early if +`graph_->IsDebuggable()`, and our APK was previously *only* built +as `assembleDebug`. + +The API 33 CI matrix now includes a separately signed, +**non-debuggable** `assembleRelease` APK. Rooted frida-server attaches +normally. The app logs its actual ApplicationInfo debuggable flag, +and the Python harness asserts this flag matches the tested variant. +The non-debuggable fixture performs additional hot calls to target +optimized compilation without touching ART's deoptimization APIs. + +Read-only `LoadStoreElimination::Run(bool)` hooks now report every +JIT invocation (bounded output), with the compilation kind and whether +the invocation belongs to the target method, plus the Boolean result +of the pass. Per-method compilation summaries include whether +`RunOptimizations()` ran and how often LSE was entered. + +The release job explicitly requires an optimized JIT compilation and +at least one LSE invocation. If either is missing, it fails with +a diagnostic instead of silently reporting an invalid optimization test. + +Source: https://android.googlesource.com/platform/art/+/master/compiler/optimizing/load_store_elimination.cc + +## CI harness correction after run 44713659551 + +The API 33 release `assembleRelease` failed in +`lintVitalRelease` because Google Play's +`ExpiredTargetSdkVersion` check rejects the fixture's intentional +targetSdk 28. Suppress only this Play-store publishing diagnostic; +keep remaining lint checks enabled and preserve targetSdk for comparisons. + +The API 33 debug test reached ART and observed LSE calls, but the test +method was not identified because adding the debuggable-flag logging +changed the target field's raw DEX index from 0 to 1. +The signature matcher now requires `iput@0` and `iget@2` on +the *same* field index within the same compiled method, regardless +of the actual index. This is a fixture fingerprint, not a general +method-identity mechanism. + +## Release DEX / field mutation research follow-up + +Run 44716336483 passed API 33 debug and API 34 debug. The new +API 33 non-debuggable release job **booted and ran ART**, including +`LoadStoreElimination::Run(bool)` with several `true` returns, but the +strict target-method DEX fingerprint was absent. Its field-builder logs +contained an `iput` for the target's field index but no corresponding +`iget` in that method. D8 has a redundant-field-load elimination pass +that can remove such a read *before ART sees the DEX*, so **do not +attribute this disappearance to ART LSE without direct DEX evidence**. + +The new `ci/dex-inventory.sh` saves the actual debug/release +`FieldIRTarget` smali using Android SDK `apkanalyzer` (or reports +tool unavailability) along with DEX SHA-256 in CI artifacts. + +The release CI now requires an optimized JIT compilation and at least +one LSE pass returning `true`, but does *not* require the debug-only +`iput@0/iget@2` DEX fingerprint. The debug CI continues its strict +get/set IR assertions. + +The API 33 observer now also recognizes +`HBasicBlock::ReplaceAndRemoveInstructionWith` and +`RemoveInstructionOrPhi`, and records vtable-verified field-node +replacements/removals across **all** compilation methods, not only the +one that may have been transformed by D8. Per-compilation call deltas +distinguish an exported hook from an actually executed call. + +The experiment is still read-only. A `true` LSE return does not, by +itself, prove any specific field read was removed, nor does it imply +a runtime field event. + +Sources: +- https://r8.googlesource.com/r8/+/main/src/main/java/com/android/tools/r8/ir/optimize/RedundantFieldLoadAndStoreElimination.java +- https://developer.android.com/tools/apkanalyzer +- https://android.googlesource.com/platform/art/+/master/compiler/optimizing/load_store_elimination.cc + +## Read-only backend field lowering experiment + +Run 44718929267 passed all required jobs and proved through +`apkanalyzer` that `FieldIRTarget.test(int)` contains `iput` + `iget` +in debug DEX, but *only `iput` + `return p1`* in release DEX. +This is a D8/build-time transformation, not evidence of ART LSE. + +`FieldIRTarget.testViaIdentity(int)` now passes the receiver through +a trivial helper before re-reading its field. The release DEX inventory +**strictly requires** the new method to contain both an `iput` and +an `iget`, otherwise CI fails before the emulator starts. This +separates build-time preservation from ART's runtime JIT optimizer. + +On API 33 x86_64, the read-only Frida probe also hooks the exported +`LocationsBuilderX86_64::VisitInstanceFieldGet/Set` and +`InstructionCodeGeneratorX86_64::VisitInstanceFieldGet/Set` +entry points. Their `HInstruction*` arguments are verified against +the exact exported field-node vtable. Observer events are associated +with the current compiled method and IR node address; per-compilation +summaries list nodes reaching location assignment and code emission. + +**A code emission visitor callback is a compile-time observation, not +a runtime field event**, and neither stage proves an optimized-away +source-level field read executed. All research hooks remain read-only. + +Relevant historical AOSP: +https://android.googlesource.com/platform/art/+/0c0043d8cc/compiler/optimizing/code_generator_x86_64.cc + +## Exact-node field elimination proof (API 33 release) + +Run [44722172785](https://github.com/mnalmahmud/frida-scripts/actions/runs/44722172785) +succeeded with both `iput` and `iget` in the **release** +`testViaIdentity(int)` DEX. ART on API 33 entered real LSE and recorded +seven vtable-validated field-node mutations: in optimized compilation +`kind=2` of a method containing the fixture's field accesses, an +`HInstanceFieldGet*` was replaced by another HInstruction and then +removed. The same pointer had been observed by a compiler visitor +before LSE. Removed nodes were absent from backend location assignment +and emission in that successful compilation. This is compiler-time +elimination, **not a runtime field callback**. + +The new `artwatch-field-lifecycle` event combines observations from +the same JIT compilation using `kind + node address` as the temporary +identity. The event records `visitedBeforeMutation`, the ordered +mutation operations, the replacement pointer, and whether the node +reached backend location assignment/code emission. No instruction +memory is accessed after deletion or after compilation. + +**Strict API 33 release CI assertion:** a successfully optimized +compilation must include an `HInstanceFieldGet` visited before +replacement/removal during LSE that is absent from backend emission. +As a control, an independently observed baseline compilation must +still emit an `HInstanceFieldGet`. The debug tests retain their +original assertions. + +**Method identity caveat:** the DEX-pattern matcher can identify +inlined `iput`/`iget` operations within a caller, not just the +standalone fixture method. Thus this proves elimination of actual +field IR during optimized compilation, but does not claim that the +standalone Java method was individually optimized or that its +source-level access occurred as a physical field load. + +This research supports a decision to treat **logical DEX-level field +events** separately from **physical compiled memory accesses**. +A future compiler-side event sink would require side-effect ordering, +exception/GC-safety analysis, field-target resolution and live-value +mapping. No such sink or IR mutation is implemented yet. + +## Opt-in API33 P1 native shadow companion + +`native/passive-shadow.c` is a read-only NDK shared library for the +**exact** API 33 x86_64 emulator ART ELF build IDs. It checks live +`libart.so` and `libart-compiler.so` GNU build IDs and SDK before +enabling observation. It reads one opaque word from a matched live +`HGraph*`, and checks `HInstanceFieldGet/Set` vptrs against exported +primary C++ vtable address points while the compiler visitor executes. +No ART memory writes or C++ class layout guesses are present. + +Only API33 CI opts in via `ARTWATCH_SHADOW_SHIM=1`. An NDK build alone +is not considered evidence: CI requires the native module to load, +verify both mapped build IDs, observe a graph, recognize both instance +field node kinds, and reject zero pointers. API34 remains unchanged. + +P1 does **not** traverse HGraph blocks or construct an IR node. The +test covers native-bridge callability and object validation, which +are prerequisites for source-matched native traversal in the next +phase. No field runtime monitoring has been implemented. + +## Native-library deployment fix (follow-up) + +CI run 44729819209 compiled the native shim on API33 debug and +release, and ART's exact GNU build IDs were present, but both jobs +failed because the app process could not map executable segments from +`/data/local/tmp/libartwatch_shadow.so` (Permission denied). API34 and +static checks passed. **This was a deployment/SELinux limitation, not a +failure of graph or node-pointer validation.** + +The shim is now staged at `test/app/src/main/jniLibs/x86_64/` as an +ephemeral NDK build output before `assembleDebug/assembleRelease`. +The APK is built with legacy JNI extraction, so Android installs the +library in the application's native library directory. The Java +fixture loads it with `System.loadLibrary("artwatch_shadow")` in +`MainActivity.onCreate()` before warmup, and the Frida agent resolves +the *already loaded* ELF lazily when the first compiler callback +occurs. No `dlopen` attempt from `/data/local/tmp`, global SELinux +policy change or writable executable file mapping is used. +API34 retains the previous monitoring behavior. + +## More reliable release JIT/LSE fixture coverage + +Run 44734968302 confirmed the API33 native shim works, with correct +ART build IDs, six graph validations, and native get/set vtable counts, +but the release compiler did not eliminate the targeted get during +that particular warmup (no field-node mutation event). The debug and +API34 jobs passed. This does not invalidate prior exact-node +elimination evidence; it reveals JIT-scheduling/coverage variability. + +Release warmup now exercises three **different** naturally hot methods +across five bounded stages, with short sleeps so the optimizing JIT +worker has time to drain its queue: `warmup`, `exerciseOverwrites` +and `exerciseAlternating`. The latter two have read-after-write +operations behind an `identity()` helper, and the release DEX audit +asserts `iput` **and** `iget` survived D8 in each method. +The Frida observation window is extended from 20 to 30 seconds only +for release; it must see all five logcat stage markers. + +This is still a natural JIT test. No selective/global deoptimization, +Stalker or compiler mutation is required. Crucially, the strict +same-node LSE replacement/removal assertion is **unchanged**; failing +to provoke elimination will remain visible as a CI failure. + +## P1.1 bounded optimization-window field-node inventory + +Native `artwatch_shadow_scope_begin/end` now maintains a **thread-local** +fixed-size (512-node) inventory of vptr-verified `HInstanceFieldGet/Set` +objects visited by ART **inside** a matched `RunOptimizations(HGraph*)` +call. The native caller reports get/set visitor counts and distinct +node identities per compilation; no pointers are retained after scope +end and no ART object is modified. The inventory never calls Java, +allocates ART memory or invokes a graph transformation. Overflow is +reported and treated as a CI failure, rather than silently losing nodes. + +This is a compiler-visitor observation window, **not** direct traversal +of `HGraph::GetBlocks()`. AOSP uses an `ArenaVector` +for its block list, but constructing a compatible native reader from +the NDK alone requires layout verification against the exact Android +13 compiler build. We deliberately do not interpret private +`HGraph` offsets or follow guessed pointers at this stage. + +Reference for structural IR types (not an ABI guarantee): +https://android.googlesource.com/platform/art/+/refs/heads/android13-d4-s1-release/compiler/optimizing/nodes.h + +## P1.2 optional source-backed basic-block discovery + +The published ART `nodes.cc` defines `HGraph::AddBlock(HBasicBlock*)`, +and `GraphChecker::VisitBasicBlock(HBasicBlock*)` is a separate +graph-verification boundary. They are candidates for **observing live +basic-block identities without assuming private object offsets**. + +The API33 x86_64 probe checks the exact exported symbols, and attaches +read-only callbacks only if present. `AddBlock` pointers must match +the graph candidate captured during the active HGraphBuilder call. +The passive native shim validates the supplied graph/block addresses +without dereferencing HBasicBlock or retaining a pointer after the +callback. `GraphChecker` block observations are logged separately. +Counts are correlated to the active JIT method and its optimization +boundary. Missing exports or inlined call sites are reported as research +gaps, **not** as evidence of an empty graph. + +This experiment does **not** claim native traversal of +`HGraph::GetBlocks()`: that accessor is inline, its member layout +is not certified against the emulator ABI, and scanning guessed C++ +memory would be unsafe. IR mutation remains disabled. + +Source: +https://android.googlesource.com/platform/art/+/refs/heads/android13-d4-s1-release/compiler/optimizing/nodes.cc + +## P1.3 optional block-to-instruction and traversal correlation + +Run [44763868026](https://github.com/mnalmahmud/frida-scripts/actions/runs/44763868026) +passed all required CI jobs. The API33 compiler exports and executes +`HGraph::AddBlock(HBasicBlock*)`, yielding real block pointers associated +with the exact building `HGraph*`. The native observer confirmed 68 +block callbacks on the debug fixture and 343 on release; the sampled +per-method block counts are 29 and 63, respectively. +`GraphChecker::VisitBasicBlock` is exported but no matching +optimization-phase callbacks were captured. + +To advance instruction ownership without undocumented pointer offsets, +the P1.3 probe independently observes *all* executed exported +`HBasicBlock::AddInstruction(HInstruction*)` calls, even outside the +original field-builder stack frame. A match to one of the construction +block identities correlates a concrete `HInstruction*` and its +vtable-identified type with its containing `HBasicBlock*`. +The existing `HInstanceFieldGet/Set::Accept` callbacks may then match +that exact `kind@node` identity. This code remains **read-only**. + +The experiment separately checks the exported +`HGraphVisitor::VisitBasicBlock` boundary and logs whether the +compiler calls it during optimization; it compares those block +pointers with construction-time identities. AOSP's +`HGraphVisitor::VisitInsertionOrder/VisitReversePostOrder` functions +are inventoried but **never invoked** by the probe. Any method inlined +into its caller may yield no out-of-line callback, and this is +recorded as a research limitation rather than fabricated traversal. + +This is not direct `HGraph::GetBlocks()` memory traversal, a mutable +native shim, or runtime field-event emission. The stronger verified +`HGraph::AddBlock` observation is now mandatory in API33 CI. +See AOSP `nodes.cc` for graph visitor/block traversal structure: +https://android.googlesource.com/platform/art/+/c32e770f21540e4e9eda6dc7f770e745d33f1b9f/compiler/optimizing/nodes.cc + +## P1.4 source-backed block-to-field instruction ownership + +Run [44787102253](https://github.com/mnalmahmud/frida-scripts/actions/runs/44787102253) +passed API33 debug/release, API34 debug and static checks. +`HGraphVisitor::VisitBasicBlock(HBasicBlock*)` is exported and actually +executes: the release compiler recorded 300 basic-block observations +across optimization scopes. The out-of-line `HBasicBlock::AddInstruction` +export continued to produce zero matching insertion callbacks. + +The next experiment correlates the *dynamic extent* of +`HGraphVisitor::VisitBasicBlock` (native thread, visitor object and +block pointer) with `HInstanceFieldGet/Set::Accept(HGraphVisitor*)`. +The AOSP `nodes.cc` implementation of `VisitBasicBlock` iterates +phis/instructions and calls `instruction->Accept(this)`. +The Frida probe therefore stores an active visitor/block pair in a +thread-local JS map only until `VisitBasicBlock` returns and accepts +an instruction association only if `Accept` supplies the *same visitor*. +Nested visitors restore previous context in `onLeave`; no stale +`HInstruction*` is dereferenced after a pass. + +Per-compilation `artwatch-field-block-ownership` reports unique +field node/block pairs, get/set visit counts, visitor mismatches +and a small set of vtable-confirmed pointer samples. API33 CI +now requires actual correlated get **and** set visits, nonempty +ownership pairs and zero visitor mismatches. This is an observation +of fields traversed in a basic block, not an invocation of +`GetBlocks()` and not a statement that every graph node survives +optimization. Nothing mutates ART memory or invokes ART graph APIs. + +AOSP implementation reference: +https://android.googlesource.com/platform/art/+/257ab7fe6885c83f1ab17fe9d4cc4a996ebd3c7e/compiler/optimizing/nodes.cc + +## P1.5 exact eliminated field instruction → observed basic block + +[Run 44801128480](https://github.com/mnalmahmud/frida-scripts/actions/runs/44801128480) +passed Android API33 debug/release, API34 debug and static checks. Its +release logs correlated **401** `Accept` callbacks to the active +`VisitBasicBlock` frame (127 gets, 274 sets) across **108** +distinct node/block pairs, with zero mismatched visitor pointers. + +The release traces also contain four optimized +`HInstanceFieldGet*` nodes replaced and removed during LSE. Each of +these exact instruction pointers appeared in a source-backed +`VisitBasicBlock` callback with a block previously observed via +`HGraph::AddBlock`. + +This patch joins the historical block identities to the +`artwatch-field-lifecycle` event using **exact pointer+IR-kind +identity within one compilation**. It asserts that every +LSE-eliminated field-get node has a real, previously observed +basic-block owner and that the corresponding block was seen in +construction callbacks. + +Important caveat: an instruction can move between blocks, so +`observedBlocks` contains *historical visitation evidence*, +not an assertion that its final `HInstruction::GetBlock()` equals +any listed address. Removed node memory is never dereferenced. +All instrumentation remains read-only. + +## P1.6 read-only field sequence and LSE replacement producer evidence + +Run [44802096790](https://github.com/mnalmahmud/frida-scripts/actions/runs/44802096790) +passed all required CI jobs, confirming historical block ownership for +every tested optimized LSE-eliminated field read. + +AOSP `HGraphVisitor::VisitBasicBlock` iterates instructions and calls +`Accept(this)`. This experiment records a **bounded per-invocation +sequence of field-node visits** (visitor address, block address, exact +instruction pointer, field IR kind, and relative field-only ordinal). +The map is restored on `VisitBasicBlock` return, even for nested +calls. It does not claim a complete block instruction listing: phis +and non-field instructions are intentionally omitted, and optimizations +may move an instruction between visits. + +The experiment also examines LSE `HInstruction::ReplaceWith` calls. +At method entry, both old field node and live replacement SSA +`HInstruction*` are known. For replacements only, the agent matches +the replacement's primary vptr against **explicitly exported, +name-and-address-validated** ART instruction vtables, without calling +virtual functions or interpreting object fields. The IR lifecycle +record exposes the replacement pointer and `replacementKind` +when recognized; otherwise it reports a null kind instead of guessing. + +CI requires nonempty, internally consistent field-visit sequences; +SSA producer classification is diagnostic initially because the +compiler may use an instruction kind without a suitable exported +primary vtable. This remains compiler-time, read-only research: +neither Java field values nor actual field-access runtime events are +emitted. These observations define the next ABI verification needed +for a correctly typed, side-effecting event sink. + +AOSP reference (structural, not a binary ABI contract): +https://android.googlesource.com/platform/art/+/refs/heads/android13-release/compiler/optimizing/nodes.h + + +## P2 runtime event transport — executable, but not compiler-injected yet + +The previous phase proved compiler-time field identity, block ownership, +LSE replacement/removal, and native pointer validation. It did **not** +deliver an event from executed Java code. + +This phase adds a real, bounded, zero-allocation-on-hot-path JNI event +recorder in native/runtime-events.c. It is deliberately packaged as a +separate libartwatch_events.so, with no dependency on private ART layouts. +The C recorder takes (site, read/write, int value), reserves a fixed slot +atomically, publishes the record with release ordering, and counts drops +instead of allocating when its fixed capacity is exceeded. A separate +bounded JSON snapshot is exported for Frida RPC *after* the worker finishes. + +The fixture FieldIRTarget.watchedOn(receiver, x) now contains **explicit** +bytecode calls to FieldEventSink.recordInt after a successful field write +and read. It warms the method naturally, resets the event recorder, runs +128 instrumented invocations, and checks a null receiver throws before +any event is recorded. Frida's runtimeevents() RPC returns the actual +native records; CI asserts 256 events, exact per-site integer values, +write/read order, no drops, and the absence of a null-access event. + +**Scope and critical distinction:** These are genuine runtime events +from executing JIT-eligible Java code, but the event calls were placed +explicitly in the fixture by Java source. Arbitrary Java field +instructions are **not** yet instrumented; ART IR call insertion is +still required. This isolates the sink ABI, JNI integration, Frida +delivery and correctness from the dangerous next step of compiler IR +mutation. The old strict LSE and native-shadow assertions are retained +unchanged. The prototype covers only successful nonvolatile integer +accesses; no reference or volatile field support is claimed. + +Android's supported JNI loading/symbol contract: +https://developer.android.com/ndk/guides/jni-tips diff --git a/art-fieldwatch-phase1/ci/art-binary-inventory.sh b/art-fieldwatch-phase1/ci/art-binary-inventory.sh new file mode 100644 index 0000000..4dc45e6 --- /dev/null +++ b/art-fieldwatch-phase1/ci/art-binary-inventory.sh @@ -0,0 +1,56 @@ +#!/usr/bin/env bash +# Offline ELF visibility evidence (no symbol scan inside the Frida process). +set -euo pipefail +out="${ARTWATCH_LOG_DIR:-/tmp/artwatch-logs}" +mkdir -p "$out" +tmp="$(mktemp -d)" +trap 'rm -rf "$tmp"' EXIT +api="$(adb shell getprop ro.build.version.sdk | tr -d '\r')" +abi="$(adb shell getprop ro.product.cpu.abi | tr -d '\r')" +{ + echo "device api=$api abi=$abi" + for library in libart.so libart-compiler.so; do + source="/apex/com.android.art/lib64/$library" + if ! adb pull "$source" "$tmp/$library" >/dev/null 2>&1; then + echo "pull-failed $source" + continue + fi + echo "=== $library ===" + sha256sum "$tmp/$library" + echo "-- build-id --" + readelf -n "$tmp/$library" 2>&1 | grep -i -m 1 'Build ID:' || true + echo "-- available symbol sections --" + readelf -SW "$tmp/$library" 2>&1 | grep -E ' (\.symtab|\.dynsym|\.debug_info|\.gnu_debugdata) ' || true + echo "-- targeted symbols (dynamic and full, if available) --" + readelf -Ws "$tmp/$library" 2>&1 | + grep -E 'HGraphBuilder|OptimizingCompiler|TryCompile|RunOptimizations|PassObserver|JitCompiler.*CompileMethod|jit_load|CompileMethodInternal|BuildInstanceFieldAccess|BuildStaticFieldAccess|HInstanceField(Get|Set)|HStaticField(Get|Set)' | + head -n 80 || true + echo "-- graph insertion and field node vtable candidates --" + readelf -Ws "$tmp/$library" 2>&1 | + grep -E '(HBasicBlock.*AddInstruction|HInstructionBuilder.*AppendInstruction|_ZTVN3art[0-9]+H(Unresolved)?(Instance|Static)Field(Get|Set)E)' | + head -n 100 || true + echo "-- P3 invoke construction/insertion ABI candidates --" + readelf -Ws "$tmp/$library" 2>&1 | + grep -E '(HInvokeStaticOrDirect|HBasicBlock.*InsertInstruction(After|Before)|HInstruction.*SetEnvironment|HEnvironment.*(Copy|Create)|HInvoke.*(SetArgument|SetRawInputAt)|HGraph.*GetArena)' | + head -n 120 || true + echo "-- optimization, IR replacement/removal candidates --" + readelf -Ws "$tmp/$library" 2>&1 | + grep -E '(LoadStoreElimination|LSEVisitor|HInstruction.*ReplaceWith|HBasicBlock.*RemoveInstruction|ReplaceAndRemoveInstruction)' | + head -n 100 || true + echo "-- HGraphVisitor traversal and instruction ownership symbols --" + readelf -Ws "$tmp/$library" 2>&1 | + grep -E '(HGraphVisitor.*(VisitBasicBlock|VisitInsertionOrder|VisitReversePostOrder)|HBasicBlock.*AddInstruction|HInstruction.*GetBlock)' | + head -n 120 || true + echo "-- HGraph/AddBlock and graph checker exports --" + readelf -Ws "$tmp/$library" 2>&1 | + grep -E '(HGraph.*AddBlock|GraphChecker.*VisitBasicBlock|HGraph.*BuildDominatorTree|HBasicBlock.*GetFirstInstruction|HInstruction.*GetBlock|HGraphVisitor.*VisitBasicBlock)' | + head -n 100 || true + echo "-- summary --" + if readelf -SW "$tmp/$library" | grep -q ' \.symtab '; then + echo 'full-symbol-table=present' + else + echo 'full-symbol-table=absent' + fi + done +} > "$out/art-elf-inventory.txt" 2>&1 +cat "$out/art-elf-inventory.txt" diff --git a/art-fieldwatch-phase1/ci/build-passive-shim.sh b/art-fieldwatch-phase1/ci/build-passive-shim.sh new file mode 100644 index 0000000..1baa897 --- /dev/null +++ b/art-fieldwatch-phase1/ci/build-passive-shim.sh @@ -0,0 +1,56 @@ +#!/usr/bin/env bash +# Pin the NDK and build only a passive Android 13 x86_64 ELF shared library. +set -euo pipefail +version="27.2.12479018" +sdk="${ANDROID_HOME:-${ANDROID_SDK_ROOT:-}}" +: "${sdk:?Set ANDROID_HOME or ANDROID_SDK_ROOT}" +clang="$sdk/ndk/$version/toolchains/llvm/prebuilt/linux-x86_64/bin/x86_64-linux-android33-clang" +if [[ ! -x "$clang" ]]; then + # sdkmanager closes stdin when done; under pipefail, 'yes' then reports + # SIGPIPE even after a successful install. Check the installed compiler. + (yes | sdkmanager --install "ndk;$version" >/dev/null) || test -x "$clang" +fi +test -x "$clang" +out="art-fieldwatch-phase1/native/out" +mkdir -p "$out" +"$clang" -std=c11 -O2 -fPIC -fvisibility=hidden -fstack-protector-strong \ + -Wall -Wextra -Werror -shared -Wl,-z,relro -Wl,-z,now \ + art-fieldwatch-phase1/native/passive-shadow.c -ldl \ + -o "$out/libartwatch_shadow.so" +file "$out/libartwatch_shadow.so" +readelf -Ws "$out/libartwatch_shadow.so" | grep -E 'artwatch_shadow_(init|graph|node|report|scope_begin|scope_end|block|clone_template_invoke|clone_invoke_before)' | tee "$out/exports.txt" + +# Package the shim as an app-owned native library. This is an ephemeral CI +# build output, not a tracked ELF in the research branch. +jni_dir="art-fieldwatch-phase1/test/app/src/main/jniLibs/x86_64" +mkdir -p "$jni_dir" +cp "$out/libartwatch_shadow.so" "$jni_dir/libartwatch_shadow.so" +echo "Native shadow library staged for APK packaging: $jni_dir" + +# The runtime event library is intentionally separate from the passive +# ART-specific shadow companion. It has no dependency on private ART. +"$clang" -std=c11 -O2 -fPIC -fvisibility=hidden -fstack-protector-strong \ + -Wall -Wextra -Werror -shared -Wl,-z,relro -Wl,-z,now \ + art-fieldwatch-phase1/native/runtime-events.c \ + -o "$out/libartwatch_events.so" +readelf -Ws "$out/libartwatch_events.so" | + grep -E '(artwatch_events_(snapshot|p3_snapshot|record_field|field_snapshot|p3_field_snapshot|configure_p3)|Java_com_example_artfieldwatch_FieldEventSink_(recordInt|recordFieldInt|recordFieldLong|recordFieldFloat|recordFieldDouble|recordFieldNarrow|reset|resetFieldMeta|fieldMetaCount|eventCount|p3Enabled|p3Verified))' | + tee "$out/runtime-events-exports.txt" +cp "$out/libartwatch_events.so" "$jni_dir/libartwatch_events.so" +echo "Runtime event library staged for APK packaging: $jni_dir" + +# Android ART JVMTI agent for debuggable applications (API 28+). +cxx="$sdk/ndk/$version/toolchains/llvm/prebuilt/linux-x86_64/bin/x86_64-linux-android33-clang++" +test -x "$cxx" +test -f "${JAVA_HOME:?JAVA_HOME required}/include/jvmti.h" +"$cxx" -std=c++17 -O2 -fPIC -fvisibility=hidden -fstack-protector-strong \ + -Wall -Wextra -Werror -shared -Wl,-z,relro -Wl,-z,now \ + -I "$sdk/ndk/$version/toolchains/llvm/prebuilt/linux-x86_64/sysroot/usr/include" \ + -I "$JAVA_HOME/include" -I "$JAVA_HOME/include/linux" \ + art-fieldwatch-phase1/native/jvmti-fieldwatch.cc -llog \ + -o "$out/libartwatch_jvmti.so" +readelf -Ws "$out/libartwatch_jvmti.so" | + grep -E '(Agent_OnAttach|artwatch_jvmti_snapshot)' | + tee "$out/jvmti-exports.txt" +cp "$out/libartwatch_jvmti.so" "$jni_dir/libartwatch_jvmti.so" +echo "JVMTI agent staged: $jni_dir" diff --git a/art-fieldwatch-phase1/ci/dex-inventory.sh b/art-fieldwatch-phase1/ci/dex-inventory.sh new file mode 100644 index 0000000..99a1317 --- /dev/null +++ b/art-fieldwatch-phase1/ci/dex-inventory.sh @@ -0,0 +1,95 @@ +#!/usr/bin/env bash +# Inspect the DEX actually shipped to the emulator, not Java source or classfiles. +# Read-only; saved per variant and uploaded with other ART CI evidence. +set -euo pipefail +variant="${ARTWATCH_BUILD_VARIANT:-debug}" +case "$variant" in debug|release) ;; *) echo "Invalid variant: $variant" >&2; exit 1 ;; esac +apk="art-fieldwatch-phase1/test/app/build/outputs/apk/$variant/app-$variant.apk" +test -f "$apk" +out="${ARTWATCH_LOG_DIR:-/tmp/artwatch-logs}" +mkdir -p "$out" +echo "variant=$variant apk=$apk" +unzip -p "$apk" classes.dex | sha256sum | tee "$out/dex-sha256-$variant.txt" +# Preserve the exact method_ids[] index of the real native sink in the +# packaged DEX (it can change across debug/release, or between builds). +python3 art-fieldwatch-phase1/ci/dex_method_index.py "$apk" | + tee "$out/p3-sink-method-$variant.json" +# Generic APK-wide field identities: all instance/static get/set opcodes, +# with declaring class, field type/name, enclosing method, DEX PC and source line. +python3 art-fieldwatch-phase1/ci/dex_field_sites.py "$apk" \ + --output "$out/field-sites-$variant.json" +analyzer="${ANDROID_HOME:-}/cmdline-tools/latest/bin/apkanalyzer" +if [[ ! -x "$analyzer" ]]; then + analyzer="$(command -v apkanalyzer || true)" +fi +if [[ -z "$analyzer" || ! -x "$analyzer" ]]; then + echo "apkanalyzer not found; leaving a diagnostic instead of guessing DEX shape" + printf 'apkanalyzer unavailable\n' > "$out/fieldir-$variant.txt" + exit 0 +fi +if "$analyzer" dex code --class com.example.artfieldwatch.FieldIRTarget "$apk" > "$out/fieldir-$variant.smali" 2> "$out/fieldir-$variant.stderr"; then + echo "-- FieldIRTarget actual DEX instructions, $variant --" + grep -E '^\.method|^[[:space:]]*\.method|iput|iget|invoke|return' "$out/fieldir-$variant.smali" | head -n 90 || true + echo "-- DEX dump saved in $out/fieldir-$variant.smali --" + # The release test must preserve both instructions in the *new* method. + # The old test() intentionally demonstrates release DEX simplification. + if [[ "$variant" == release ]]; then + awk '/^\.method public testViaIdentity\(I\)I/ { inside=1; next } + inside && /^\.end method/ { exit } + inside { print }' "$out/fieldir-$variant.smali" > "$out/fieldir-release-identity.smali" + if ! grep -q 'iput' "$out/fieldir-release-identity.smali" || + ! grep -q 'iget' "$out/fieldir-release-identity.smali"; then + echo "::error::Release DEX removed iget/iput from testViaIdentity; ART LSE cannot be tested with it." + cat "$out/fieldir-release-identity.smali" + exit 1 + fi + echo "Verified release testViaIdentity DEX retains both iput and iget." + awk '/^\.method.* p3CanaryOn\(/ { inside=1; next } + inside && /^\.end method/ { exit } + inside { print }' "$out/fieldir-$variant.smali" > "$out/fieldir-release-p3CanaryOn.smali" + if ! grep -q 'iput' "$out/fieldir-release-p3CanaryOn.smali" || + ! grep -q 'iget' "$out/fieldir-release-p3CanaryOn.smali"; then + echo "::error::P3 canary missing iput or iget in release DEX" + cat "$out/fieldir-release-p3CanaryOn.smali" + exit 1 + fi + if grep -q 'FieldEventSink' "$out/fieldir-release-p3CanaryOn.smali"; then + echo "::error::P3 canary must not call the native event sink" + exit 1 + fi + echo "Verified P3 canary has real field instructions without an explicit event sink." + # The template carrier must retain a genuine resolved native invoke + # alongside both field operations in the same DEX method. + awk '/^\.method.* p3TemplateCarrierOn\(/ { inside=1; next } + inside && /^\.end method/ { exit } + inside { print }' "$out/fieldir-$variant.smali" > "$out/fieldir-release-p3TemplateCarrierOn.smali" + if ! grep -q 'iput' "$out/fieldir-release-p3TemplateCarrierOn.smali" || + ! grep -q 'iget' "$out/fieldir-release-p3TemplateCarrierOn.smali" || + ! grep -q 'FieldEventSink;->recordInt(III)V' "$out/fieldir-release-p3TemplateCarrierOn.smali"; then + echo "::error::P3 template must retain iput, iget and a real recordInt invoke" + cat "$out/fieldir-release-p3TemplateCarrierOn.smali" + exit 1 + fi + echo "Verified P3 template DEX contains field operations and recordInt invoke." + # Separate loop fixtures should also preserve actual field reads in DEX. + # Otherwise JIT cannot be credited with eliminating them. + for method in exerciseOverwrites exerciseAlternating; do + awk -v method="$method" ' + $0 ~ "^\\.method.* " method "\\(I\\)I" { inside=1; next } + inside && /^\.end method/ { exit } + inside { print } + ' "$out/fieldir-$variant.smali" > "$out/fieldir-release-$method.smali" + if ! grep -q 'iput' "$out/fieldir-release-$method.smali" || + ! grep -q 'iget' "$out/fieldir-release-$method.smali"; then + echo "::error::Release DEX missing field iput/iget in $method" + cat "$out/fieldir-release-$method.smali" + exit 1 + fi + echo "Verified release DEX $method retains both iput and iget." + done + fi +else + echo "apkanalyzer failed; preserving stderr as diagnostic" + cat "$out/fieldir-$variant.stderr" + printf 'apkanalyzer failed\n' > "$out/fieldir-$variant.txt" +fi diff --git a/art-fieldwatch-phase1/ci/dex_field_sites.py b/art-fieldwatch-phase1/ci/dex_field_sites.py new file mode 100644 index 0000000..704222c --- /dev/null +++ b/art-fieldwatch-phase1/ci/dex_field_sites.py @@ -0,0 +1,237 @@ +#!/usr/bin/env python3 +"""Enumerate *every* concrete iget/iput/sget/sput in packaged APK DEX. + +Field IDs, method IDs and DEX PCs are scoped to a particular DexFile. +This is the identity catalog for an eventual generic ART compiler injector, +not an assertion that every DEX operation runs or survives optimization. +""" +import argparse +import bisect +import hashlib +import json +import struct +import zipfile +from pathlib import Path +from dex_method_index import u16, u32, uleb128 + +KINDS = ("int", "wide", "object", "boolean", "byte", "char", "short") +WIDTHS = {**{op: 1 for op in range(0x00, 0x100)}} +for op in (0x02,0x05,0x08,0x13,0x15,0x16,0x19,0x1a,0x1c,0x1f, + 0x20,0x22,0x23,0x29,0xfe,0xff): + WIDTHS[op] = 2 +for op in (0x03,0x06,0x09,0x14,0x17,0x1b,0x24,0x25,0x26,0x2a, + 0x2b,0x2c,0xfc,0xfd): + WIDTHS[op] = 3 +WIDTHS[0x18] = 5 +WIDTHS[0xfa] = WIDTHS[0xfb] = 4 +for first,last,width in ((0x2d,0x3d,2),(0x44,0x6d,2), + (0x6e,0x72,3),(0x74,0x78,3), + (0x90,0xaf,2),(0xd0,0xe2,2)): + for op in range(first,last+1): WIDTHS[op] = width +# Only legal DEX instructions are decoded. Reserved/odex opcodes fail closed. +RESERVED = set(range(0x3e,0x44)) | {0x73,0x79,0x7a} | set(range(0xe3,0xfa)) +FIELD_OPS = { + op: {"access": "instance" if op < 0x60 else "static", + "operation": "read" if (0x52 <= op <= 0x58 or 0x60 <= op <= 0x66) else "write", + "valueKind": KINDS[(op - (0x52 if op <= 0x58 else + 0x59 if op <= 0x5f else + 0x60 if op <= 0x66 else 0x67))]} + for op in range(0x52,0x6e) +} + +def sleb128(data,pos): + value=0 + for i in range(5): + if pos>=len(data): raise ValueError("truncated SLEB128") + b=data[pos]; pos+=1; value |= (b&0x7f) << (7*i) + if not b&0x80: + if b&0x40: value -= 1 << (7*(i+1)) + return value,pos + raise ValueError("oversized SLEB128") + +def insn_width(data, base, pc, count): + first=u16(data,base+2*pc) + op=first&255 + if op==0 and first: + marker=first>>8 + if marker==1: width=4+2*u16(data,base+2*(pc+1)) + elif marker==2: width=2+4*u16(data,base+2*(pc+1)) + elif marker==3: + size=u32(data,base+2*(pc+2)) + unit=u16(data,base+2*(pc+1)) + if unit not in (1,2,4,8): raise ValueError("bad array payload width") + width=4+(size*unit+1)//2 + else: raise ValueError(f"unknown DEX payload 0x{first:04x}") + else: + if op in RESERVED: raise ValueError(f"reserved opcode 0x{op:02x}") + width=WIDTHS[op] + if pc+width>count: raise ValueError("truncated DEX instruction") + return width + +def debug_lines(data, off): + if not off: return [] + line,off=uleb128(data,off) + params,off=uleb128(data,off) + for _ in range(params): _,off=uleb128(data,off) + addr=0 + positions=[(0,line)] + for _ in range(len(data)): + if off>=len(data): raise ValueError("unterminated DEX debug info") + op=data[off];off+=1 + if op==0: return positions + if op==1: + delta,off=uleb128(data,off);addr+=delta + elif op==2: + delta,off=sleb128(data,off);line+=delta + elif op in (3,4): + count=4 if op==4 else 3 + for __ in range(count): _,off=uleb128(data,off) + elif op in (5,6,9): + _,off=uleb128(data,off) + elif op in (7,8): pass + else: + shifted=op-10 + addr+=shifted//15 + line+=shifted%15-4 + positions.append((addr,line)) + raise ValueError("too many DEX debug operations") + +class Dex: + def __init__(self,data,name): + if len(data)<112 or data[:4]!=b"dex\n": raise ValueError("not a standard DEX") + self.data=data + self.name=name + self.shasum=hashlib.sha256(data).hexdigest() + self.strings_count,self.strings_off=u32(data,0x38),u32(data,0x3c) + self.types_count,self.types_off=u32(data,0x40),u32(data,0x44) + self.protos_count,self.protos_off=u32(data,0x48),u32(data,0x4c) + self.fields_count,self.fields_off=u32(data,0x50),u32(data,0x54) + self.methods_count,self.methods_off=u32(data,0x58),u32(data,0x5c) + self.classes_count,self.classes_off=u32(data,0x60),u32(data,0x64) + for n,off,stride in ((self.strings_count,self.strings_off,4), + (self.types_count,self.types_off,4), + (self.protos_count,self.protos_off,12), + (self.fields_count,self.fields_off,8), + (self.methods_count,self.methods_off,8), + (self.classes_count,self.classes_off,32)): + if n>len(data)//stride or off>len(data)-n*stride: + raise ValueError("DEX table bounds") + self.string_cache={} + def string(self,i): + if i>=self.strings_count: raise ValueError("string ID out of bounds") + if i not in self.string_cache: + offset=u32(self.data,self.strings_off+4*i) + _,pos=uleb128(self.data,offset) + end=self.data.find(b"\0",pos) + if end<0: raise ValueError("unterminated DEX string") + self.string_cache[i]=self.data[pos:end].decode("utf-8","replace") + return self.string_cache[i] + def typ(self,i): + if i>=self.types_count: raise ValueError("type ID out of bounds") + return self.string(u32(self.data,self.types_off+4*i)) + def field(self,i): + if i>=self.fields_count: raise ValueError("field ID out of bounds") + pos=self.fields_off+8*i + return {"fieldIndex":i,"declaringClass":self.typ(u16(self.data,pos)), + "fieldType":self.typ(u16(self.data,pos+2)), + "fieldName":self.string(u32(self.data,pos+4))} + def method(self,i): + if i>=self.methods_count: raise ValueError("method ID out of bounds") + pos=self.methods_off+8*i + return {"methodIndex":i,"methodClass":self.typ(u16(self.data,pos)), + "methodName":self.string(u32(self.data,pos+4)), + "prototypeIndex":u16(self.data,pos+2)} + def sites(self): + out=[] + for cls in range(self.classes_count): + pos=self.classes_off+cls*32 + class_type=self.typ(u32(self.data,pos)) + source_idx=u32(self.data,pos+16) + source=None if source_idx==0xffffffff else self.string(source_idx) + offset=u32(self.data,pos+24) + if not offset: continue + counts=[] + for _ in range(4): + n,offset=uleb128(self.data,offset) + if n>len(self.data): raise ValueError("class item count exceeds DEX") + counts.append(n) + for _ in range(counts[0]+counts[1]): + _,offset=uleb128(self.data,offset) + _,offset=uleb128(self.data,offset) + for count in counts[2:]: + method_idx=0 + for _ in range(count): + diff,offset=uleb128(self.data,offset) + method_idx+=diff + _,offset=uleb128(self.data,offset) + code,offset=uleb128(self.data,offset) + if not code: continue + if method_idx>=self.methods_count: raise ValueError("method index OOB") + debug=u32(self.data,code+8) + insns=u32(self.data,code+12) + base=code+16 + if insns>(len(self.data)-base)//2: + raise ValueError("code item instruction extent OOB") + positions=debug_lines(self.data,debug) + pc=0 + method=self.method(method_idx) + if method["methodClass"]!=class_type: raise ValueError("class method mismatch") + while pc=0: line=positions[k][1] + out.append({**method,**self.field(field_idx), + **FIELD_OPS[op],"dexPc":pc, + "sourceFile":source,"sourceLine":line, + "opcode":f"0x{op:02x}"}) + pc+=width + return out + +def inventory(apk): + with zipfile.ZipFile(apk) as z: + names=sorted(n for n in z.namelist() if n=="classes.dex" or + (n.startswith("classes") and n.endswith(".dex") and n[7:-4].isdigit())) + if not names: raise ValueError("APK has no DEX") + dex_files=[] + for dex_id,name in enumerate(names): + dex=Dex(z.read(name),name) + sites=dex.sites() + dex_files.append({"dexId":dex_id,"name":name,"sha256":dex.shasum, + "fieldAccesses":sites,"count":len(sites)}) + return {"schemaVersion":1,"apk":Path(apk).name, + "totalFieldSites":sum(d["count"] for d in dex_files), + "dexFiles":dex_files} + +def self_test(): + assert FIELD_OPS[0x52]=={"access":"instance","operation":"read","valueKind":"int"} + assert FIELD_OPS[0x5a]["valueKind"]=="wide" + assert FIELD_OPS[0x60]["access"]=="static" + assert FIELD_OPS[0x6d]=={"access":"static","operation":"write","valueKind":"short"} + assert insn_width(b"\x52\x00\x03\x00",0,0,2)==2 + assert insn_width(b"\x00\x01\x02\x00"+b"\0"*12,0,0,8)==8 + assert insn_width(b"\x00\x03\x02\x00\x03\x00\x00\x00"+b"\0"*6,0,0,7)==7 + try: insn_width(b"\x52\x00",0,0,1) + except ValueError: pass + else: raise AssertionError("truncated field instruction accepted") + print("dex_field_sites self-test OK") + +if __name__=="__main__": + parser=argparse.ArgumentParser() + parser.add_argument("apk",nargs="?") + parser.add_argument("--self-test",action="store_true") + parser.add_argument("--output",type=Path) + args=parser.parse_args() + if args.self_test: + self_test() + else: + if not args.apk: parser.error("APK argument required") + result=inventory(args.apk) + payload=json.dumps(result,indent=2,sort_keys=True) + if args.output: args.output.write_text(payload+"\n") + else: print(payload) + print(f"Indexed {result['totalFieldSites']} field sites across {len(result['dexFiles'])} DEX files",file=__import__("sys").stderr) diff --git a/art-fieldwatch-phase1/ci/dex_method_index.py b/art-fieldwatch-phase1/ci/dex_method_index.py new file mode 100644 index 0000000..650f9bf --- /dev/null +++ b/art-fieldwatch-phase1/ci/dex_method_index.py @@ -0,0 +1,267 @@ +#!/usr/bin/env python3 +"""Find the fixture sink's DEX method ID without Android framework dependencies. + +A method index is scoped to its DexFile. This is *not* proof that an arbitrary +ART invoke points at the sink; it must be joined with the compiled DexFile and +the exact DEX PC before constructing or cloning a compiler invoke. +""" +import hashlib +import json +import struct +import sys +import zipfile +from pathlib import Path + +SINK_CLASS = "Lcom/example/artfieldwatch/FieldEventSink;" +SINK_NAME = "recordInt" +SINK_PROTO = "(III)V" + + +def u16(data, pos): + if pos < 0 or pos + 2 > len(data): + raise ValueError("DEX u16 out of bounds") + return struct.unpack_from(" len(data): + raise ValueError("DEX u32 out of bounds") + return struct.unpack_from("= len(data): + raise ValueError("truncated DEX ULEB128") + byte = data[pos + n] + value |= (byte & 0x7f) << (7 * n) + if not (byte & 0x80): + return value, pos + n + 1 + raise ValueError("oversized DEX ULEB128") + + +def sink_method_index(data): + if len(data) < 0x70 or data[:4] != b"dex\n": + raise ValueError("not a DEX file") + strings_count, strings_off = u32(data, 0x38), u32(data, 0x3c) + types_count, types_off = u32(data, 0x40), u32(data, 0x44) + protos_count, protos_off = u32(data, 0x48), u32(data, 0x4c) + methods_count, methods_off = u32(data, 0x58), u32(data, 0x5c) + for count, off, stride in [(strings_count, strings_off, 4), + (types_count, types_off, 4), + (protos_count, protos_off, 12), + (methods_count, methods_off, 8)]: + if count > len(data) // stride or off > len(data) - count * stride: + raise ValueError("invalid DEX table bounds") + cache = {} + + def string(idx): + if idx >= strings_count: + raise ValueError("invalid DEX string ID") + if idx not in cache: + off = u32(data, strings_off + 4 * idx) + _, start = uleb128(data, off) + end = data.find(b"\0", start) + if end < 0: + raise ValueError("unterminated DEX string") + # Java descriptors and method names are ASCII even though + # general DEX strings use modified UTF-8. + cache[idx] = data[start:end].decode("ascii") + return cache[idx] + + def descriptor(idx): + if idx >= types_count: + raise ValueError("invalid DEX type ID") + return string(u32(data, types_off + 4 * idx)) + + def signature(idx): + if idx >= protos_count: + raise ValueError("invalid DEX proto ID") + item = protos_off + 12 * idx + result = descriptor(u32(data, item + 4)) + params_off = u32(data, item + 8) + args = "" + if params_off: + n = u32(data, params_off) + if n > len(data) // 2 or params_off + 4 + 2*n > len(data): + raise ValueError("invalid DEX parameter list") + args = "".join(descriptor(u16(data, params_off + 4 + 2*i)) + for i in range(n)) + return "(" + args + ")" + result + + found = [] + for idx in range(methods_count): + pos = methods_off + 8 * idx + class_idx = u16(data, pos) + proto_idx = u16(data, pos + 2) + name_idx = u32(data, pos + 4) + if descriptor(class_idx) == SINK_CLASS and string(name_idx) == SINK_NAME: + if signature(proto_idx) != SINK_PROTO: + raise ValueError("sink name found but prototype mismatches") + found.append(idx) + if len(found) != 1: + raise ValueError(f"expected one sink DEX method ID, found {len(found)}") + return found[0] + + +def canary_pcs(data, sink_idx): + """Return exact code-unit PCs for one iget and sink invoke in carrier.""" + types_count, types_off = u32(data, 0x40), u32(data, 0x44) + strings_count, strings_off = u32(data, 0x38), u32(data, 0x3c) + methods_off = u32(data, 0x5c) + classes_count, classes_off = u32(data, 0x60), u32(data, 0x64) + + def string(idx): + if idx >= strings_count: + raise ValueError("bad string ID") + off = u32(data, strings_off + 4 * idx) + _, pos = uleb128(data, off) + end = data.find(b"\0", pos) + if end < 0: + raise ValueError("bad string terminator") + return data[pos:end].decode("ascii") + + def descriptor(idx): + if idx >= types_count: + raise ValueError("bad type ID") + return string(u32(data, types_off + 4 * idx)) + + target = "Lcom/example/artfieldwatch/FieldIRTarget;" + found = [] + for j in range(classes_count): + pos = classes_off + 32 * j + if descriptor(u32(data, pos)) != target: + continue + off = u32(data, pos + 24) + if off == 0: + raise ValueError("missing field target class data") + counts = [] + for _ in range(4): + n, off = uleb128(data, off) + counts.append(n) + if any(n > len(data) for n in counts): + raise ValueError("invalid class member count") + for _ in range(counts[0] + counts[1]): + _, off = uleb128(data, off) + _, off = uleb128(data, off) + for group, n in enumerate(counts[2:]): + method_index = 0 + for _ in range(n): + diff, off = uleb128(data, off) + method_index += diff + _, off = uleb128(data, off) + code_off, off = uleb128(data, off) + name_idx = u32(data, methods_off + method_index * 8 + 4) + if string(name_idx) != "p3TemplateCarrierOn": + continue + if code_off == 0: + raise ValueError("P3 carrier has no DEX code") + insn_count = u32(data, code_off + 12) + insns_start = code_off + 16 + if insn_count > len(data) // 2 or insns_start + 2*insn_count > len(data): + raise ValueError("invalid P3 carrier code bounds") + candidates_set = [] + candidates_get = [] + candidates_invoke = [] + for pc in range(insn_count): + op = u16(data, insns_start + pc*2) & 0xff + if op == 0x59: + candidates_set.append(pc) + if op == 0x52: + candidates_get.append(pc) + if op in (0x71, 0x77) and pc+1 < insn_count: + method_id = u16(data, insns_start+(pc+1)*2) + if method_id == sink_idx: + candidates_invoke.append(pc) + if (len(candidates_set)!=1 or len(candidates_get)!=1 or + len(candidates_invoke)!=2 or + not (candidates_set[0] < candidates_invoke[0] < + candidates_get[0] < candidates_invoke[1])): + raise ValueError(f"bad P3 templates: sets={candidates_set} gets={candidates_get} invokes={candidates_invoke}") + put_field = u16(data, insns_start + 2*(candidates_set[0] + 1)) + get_field = u16(data, insns_start + 2*(candidates_get[0] + 1)) + if put_field != get_field: + raise ValueError("P3 template accesses different DEX fields") + found.append({"carrierMethodIndex":method_index, + "fieldIndex":put_field, + "setDexPc":candidates_set[0], + "writeInvokeDexPc":candidates_invoke[0], + "getDexPc":candidates_get[0], + "readInvokeDexPc":candidates_invoke[1]}) + if len(found) != 1: + raise ValueError(f"expected one P3 carrier method, found {len(found)}") + return found[0] + + +def apk_sink_method(apk): + with zipfile.ZipFile(apk) as archive: + dex_names = sorted(x for x in archive.namelist() + if x == "classes.dex" or + (x.startswith("classes") and x.endswith(".dex") and + x[7:-4].isdigit())) + matches = [] + for dex_id, name in enumerate(dex_names): + data = archive.read(name) + try: + idx = sink_method_index(data) + except ValueError as e: + if "expected one sink DEX method ID, found 0" in str(e): + continue + raise + try: + pcs = canary_pcs(data, idx) + except ValueError as e: + if "expected one P3 carrier method, found 0" in str(e): + continue + raise + matches.append({"dex": name, "dexId":dex_id, + "methodIndex": idx, + **pcs, + "sha256": hashlib.sha256(data).hexdigest()}) + if len(matches) != 1: + raise ValueError(f"expected one fixture sink in APK, found {len(matches)}") + return matches[0] + + +def self_test(): + strings = [SINK_CLASS, SINK_NAME, "I", "V"] + data = bytearray(1024) + data[:8] = b"dex\n035\0" + strings_off, types_off, protos_off, methods_off = 0x100, 0x120, 0x140, 0x160 + for base, count_off, offset_off, count in [ + (strings_off, 0x38, 0x3c, len(strings)), + (types_off, 0x40, 0x44, 3), + (protos_off, 0x48, 0x4c, 1), + (methods_off, 0x58, 0x5c, 1)]: + struct.pack_into(" | --self-test") diff --git a/art-fieldwatch-phase1/ci/resolve_field_events.py b/art-fieldwatch-phase1/ci/resolve_field_events.py new file mode 100644 index 0000000..a2ff30e --- /dev/null +++ b/art-fieldwatch-phase1/ci/resolve_field_events.py @@ -0,0 +1,169 @@ +#!/usr/bin/env python3 +"""Strictly join executed ART field events with the *packaged* DEX site catalog. + +The tuple (dexId, methodId, fieldId, dexPc, read/write) is authoritative. +Never infer a field name from event order, field index alone, or a method name. +Field values are the original event bit patterns, not a second field read. +""" +import argparse +import json +import re +from pathlib import Path + +VALUE_TYPES = {"Z": 1, "B": 2, "C": 3, "S": 4, "I": 5, + "J": 6, "F": 7, "D": 8} +KIND = {1: "read", 2: "write"} +BITS = re.compile(r"0x[0-9a-fA-F]{16}\Z") + + +def _type_id(descriptor): + if not isinstance(descriptor, str) or not descriptor: + raise ValueError(f"invalid DEX field descriptor {descriptor!r}") + return VALUE_TYPES.get(descriptor, 9 if descriptor[0] in ("L", "[") else 0) + + +def _signed(value, bits): + mask = (1 << bits) - 1 + value &= mask + return value - (1 << bits) if value & (1 << (bits - 1)) else value + + +def resolve(inventory, snapshot): + if inventory.get("schemaVersion") != 1: + raise ValueError("unsupported DEX catalog version") + if snapshot.get("version") != 2: + raise ValueError("unsupported native event ABI version") + dexes = {} + sites = {} + for dex in inventory.get("dexFiles", []): + dex_id = dex.get("dexId") + if not isinstance(dex_id, int) or dex_id < 0 or dex_id in dexes: + raise ValueError("invalid or repeated DEX ID") + if not isinstance(dex.get("sha256"), str) or len(dex["sha256"]) != 64: + raise ValueError("missing DEX SHA-256") + dexes[dex_id] = dex + if dex.get("count") != len(dex.get("fieldAccesses", [])): + raise ValueError("DEX field-site count mismatch") + for site in dex["fieldAccesses"]: + direction = site.get("operation") + kind = {"read": 1, "write": 2}.get(direction) + key = (dex_id, site.get("methodIndex"), site.get("fieldIndex"), + site.get("dexPc"), kind) + if kind is None or key in sites or not all(isinstance(n, int) for n in key): + raise ValueError(f"ambiguous DEX site identity {key}") + sites[key] = (dex, site) + if inventory.get("totalFieldSites") != len(sites): + raise ValueError("APK-wide field-site count mismatch") + events = snapshot.get("events", []) + if snapshot.get("total") != len(events) or snapshot.get("dropped") != 0: + raise ValueError("incomplete, dropped or truncated event snapshot") + resolved = [] + for index, event in enumerate(events): + if event.get("seq") != index + 1: + raise ValueError("non-contiguous event sequence") + key = tuple(event.get(k) for k in + ("dexId", "methodId", "fieldId", "dexPc", "kind")) + if key not in sites: + raise ValueError(f"event {index + 1} has no matching DEX field instruction: {key}") + dex, site = sites[key] + type_id = _type_id(site["fieldType"]) + if type_id == 0 or event.get("type") != type_id: + raise ValueError(f"event {index + 1} type does not match DEX field descriptor") + bits = event.get("valueBits") + if not isinstance(bits, str) or not BITS.fullmatch(bits): + raise ValueError(f"event {index + 1} has invalid 64-bit value encoding") + value_bits = int(bits, 16) + # The direct 6-int JNI ABI sign-extends to 64 bits, preserving negative ints. + # Floating point values retain raw IEEE bits, with no precision-losing JSON floats. + value = None + if type_id in (1, 2, 3, 4, 5): + width = {1: 1, 2: 8, 3: 16, 4: 16, 5: 32}[type_id] + if type_id == 1: + if value_bits not in (0, 1): + raise ValueError("invalid boolean bit value") + value = bool(value_bits) + elif type_id == 3: + if value_bits > 0xFFFF: + raise ValueError("invalid unsigned Java char") + value = value_bits + else: + value = _signed(value_bits, width) + if value_bits != (value & ((1 << 64) - 1)): + raise ValueError("invalid signed narrow-primitive extension") + elif type_id == 6: + value = _signed(value_bits, 64) + # Never claim an object identity or dereference an opaque reference token. + resolved.append({ + "seq": index + 1, + "dexId": key[0], "dexName": dex["name"], "dexSha256": dex["sha256"], + "methodId": key[1], "methodClass": site["methodClass"], + "methodName": site["methodName"], "prototypeIndex": site["prototypeIndex"], + "fieldId": key[2], "declaringClass": site["declaringClass"], + "fieldName": site["fieldName"], "fieldType": site["fieldType"], + "access": site["access"], "operation": KIND[key[4]], + "dexPc": key[3], "sourceFile": site["sourceFile"], + "sourceLine": site["sourceLine"], "valueType": type_id, + "valueBits": f"0x{value_bits:016x}", "value": value, + }) + return {"schemaVersion": 1, "apk": inventory.get("apk"), + "eventCount": len(resolved), "events": resolved} + + +def self_test(): + sha = "a" * 64 + def site(method, field, pc, operation, typ="I", access="instance"): + return {"methodIndex": method, "fieldIndex": field, "dexPc": pc, + "operation": operation, "access": access, "fieldType": typ, + "methodClass": "Lexample/Caller;", "methodName": "hot", + "prototypeIndex": 2, "declaringClass": "Lexample/Data;", + "fieldName": "watched", "sourceFile": "Caller.java", + "sourceLine": 17} + inv = {"schemaVersion": 1, "apk": "test.apk", "totalFieldSites": 3, + "dexFiles": [{"dexId": 0, "name": "classes.dex", "sha256": sha, + "count": 3, "fieldAccesses": [ + site(1, 2, 3, "write"), + site(1, 2, 4, "read"), + site(1, 9, 8, "write", "J", "static")]}]} + def ev(seq, field, pc, kind, typ, bits): + return {"seq": seq, "dexId": 0, "methodId": 1, "fieldId": field, + "dexPc": pc, "kind": kind, "type": typ, "valueBits": bits} + snapshot = {"version": 2, "total": 3, "dropped": 0, "events": [ + ev(1, 2, 3, 2, 5, "0xfffffffffffffff5"), + ev(2, 2, 4, 1, 5, "0xfffffffffffffff5"), + ev(3, 9, 8, 2, 6, "0x8000000000000000")]} + result = resolve(inv, snapshot) + assert result["eventCount"] == 3 + assert [e["value"] for e in result["events"]] == [ + -11, -11, -(1 << 63)] + assert result["events"][2]["access"] == "static" + for key, bad in (("kind", 1), ("fieldId", 999), ("dexPc", 99), + ("type", 7), ("valueBits", "garbage")): + old = snapshot["events"][0][key] + snapshot["events"][0][key] = bad + try: + resolve(inv, snapshot) + except ValueError: + pass + else: + raise AssertionError(f"invalid {key} event accepted") + snapshot["events"][0][key] = old + print("strict DEX field-event resolver self-test passed") + + +if __name__ == "__main__": + cli = argparse.ArgumentParser() + cli.add_argument("--inventory", type=Path) + cli.add_argument("--events", type=Path) + cli.add_argument("--output", type=Path) + cli.add_argument("--self-test", action="store_true") + args = cli.parse_args() + if args.self_test: + self_test() + else: + if not all((args.inventory, args.events, args.output)): + cli.error("--inventory, --events and --output are required") + catalog = json.loads(args.inventory.read_text()) + snapshot = json.loads(args.events.read_text()) + result = resolve(catalog, snapshot) + args.output.write_text(json.dumps(result, indent=2) + "\n") + print(f"Resolved {result['eventCount']} field events with strict DEX identities") diff --git a/art-fieldwatch-phase1/ci/run-emulator-smoke.sh b/art-fieldwatch-phase1/ci/run-emulator-smoke.sh new file mode 100644 index 0000000..fe36350 --- /dev/null +++ b/art-fieldwatch-phase1/ci/run-emulator-smoke.sh @@ -0,0 +1,70 @@ +#!/usr/bin/env bash +set -euo pipefail +mkdir -p "${ARTWATCH_LOG_DIR:-/tmp/artwatch-logs}" +# adbd restarts when switching to root. A just-booted API33 emulator can +# briefly close the transport, returning "unable to connect for root: closed". +# Retry only the setup operation; never mask errors from the test workload. +root_ready=0 +for attempt in 1 2 3 4 5 6 7 8; do + if adb root && adb wait-for-device; then + uid="$(adb shell id -u 2>/dev/null | tr -d '\r' || true)" + if [[ "$uid" == 0 ]]; then + root_ready=1 + break + fi + fi + echo "::warning::adbd root not ready (attempt $attempt/8)" + sleep 3 +done +if [[ "$root_ready" -ne 1 ]]; then + echo "::error::Android emulator did not stabilize in root mode" + adb devices -l || true + exit 1 +fi +variant="${ARTWATCH_BUILD_VARIANT:-debug}" +case "$variant" in + debug|release) ;; + *) echo "Invalid APK variant: $variant" >&2; exit 1 ;; +esac +apk="art-fieldwatch-phase1/test/app/build/outputs/apk/$variant/app-$variant.apk" +test -f "$apk" || { echo "APK not found: $apk" >&2; exit 1; } +adb install -r "$apk" +FRIDA_VERSION="${FRIDA_VERSION:-17.27.1}" +ABI="$(adb shell getprop ro.product.cpu.abi | tr -d '\r')" +case "$ABI" in + x86_64) FRIDA_ARCH=x86_64 ;; + arm64-v8a) FRIDA_ARCH=arm64 ;; + x86) FRIDA_ARCH=x86 ;; + armeabi-v7a) FRIDA_ARCH=arm ;; + *) echo "Unsupported emulator ABI: $ABI" >&2; exit 1 ;; +esac +curl --fail --location --retry 3 "https://github.com/frida/frida/releases/download/$FRIDA_VERSION/frida-server-$FRIDA_VERSION-android-$FRIDA_ARCH.xz" --output /tmp/frida-server.xz +xz -df /tmp/frida-server.xz +adb push /tmp/frida-server /data/local/tmp/frida-server +adb shell chmod 755 /data/local/tmp/frida-server +adb shell '(/data/local/tmp/frida-server >/data/local/tmp/artwatch-frida-server.log 2>&1 < /dev/null &)' +# Check that frida-server actually survives startup. +ready=0 +for i in $(seq 1 12); do + if adb shell pidof frida-server >/dev/null 2>&1; then ready=1; break; fi + sleep 2 +done +if [ "$ready" -ne 1 ]; then + echo "Frida server is not running" + adb shell cat /data/local/tmp/artwatch-frida-server.log || true + exit 1 +fi +if [[ "${ARTWATCH_SHADOW_SHIM:-0}" == 1 ]]; then + # The app uses System.loadLibrary() from its packaged nativeLibraryDir; + # never attempt executable mappings from /data/local/tmp in an app context. + unzip -l "$apk" | grep -q "lib/x86_64/libartwatch_shadow.so" || + { echo "Native shim missing from APK" >&2; exit 1; } +fi +# Pull ART ELF files for offline symbol inspection; never scan their full +# symbol tables inside the injected application. +bash art-fieldwatch-phase1/ci/art-binary-inventory.sh || true +if ! python3 art-fieldwatch-phase1/ci/smoke_test.py; then + adb shell cat /data/local/tmp/artwatch-frida-server.log || true + adb logcat -d -t 1500 > "$ARTWATCH_LOG_DIR/logcat-failure.txt" || true + exit 1 +fi diff --git a/art-fieldwatch-phase1/ci/smoke_test.py b/art-fieldwatch-phase1/ci/smoke_test.py new file mode 100644 index 0000000..da18bc6 --- /dev/null +++ b/art-fieldwatch-phase1/ci/smoke_test.py @@ -0,0 +1,744 @@ +#!/usr/bin/env python3 +"""Frida + Android fixture integration smoke, NOT field-hook coverage.""" +import json +import os +import subprocess +import sys +import time +from pathlib import Path +import frida +from resolve_field_events import resolve + +BASE = Path(__file__).resolve().parents[1] +LOG_DIR = Path(os.environ.get('ARTWATCH_LOG_DIR','/tmp/artwatch-logs')) +LOG_DIR.mkdir(parents=True,exist_ok=True) +messages, errors = [], [] + +def record(kind,content): + messages.append({'kind':kind,'text':str(content)}) + print(f'[{kind}] {content}',flush=True) + +def on_message(message,data): + if message.get('type') == 'error': + errors.append(message.get('stack') or message.get('description') or str(message)) + record('error',errors[-1]) + else: + record('frida',json.dumps(message,sort_keys=True)) + +def main(): + device = frida.get_usb_device(timeout=30) + record('host','frida-device='+device.name) + record('host','frida-process-count='+str(len(device.enumerate_processes()))) + pid = device.spawn(['com.example.artfieldwatch']) + record('host','spawned-pid='+str(pid)) + session = device.attach(pid) + runtime_snapshot = None + p3_snapshot = None + field_snapshot = None + direct_abi_snapshot = None + jvmti_snapshot = None + try: + source = (BASE/'jit-boundary-probe.js').read_text() + sink_inventory = LOG_DIR / ('p3-sink-method-' + + os.environ.get('ARTWATCH_BUILD_VARIANT','debug') + + '.json') + if sink_inventory.is_file() and os.environ.get('ARTWATCH_SHADOW_SHIM') == '1': + sink_info = json.loads(sink_inventory.read_text()) + if not str(sink_info.get('dex','')).startswith('classes'): + raise AssertionError('P3 sink was not found in a packaged DEX') + source = ('globalThis.__artwatchP3Fixture = ' + + json.dumps(sink_info) + ';\n' + + 'globalThis.__artwatchP3Inject = ' + + json.dumps(os.environ.get('ARTWATCH_P3_INJECT') == '1') + + ';\n' + source) + if os.environ.get('ARTWATCH_SHADOW_SHIM') == '1': + source = ('globalThis.__artwatchShadowPath = ' + + json.dumps('libartwatch_shadow.so') + + ';\n' + source) + script = session.create_script(source) + script.on('message',on_message) + script.set_log_handler(lambda level, line: record('console-'+level, line)) + script.load() + device.resume(pid) + # Staged release warmup gives natural JIT workers time to compile + # all three independently hot field-read/write workloads. + time.sleep(30 if os.environ.get('ARTWATCH_BUILD_VARIANT') == 'release' else 20) + if os.environ.get('ARTWATCH_SHADOW_SHIM') == '1': + runtime_snapshot = script.exports_sync.runtimeevents() + direct_abi_snapshot = script.exports_sync.fieldmeta() + if os.environ.get('ARTWATCH_BUILD_VARIANT','debug') == 'debug': + jvmti_snapshot = script.exports_sync.jvmtievents() + (LOG_DIR/'jvmti-events.json').write_text( + json.dumps(jvmti_snapshot,indent=2)) + record('host',f'JVMTI watched={jvmti_snapshot.get("watched")} ' + f'events={jvmti_snapshot.get("total")}') + (LOG_DIR/'direct-abi-events.json').write_text( + json.dumps(direct_abi_snapshot,indent=2)) + if os.environ.get('ARTWATCH_P3_INJECT') == '1': + p3_snapshot = script.exports_sync.p3events() + field_snapshot = script.exports_sync.p3fieldmeta() + (LOG_DIR/'p3-field-metadata.json').write_text( + json.dumps(field_snapshot,indent=2)) + record('host',f'P3 metadata events ready={field_snapshot.get("ready")} ' + f'total={field_snapshot.get("total")}') + (LOG_DIR/'p3-injected-events.json').write_text( + json.dumps(p3_snapshot,indent=2)) + record('host',f'P3 compiled events ready={p3_snapshot.get("ready")} ' + f'total={p3_snapshot.get("total")} ' + f'dropped={p3_snapshot.get("dropped")}') + (LOG_DIR/'runtime-events.json').write_text( + json.dumps(runtime_snapshot,indent=2)) + record('host',f'Native runtime events ready={runtime_snapshot.get("ready")} ' + f'total={runtime_snapshot.get("total")} ' + f'dropped={runtime_snapshot.get("dropped")}') + finally: + try: session.detach() + except frida.InvalidOperationError: pass + logs = subprocess.run(['adb','logcat','-d','-s','ARTWATCH_CI:I','*:S'], + capture_output=True,text=True,check=False) + (LOG_DIR/'logcat.txt').write_text(logs.stdout+logs.stderr) + (LOG_DIR/'frida-messages.json').write_text(json.dumps(messages,indent=2)) + text = '\n'.join(m['text'] for m in messages) + if 'module=libart' not in text: raise AssertionError('libart not discovered') + if 'arch=' not in text: raise AssertionError('No Frida process header') + if errors: raise AssertionError('Frida errors: '+'; '.join(errors)) + variant = os.environ.get('ARTWATCH_BUILD_VARIANT','debug') + expected_debug = 'true' if variant == 'debug' else 'false' + if f'APP_DEBUGGABLE={expected_debug}' not in logs.stdout: + raise AssertionError(f'Unexpected app debuggable flag for {variant} build') + if os.environ.get('ARTWATCH_SHADOW_SHIM') == '1': + if 'SHADOW_LIB_LOADED=true' not in logs.stdout or ( + 'EVENT_LIB_LOADED=true' not in logs.stdout): + raise AssertionError('App failed to load packaged native observer/event libraries') + p3_inject = os.environ.get('ARTWATCH_P3_INJECT') == '1' + if p3_inject: + template_marker = 'P3_TEMPLATE_DONE count=256 checksum=25280 nullCheck=true injected=true' + else: + template_marker = 'P3_TEMPLATE_DONE count=0 checksum=25280 nullCheck=true injected=false' + if template_marker not in logs.stdout: + raise AssertionError('P3 compiler-insertion result mismatch: ' + template_marker) + if p3_inject: + if not p3_snapshot or p3_snapshot.get('ready') is not True or ( + p3_snapshot.get('total') != 256 or p3_snapshot.get('dropped') != 0): + raise AssertionError(f'Independent P3 runtime snapshot unavailable: {p3_snapshot}') + p3_events = p3_snapshot.get('events',[]) + if len(p3_events) != 256: + raise AssertionError(f'Expected 256 P3 events, got {len(p3_events)}') + for i in range(128): + expected = 7 + 3 * i + write, read = p3_events[2*i], p3_events[2*i+1] + if write != {'seq':2*i+1,'site':9001,'kind':2,'value':expected}: + raise AssertionError(f'P3 incorrect write event at {i}: {write}') + if read != {'seq':2*i+2,'site':9002,'kind':1,'value':expected}: + raise AssertionError(f'P3 incorrect read event at {i}: {read}') + if not field_snapshot or field_snapshot.get('ready') is not True: + raise AssertionError('P3 detailed event metadata snapshot unavailable') + fixture = json.loads((LOG_DIR / ( + 'p3-sink-method-' + variant + '.json')).read_text()) + records = field_snapshot.get('events', []) + if field_snapshot.get('total') != 256 or ( + field_snapshot.get('dropped') != 0 or len(records) != 256): + raise AssertionError('P3 field metadata event count/drops invalid') + for i in range(128): + expected = 7 + 3*i + for ordinal, kind, pc in ( + (2*i, 2, fixture['setDexPc']), + (2*i+1, 1, fixture['getDexPc'])): + e = records[ordinal] + expected_bits = f'0x{expected:016x}' + if (e.get('seq') != ordinal+1 or + e.get('dexId') != fixture['dexId'] or + e.get('methodId') != fixture['carrierMethodIndex'] or + e.get('fieldId') != fixture['fieldIndex'] or + e.get('dexPc') != pc or e.get('kind') != kind or + e.get('type') != 5 or e.get('valueBits') != expected_bits): + raise AssertionError(f'P3 metadata/value mismatch: {e}') + catalog = json.loads((LOG_DIR / ( + 'field-sites-' + variant + '.json')).read_text()) + resolved_p3 = resolve(catalog, field_snapshot) + (LOG_DIR/'p3-resolved-field-events.json').write_text( + json.dumps(resolved_p3,indent=2)) + if resolved_p3['eventCount'] != 256: + raise AssertionError('P3 full DEX metadata resolution lost field events') + for event in resolved_p3['events']: + if (event['methodClass'] != + 'Lcom/example/artfieldwatch/FieldIRTarget;' or + event['methodName'] != 'p3TemplateCarrierOn' or + event['declaringClass'] != + 'Lcom/example/artfieldwatch/FieldIRTarget;' or + event['fieldName'] != 'value' or + event['fieldType'] != 'I' or + event['access'] != 'instance'): + raise AssertionError(f'P3 runtime identity resolved to wrong DEX site: {event}') + record('host','PASS: 256 runtime P3 records resolved to exact ' + 'DEX caller class/method, field name/type, and source metadata') + record('host','PASS: 256 field events joined to exact DEX method, ' + 'field, PC, direction, int type and value bits') + record('host','PASS: independently archived 256 P3 injected-context ' + 'events with exact values/order and zero drops') + if logs.stdout.index(template_marker) >= logs.stdout.find('P3_CANARY_DONE'): + raise AssertionError('P3 template did not run before the silent canary') + canary_marker = 'P3_CANARY_DONE count=0 checksum=25280 nullCheck=true' + if canary_marker not in logs.stdout: + raise AssertionError('P3 raw-field canary must produce zero native events') + if logs.stdout.index(canary_marker) >= logs.stdout.find('RUNTIME_EVENTS_DONE'): + raise AssertionError('P3 negative control did not precede the P2 fixture') + if 'DIRECT_ABI_DONE count=4 checksum=103' not in logs.stdout or ( + 'PRIMITIVE_ABI_DONE count=14 checksum=61' not in logs.stdout): + raise AssertionError('Primitive ABI completion markers missing') + if variant == 'debug': + if 'JVMTI_ATTACH=true' not in logs.stdout: + raise AssertionError('JVMTI agent did not attach') + if 'JVMTI_NO_TEMPLATE_DONE checksum=32' not in logs.stdout: + raise AssertionError('No-template field workload failed') + if not jvmti_snapshot or jvmti_snapshot.get('ready') is not True: + raise AssertionError('JVMTI snapshot unavailable') + if jvmti_snapshot.get('watched',0) < 2: + raise AssertionError('JVMTI watched fewer than two fields') + events_jvmti = jvmti_snapshot.get('events', []) + if not {1,2}.issubset({e.get('kind') for e in events_jvmti}): + raise AssertionError('JVMTI missing field read/write events') + if not {'instanceValue','staticValue'}.issubset( + {e.get('field') for e in events_jvmti}): + raise AssertionError('JVMTI missing instance/static fields') + if 'exercise' not in {e.get('method') for e in events_jvmti}: + raise AssertionError('JVMTI caller method missing') + record('host','PASS: no-template instance and static field ' + 'read/write callbacks with method/field identities') + if 'DIRECT_ABI_DONE count=4 checksum=103' not in logs.stdout: + raise AssertionError('Direct six-int native ABI fixture failed') + if not direct_abi_snapshot or direct_abi_snapshot.get('ready') is not True: + raise AssertionError('Direct six-int native ABI snapshot unavailable') + records_abi = direct_abi_snapshot.get('events',[]) + values_abi = [(-11,2,17,3,7),(-11,1,17,3,9), + (42,2,18,4,11),(42,1,18,4,13)] + long_bits = (-0x102030405060708) & ((1<<64)-1) + values_abi.extend([ + (0,5,21,2,2,6,long_bits), + (0,5,21,4,1,6,long_bits), + (0,5,22,6,2,7,0x80000000), + (0,5,22,8,1,7,0x80000000), + (0,5,23,10,2,8,0x8000000000000000), + (0,5,23,12,1,8,0x8000000000000000), + (0,6,24,14,1,1,1), + (0,6,25,16,2,2,(1<<64)-128), + (0,6,26,18,1,3,0xd7ff), + (0,6,27,20,2,4,(1<<64)-32768) + ]) + if direct_abi_snapshot.get('total') != 14 or ( + direct_abi_snapshot.get('dropped') != 0 or len(records_abi) != 14): + raise AssertionError('Direct primitive JNI ABI count mismatch') + for i,row in enumerate(values_abi): + if len(row) == 5: + value,kind,field_id,method_id,dex_pc = row + row = (0,method_id,field_id,dex_pc,kind,5,value & ((1<<64)-1)) + dex_id,method_id,field_id,dex_pc,kind,typ,bits = row + expected_abi = { + 'seq':i+1,'dexId':dex_id,'methodId':method_id,'fieldId':field_id, + 'dexPc':dex_pc,'kind':kind,'type':typ, + 'valueBits':f'0x{bits:016x}'} + if records_abi[i] != expected_abi: + raise AssertionError(f'Direct primitive JNI ABI record invalid: {records_abi[i]}') + record('host','PASS: 14 exact primitive JNI field records including ' + 'negative long, negative-zero float/double, boolean, byte, char, short') + if 'RUNTIME_EVENTS_DONE count=256' not in logs.stdout or ( + 'nullCheck=true' not in logs.stdout): + raise AssertionError('Native runtime field event workload did not complete') + if not runtime_snapshot or runtime_snapshot.get('ready') is not True: + raise AssertionError(f'Native runtime event snapshot unavailable: {runtime_snapshot}') + observed = runtime_snapshot.get('events',[]) + if (runtime_snapshot.get('total') != 256 or len(observed) != 256 or + runtime_snapshot.get('dropped') != 0): + raise AssertionError('Runtime event count, capacity or delivery mismatch') + for i in range(128): + expected = 7 + 3 * i + write, read = observed[2*i], observed[2*i+1] + if write != {'seq':2*i+1,'site':9001,'kind':2,'value':expected}: + raise AssertionError(f'Incorrect executed write event at index {i}: {write}') + if read != {'seq':2*i+2,'site':9002,'kind':1,'value':expected}: + raise AssertionError(f'Incorrect executed read event at index {i}: {read}') + record('host','PASS: 256 real native field events, 128 read/write pairs, ' + 'exact values/order, zero drops, no event on null access') + if 'WARMUP_FAILED' in logs.stdout or 'WARMUP_DONE' not in logs.stdout: + raise AssertionError('APK fixture warmup failed or timed out') + if variant == 'release': + markers = [f'LSE_STAGE_DONE={i}' for i in range(5)] + missing_stages = [marker for marker in markers if marker not in logs.stdout] + if missing_stages: + raise AssertionError(f'Incomplete staged LSE warmup: {missing_stages}') + record('host','Five staged release warmups completed before JIT assertions') + hooked = [e['text'] for e in messages if e['kind']=='frida' and + '"artwatch-hook-attached"' in e['text']] + compiled = [e['text'] for e in messages if e['kind']=='frida' and + '"artwatch-jit"' in e['text']] + record('host',f'JIT hooks={len(hooked)} compilation events={len(compiled)}') + required = os.environ.get('ARTWATCH_REQUIRE_JIT') == '1' + if required: + # Assert the actual worker entry, not the exported Jit::CompileMethod() + # path bypassed by ordinary JitCompileTask execution. + # API 33 did not export CompileMethodInternal in earlier CI inventory. + # The compiler vtable boundary is the essential shared capability. + if not any('"compiler"' in h for h in hooked): + raise AssertionError('JitCompilerInterface::CompileMethod interceptor not installed') + internal = [e for e in compiled if '"runtime_internal"' in e] + compiler = [e for e in compiled if '"compiler"' in e] + record('host',f'JIT runtime_internal events={len(internal)} compiler events={len(compiler)}') + if not compiler: + raise AssertionError('No JIT compiler callbacks observed') + # When an internal hook exists, it must actually execute. + if any('"runtime_internal"' in h for h in hooked) and not internal: + raise AssertionError('Internal runtime hook installed but did not execute') + if required and 'api=33' in text and 'arch=x64' in text: + # This binary exports both boundaries; require actual callbacks. + shadow_enabled = os.environ.get('ARTWATCH_SHADOW_SHIM') == '1' + payloads = [] + for e in messages: + if e['kind'] != 'frida': + continue + try: + m = json.loads(e['text']) + if m.get('type') == 'send' and isinstance(m.get('payload'), dict): + payloads.append(m['payload']) + except (ValueError, TypeError): + continue + # P3 must prove the exact two native-cloned invoke nodes reached + # BOTH location assignment and code emission in one compilation. + # Counts and fixture assertions alone are not clone provenance. + p3_clones = [v for v in payloads if v.get('type') == 'artwatch-p3-clone'] + p3_compiled = [v for v in payloads if v.get('type') == 'artwatch-p3-compiled'] + p3_errors = [v for v in payloads if v.get('type') == 'artwatch-p3-clone-error'] + if p3_inject: + attached = [v for v in payloads if v.get('type') == 'artwatch-hook-attached' + and v.get('layer') == 'p3_clone_canary'] + successful = [v for v in p3_clones if v.get('rc') == 1] + if not attached or p3_errors or len(successful) != 2: + raise AssertionError(f'P3 clone hook/errors/attempts invalid: ' + f'{len(attached)}, {p3_errors}, {p3_clones}') + nodes = {v.get('clonedNode') for v in successful} + if {v.get('kind') for v in successful} != {'write','read'} or ( + None in nodes or len(nodes) != 2): + raise AssertionError(f'P3 did not return two distinct typed clone nodes: {successful}') + if len(p3_compiled) != 1 or p3_compiled[0].get('codegenSuccess') is not True or ( + p3_compiled[0].get('metadataConfigured') is not True): + raise AssertionError(f'P3 compiler completion not proven: {p3_compiled}') + proof = p3_compiled[0].get('cloneProof', []) + if (len(proof) != 2 or {v.get('node') for v in proof} != nodes or + {v.get('kind') for v in proof} != {'write','read'} or + not all(v.get('locations') is True and v.get('emitted') is True + for v in proof)): + raise AssertionError(f'P3 exact clone nodes missing from backend: {proof}') + if any(v.get('method') != p3_compiled[0].get('method') + for v in successful): + raise AssertionError('P3 cloned invokes came from different JIT methods') + record('host','PASS: P3 write/read clone IDs reached location assignment ' + 'and code emission in the successful ART compilation') + elif p3_clones or p3_compiled or p3_errors: + raise AssertionError('P3 mutation occurred while opt-in is disabled') + # Source-backed ABI oracle: compiler-created HInvokeStaticOrDirect + # nodes must be observed, not merely a successfully hooked export. + # This remains passive and does not imply an injected invoke. + invoke_abi = [v for v in payloads + if v.get('type') == 'artwatch-existing-invoke-abi'] + invoke_samples = [v for v in payloads + if v.get('type') == 'artwatch-existing-invoke'] + invoke_summaries = [v for v in payloads + if v.get('type') == 'artwatch-existing-invoke-summary'] + if not any(v.get('acceptExported') is True and + v.get('vtableExported') is True and + v.get('writesArtMemory') is False for v in invoke_abi): + raise AssertionError('API 33 compiler invoke ABI exports not verified') + if not invoke_samples or not invoke_summaries: + raise AssertionError('No real compiler-created invoke-node observations') + if not any(v.get('compilationSucceeded') is True and + v.get('visits', 0) >= v.get('uniqueNodes', 0) > 0 + for v in invoke_summaries): + raise AssertionError('No successful compilation containing invoke IR') + if not all(v.get('blockCorrelated', 0) <= v.get('visits', 0) + for v in invoke_summaries): + raise AssertionError('Invalid invoke visitor/block correlation count') + backend_layers = {v.get('layer') for v in payloads + if v.get('type') == 'artwatch-hook-attached' + and v.get('layer') in + ('existing_invoke_locations','existing_invoke_emission')} + if backend_layers != {'existing_invoke_locations', + 'existing_invoke_emission'}: + raise AssertionError('API33 invoke codegen hooks missing') + if not any(v.get('compilationSucceeded') is True and + v.get('backendEmitted', 0) > 0 and + v.get('backendLocations', 0) >= v.get('backendEmitted', 0) + for v in invoke_summaries): + raise AssertionError('No successful JIT with an emitted invoke node') + if not all(v.get('backendEmitted',0) >= + len(v.get('emittedInvokeNodes',[])) for v in invoke_summaries): + raise AssertionError('Invoke emission sample exceeds observed count') + if shadow_enabled and any(v.get('adjacencyRejected',0) > 0 + for v in invoke_summaries): + raise AssertionError('Build-ID-gated instruction adjacency probe rejected live nodes') + probe_count = sum(v.get('adjacencyProbes',0) for v in invoke_summaries) + direct_count = sum(v.get('adjacencyMatches',0) for v in invoke_summaries) + nearby_count = sum(v.get('adjacencyWithin8',0) for v in invoke_summaries) + mismatched = sum(v.get('adjacencyBlockMismatch',0) for v in invoke_summaries) + broken = sum(v.get('adjacencyBrokenLinks',0) for v in invoke_summaries) + no_get = sum(v.get('adjacencyNoGetWithin8',0) for v in invoke_summaries) + rejected = sum(v.get('adjacencyRejected',0) for v in invoke_summaries) + record('host',f'ART P3 invoke predecessors: probes={probe_count} ' + f'direct={direct_count} within8={nearby_count} ' + f'blockMismatch={mismatched} brokenLinks={broken} ' + f'noGetWithin8={no_get} rejected={rejected}') + if shadow_enabled: + if probe_count == 0: + raise AssertionError('P3 invoke predecessor observer never ran') + if probe_count != (direct_count + nearby_count + mismatched + + broken + no_get + rejected): + raise AssertionError('P3 invoke predecessor tallies inconsistent') + field_target_summaries = [ + v for v in invoke_summaries if v.get('fieldTarget') is True] + field_target_probes = sum( + v.get('targetAdjacencyProbes',0) for v in field_target_summaries) + record('host',f'P3 field-target predecessor probes={field_target_probes} ' + f'compilations={len(field_target_summaries)}') + if not field_target_summaries or field_target_probes == 0: + raise AssertionError('No baseline field-target invoke predecessor scans') + matched_get_pcs = sum(v.get('targetGetPcMatches',0) + for v in field_target_summaries) + unmatched_get_pcs = sum(v.get('targetGetPcMismatches',0) + for v in field_target_summaries) + unavailable_get_pcs = sum(v.get('targetGetPcUnavailable',0) + for v in field_target_summaries) + target_gets_found = sum( + v.get('adjacencyMatches',0) + v.get('adjacencyWithin8',0) + for v in field_target_summaries) + record('host',f'P3 target get identity: matched={matched_get_pcs} ' + f'unmatched={unmatched_get_pcs} unavailable={unavailable_get_pcs} ' + f'adjacent-or-nearby={target_gets_found}') + if matched_get_pcs + unmatched_get_pcs + unavailable_get_pcs != target_gets_found: + raise AssertionError('Inconsistent P3 get DEX-PC identity counters') + if matched_get_pcs == 0: + raise AssertionError('No live field-get DEX PC matched a field-builder target') + record('host',f'Invoke x64 backend: code-emission nodes=' + + str(sum(v.get('backendEmitted',0) for v in invoke_summaries))) + record('host',f'Existing invoke ABI: samples={len(invoke_samples)} ' + f'compilations={len(invoke_summaries)} ' + f'correlated={sum(v.get("blockCorrelated",0) for v in invoke_summaries)}') + graph_hooks = {v.get('layer') for v in payloads + if v.get('type') == 'artwatch-hook-attached' + and v.get('layer') in ('graph_builder','pre_opt')} + built = [v for v in payloads if v.get('type') == 'artwatch-graph' + and v.get('phase') == 'build-complete'] + preopt = [v for v in payloads if v.get('type') == 'artwatch-graph' + and v.get('phase') == 'pre-opt'] + matched = [v for v in preopt if v.get('graphMatchesBuilder') is True] + record('host',f'graph hooks={sorted(graph_hooks)} built={len(built)} ' + f'pre-opt={len(preopt)} pointer-matches={len(matched)}') + if graph_hooks != {'graph_builder','pre_opt'}: + raise AssertionError('API 33 graph boundaries not both attached') + if not built or not preopt: + raise AssertionError('API 33 graph construction/pre-optimization callback missing') + if not matched: + raise AssertionError('No graph pointer correlation between the boundaries') + field_hooks = {v.get('layer') for v in payloads + if v.get('type') == 'artwatch-hook-attached' + and v.get('layer') in ('field_instance','field_static')} + field_events = [v for v in payloads + if v.get('type') == 'artwatch-field-build'] + instance_reads = [v for v in field_events + if v.get('access') == 'instance' and v.get('isPut') is False] + instance_writes = [v for v in field_events + if v.get('access') == 'instance' and v.get('isPut') is True] + linked = [v for v in field_events + if v.get('graphCandidate') and v.get('method') and + isinstance(v.get('dexPc'), int)] + record('host',f'field hooks={sorted(field_hooks)} events={len(field_events)} ' + f'instance-reads={len(instance_reads)} instance-writes={len(instance_writes)} ' + f'graph-linked={len(linked)}') + if 'field_instance' not in field_hooks: + raise AssertionError('API 33 instance field-builder hook not installed') + if not instance_reads or not instance_writes: + raise AssertionError('Missing compiled instance-field get/set DEX build callbacks') + if not linked: + raise AssertionError('No field-builder event correlated with a live HGraph') + append_hooks = [v for v in payloads + if v.get('type') == 'artwatch-hook-attached' + and v.get('layer') == 'ir_append'] + nodes = [v for v in payloads if v.get('type') == 'artwatch-ir-node'] + typed = [v for v in nodes if v.get('kind') is not None] + observed_kinds = sorted({v['kind'] for v in typed}) + record('host', f'IR append hooks={len(append_hooks)} ' + f'candidate nodes={len(nodes)} typed={len(typed)} kinds={observed_kinds}') + visits = [v for v in payloads if v.get('type') == 'artwatch-ir-visit'] + visit_kinds = sorted({v.get('kind') for v in visits if v.get('kind')}) + matching_visits = [v for v in visits if v.get('vtableMatches') is True] + instance_types = [v for v in visits if v.get('kind') in + ('HInstanceFieldGet','HInstanceFieldSet')] + record('host',f'IR visits={len(visits)} visit kinds={visit_kinds} ' + f'vtable-matched={len(matching_visits)} ' + f'instance-typed={len(instance_types)}') + if nodes and not any(v.get('fieldIndexRaw') == 0 and + v.get('access') == 'instance' for v in nodes): + raise AssertionError('No FieldIRTarget field IR append candidates') + vtables = [v for v in payloads if v.get('type') == 'artwatch-ir-vtables'] + if vtables: + record('host', f'IR vtables available={vtables[-1].get("available",[])}') + if not nodes and not instance_types: + raise AssertionError('No field IR nodes observed through insertion or Accept()') + if visits and not matching_visits: + raise AssertionError('Field Accept callback vtables did not match class identity') + targets = [v for v in payloads if v.get('type') == 'artwatch-target-dex'] + target_ir = [v for v in payloads if v.get('type') == 'artwatch-target-ir'] + summaries = [v for v in payloads + if v.get('type') == 'artwatch-target-summary'] + mutations = [v for v in payloads + if v.get('type') == 'artwatch-ir-mutation'] + mutation_hooks = sorted({v.get('layer') for v in payloads + if v.get('type') == 'artwatch-hook-attached' + and str(v.get('layer','')).startswith('ir_mutation_')}) + target_kinds = sorted({v.get('kind') for v in target_ir}) + record('host',f'target DEX identified={len(targets)} ' + f'target IR={len(target_ir)} kinds={target_kinds} ' + f'target summaries={len(summaries)} ' + f'mutation hooks={mutation_hooks} mutation events={len(mutations)}') + if variant == 'debug': + if not targets: + raise AssertionError('Debug FieldIRTarget.test DEX pattern not identified') + if not summaries: + raise AssertionError('No debug compiler summary for FieldIRTarget.test') + if not {'HInstanceFieldGet','HInstanceFieldSet'}.issubset(set(target_kinds)): + raise AssertionError('Debug FieldIRTarget.test get/set IR nodes not both seen') + else: + record('host', 'Release DEX target fingerprint is diagnostic: ' + 'the missing iget may have been eliminated by D8 before ART JIT') + # Mutation/LSE hookability is a new hypothesis; missing exports are + # recorded, but do not invalidate the verified field-node capture. + phases = [v for v in payloads + if v.get('type') == 'artwatch-phase-summary'] + lse = [v for v in payloads if v.get('type') == 'artwatch-lse' + and v.get('phase') == 'enter'] + optimized = [v for v in phases if v.get('compilationKind') == 2] + record('host',f'variant={variant} compilations={len(phases)} ' + f'optimized={len(optimized)} lse-enter={len(lse)} ' + f'target-phases={[v for v in phases if v.get("isFieldTarget")]}') + if variant == 'release' and not optimized: + raise AssertionError('Non-debuggable release fixture did not trigger optimized JIT') + if variant == 'release' and not lse: + raise AssertionError('No LSE::Run invocation observed in non-debuggable optimized JIT') + backend_hooks = [v for v in payloads + if v.get('type') == 'artwatch-hook-attached' + and str(v.get('layer','')).startswith('backend_field_')] + backend_events = [v for v in payloads + if v.get('type') == 'artwatch-backend-field'] + lowered = [v for v in backend_events if v.get('stage') == 'locations'] + emitted = [v for v in backend_events if v.get('stage') == 'emission'] + record('host', f'backend field hooks={len(backend_hooks)} ' + f'locations={len(lowered)} emission={len(emitted)} ' + f'emitted kinds={sorted({v.get("expectedKind") for v in emitted})}') + if len(backend_hooks) != 4: + raise AssertionError('Expected four API33 x86_64 backend field visitor hooks') + if not lowered and not emitted: + raise AssertionError('No instance-field IR nodes reached backend field visitors') + if variant == 'release' and not targets: + raise AssertionError('Release fixture did not produce any method with iget+iput DEX') + positive_lse = [v for v in payloads + if v.get('type') == 'artwatch-lse' + and v.get('phase') == 'exit' + and v.get('compilationKind') == 2 + and v.get('result') is True] + field_mutations = [v for v in payloads + if v.get('type') == 'artwatch-field-ir-mutation'] + mutation_calls = [v for v in payloads + if v.get('type') == 'artwatch-mutation-call-summary'] + record('host', f'variant={variant} optimized-LSE-changes={len(positive_lse)} ' + f'field-IR-mutations={len(field_mutations)} ' + f'mutation-call-summaries={len(mutation_calls)}') + if variant == 'release' and not positive_lse: + raise AssertionError('Release optimized JIT saw LSE but no Run() returned true') + + # Exact-node evidence: source-level DEX read was present, and ART + # visited its HInstanceFieldGet before LSE replaced and removed it. + # The removed pointer must not appear in this compilation's backend. + lifecycles = [v for v in payloads + if v.get('type') == 'artwatch-field-lifecycle'] + eliminated_gets = [(lc, entry) for lc in lifecycles + if lc.get('compilationKind') == 2 + and lc.get('compilationSucceeded') is True + for entry in lc.get('entries', []) + if entry.get('kind') == 'HInstanceFieldGet' + and {'replace', 'remove'}.issubset( + set(entry.get('operations', []))) + and entry.get('visitedBeforeMutation') is True + and entry.get('lowered') is False + and entry.get('emitted') is False] + block_traced_gets = [(lc, entry) for lc, entry in eliminated_gets + if entry.get('observedBlocks') + and any(v.get('constructed') is True + for v in entry.get('observedBlocks',[]))] + baseline_reads = [v for v in summaries + if v.get('compilationKind') == 1 and + v.get('compilationSucceeded') is True and + any(str(k).startswith('HInstanceFieldGet@') + for k in v.get('codeEmittedNodes', []))] + record('host', f'variant={variant} lifecycle-compilations={len(lifecycles)} ' + f'optimized-removed-gets={len(eliminated_gets)} ' + f'block-traced-eliminated-gets={len(block_traced_gets)} ' + f'baseline-emitted-gets={len(baseline_reads)}') + if variant == 'release' and not eliminated_gets: + raise AssertionError('No exact HInstanceFieldGet visited, replaced and ' + 'removed during LSE without backend emission') + if variant == 'release' and not baseline_reads: + raise AssertionError('No baseline JIT get node observed at code emission') + if variant == 'release' and len(block_traced_gets) != len(eliminated_gets): + raise AssertionError('LSE-eliminated field get lacked prior ' + 'observed HGraph basic-block ownership') + for lc, entry in block_traced_gets: + if not all(b.get('block') and b.get('visits',0) >= 1 + for b in entry['observedBlocks']): + raise AssertionError('Malformed historical field block membership') + producer_types = sorted({e.get('replacementKind') for _,e in eliminated_gets + if e.get('replacementKind')}) + record('host',f'Replaced instance-field SSA producer kinds={producer_types}') + visit_order = [v for v in payloads + if v.get('type') == 'artwatch-field-visit-order'] + sampled_passes = [item for event in visit_order + for item in event.get('passes',[])] + order_field_count = sum(p.get('fieldCount',0) for p in sampled_passes) + order_truncated = sum(v.get('truncatedFieldEntries',0) + for v in visit_order) + record('host',f'Field visit order scopes={len(visit_order)} ' + f'passes={len(sampled_passes)} fields={order_field_count} ' + f'truncated={order_truncated}') + if not sampled_passes or order_field_count <= 0: + raise AssertionError('No field visitation order from real ART blocks') + for event in visit_order: + if event.get('passesCaptured') != len(event.get('passes',[])): + raise AssertionError('Incorrect captured visitor pass count') + if event.get('passesWithFields',0) < event.get('passesCaptured',0): + raise AssertionError('Captured more field passes than observed') + for item in sampled_passes: + fields = item.get('fields',[]) + if not item.get('block') or not item.get('visitor'): + raise AssertionError('Missing visitor/block pointer in visit order') + if item.get('fieldCount',0) < len(fields) or len(fields) > 20: + raise AssertionError('Field visitor sample overflow') + if [i.get('ordinal') for i in fields] != list(range(len(fields))): + raise AssertionError('Field visitor ordering ordinals are inconsistent') + if not all(i.get('node') and str(i.get('kind','')).startswith('H') + for i in fields): + raise AssertionError('Missing typed node from visit order') + if shadow_enabled: + inits = [v for v in payloads if v.get('type') == 'artwatch-shadow-init'] + if not any(v.get('ready') is True and v.get('buildIdVerified') is True + for v in inits): + raise AssertionError(f'Native passive shadow shim rejected: {inits}') + graphs = [v for v in payloads + if v.get('type') == 'artwatch-shadow-graph'] + nodes = [v for v in payloads + if v.get('type') == 'artwatch-shadow-node'] + stats = [v for v in payloads + if v.get('type') == 'artwatch-shadow-stats' + and v.get('ready') is True] + kinds = {v.get('kind') for v in nodes} + record('host',f'Native shadow graphs={len(graphs)} ' + f'nodes={len(nodes)} kinds={sorted(kinds)} ' + f'latest-stats={stats[-1] if stats else None}') + if not graphs or not {'HInstanceFieldGet', + 'HInstanceFieldSet'}.issubset(kinds): + raise AssertionError('Native shim did not validate graph/get/set') + if not stats or not all(stats[-1].get(k,0)>0 + for k in ('graphs','gets','sets')): + raise AssertionError('Native shim missing expected counters') + if stats[-1].get('rejected') != 0: + raise AssertionError('Native shim rejected a pointer/vtable') + scopes = [v for v in payloads + if v.get('type') == 'artwatch-shadow-scope'] + active_scopes = [v for v in scopes + if v.get('getVisits',0) + v.get('setVisits',0) > 0] + total_unique = sum(v.get('uniqueGets',0) + v.get('uniqueSets',0) + for v in scopes) + record('host',f'Native optimization scopes={len(scopes)} ' + f'with-field-visits={len(active_scopes)} ' + f'sum-unique-field-nodes={total_unique}') + if not scopes or not active_scopes or total_unique <= 0: + raise AssertionError('Native per-compilation observer saw no field nodes') + if any(v.get('overflow') != 0 for v in scopes): + raise AssertionError('Native fixed-capacity field inventory overflowed') + if any(v.get('uniqueGets',0) > v.get('getVisits',0) or + v.get('uniqueSets',0) > v.get('setVisits',0) for v in scopes): + raise AssertionError('Native field inventory has inconsistent counts') + block_hooks = [v for v in payloads + if v.get('type') == 'artwatch-hook-attached' + and v.get('layer') in ('graph_add_block', + 'graph_checker_block')] + constructed = [v for v in payloads + if v.get('type') == 'artwatch-block-discovery'] + checked = [v for v in payloads + if v.get('type') == 'artwatch-block-checker'] + unique_blocks = sum(v.get('uniqueBlocks',0) for v in constructed) + checked_blocks = sum(v.get('uniqueBlocks',0) for v in checked) + record('host', f'Graph block hooks={sorted({v.get("layer") for v in block_hooks})} ' + f'created unique={unique_blocks} checked unique={checked_blocks} ' + f'native block callbacks={stats[-1].get("blocks",0)}') + if any(v.get('uniqueBlocks',0) < 0 or v.get('unmatched',0) < 0 + for v in constructed): + raise AssertionError('Invalid graph block discovery counts') + if unique_blocks and stats[-1].get('blocks',0) < unique_blocks: + raise AssertionError('Native block confirmations smaller than unique discoveries') + if 'graph_add_block' not in {v.get('layer') for v in block_hooks}: + raise AssertionError('Previously verified HGraph::AddBlock export disappeared') + if not constructed or unique_blocks <= 0: + raise AssertionError('No block identities observed at graph construction') + instruction_evidence = [v for v in payloads + if v.get('type') == + 'artwatch-block-instruction-evidence'] + visitor_evidence = [v for v in payloads + if v.get('type') == 'artwatch-block-visitor'] + insert_calls = sum(v.get('addInstructionCalls',0) + for v in instruction_evidence) + inserted_fields = sum(v.get('fieldNodeInserts',0) + for v in instruction_evidence) + visited_blocks = sum(v.get('uniqueBlocks',0) + for v in visitor_evidence) + record('host',f'Block/instruction bridge calls={insert_calls} ' + f'typed-field-inserts={inserted_fields} ' + f'visitor-scopes={len(visitor_evidence)} ' + f'visitor-blocks={visited_blocks}') + if any(v.get('mappedFieldNodes',0) > v.get('fieldNodeInserts',0) + for v in instruction_evidence): + raise AssertionError('Impossible block-to-field mapping counts') + if any(v.get('newlySeenBlocks',0) > v.get('uniqueBlocks',0) + for v in visitor_evidence): + raise AssertionError('Impossible visitor block membership counts') + ownership = [v for v in payloads + if v.get('type') == 'artwatch-field-block-ownership'] + matched_visits = sum(v.get('correlatedVisits',0) for v in ownership) + get_visits = sum(v.get('getVisits',0) for v in ownership) + set_visits = sum(v.get('setVisits',0) for v in ownership) + pairs = sum(v.get('uniqueFieldBlockPairs',0) for v in ownership) + mismatches = sum(v.get('visitorPointerMismatches',0) for v in ownership) + record('host',f'Field->block visitor correlation scopes={len(ownership)} ' + f'visits={matched_visits} get={get_visits} set={set_visits} ' + f'node/block pairs={pairs} visitor mismatches={mismatches}') + if not ownership or matched_visits <= 0 or pairs <= 0: + raise AssertionError('No field instruction correlated with a ' + 'real HGraphVisitor basic-block callback') + if get_visits <= 0 or set_visits <= 0: + raise AssertionError('Visitor ownership missing field get or set') + if mismatches: + raise AssertionError('Field Accept visitor did not match active ' + 'HGraphVisitor::VisitBasicBlock') + for item in ownership: + if item.get('uniqueFieldBlockPairs',0) > item.get('correlatedVisits',0): + raise AssertionError('More unique ownership pairs than field visits') + if item.get('uniqueFieldNodes',0) > item.get('uniqueFieldBlockPairs',0): + raise AssertionError('More unique nodes than node-block pairs') + if any(not sample.get('block') or not sample.get('node') + for sample in item.get('examples',[])): + raise AssertionError('Field ownership example missing pointer') + # Do not mistake observation during an ART traversal for a + # direct C++ layout walk, insertion event, or runtime read. + record('host','PASS: Frida attach + ART discovery + fixture warmup') + +if __name__ == '__main__': + try: main() + except Exception as e: + record('host','FAIL: '+repr(e)) + (LOG_DIR/'frida-messages.json').write_text(json.dumps(messages,indent=2)) + sys.exit(1) diff --git a/art-fieldwatch-phase1/jit-boundary-probe.js b/art-fieldwatch-phase1/jit-boundary-probe.js new file mode 100644 index 0000000..6897685 --- /dev/null +++ b/art-fieldwatch-phase1/jit-boundary-probe.js @@ -0,0 +1,1620 @@ +'use strict'; +// Read-only ART JIT interception probe; no field interception or IR mutation. +const TAG = '[art-fieldwatch/phase1] '; +const SAMPLE_LIMIT = 60; +const artLibraries = new Set(['libart.so', 'libartd.so', 'libart-compiler.so', 'libartd-compiler.so']); +const log = s => console.log(TAG + s); +const count = {runtime_internal: 0, compiler: 0, graph_builder: 0, pre_opt: 0}; +// Track the method being compiled per native thread, only while compilation runs. +const compiling = new Map(); +const builtByThread = new Map(); +const activeGraphBuild = new Map(); +const FIELD_SAMPLE_LIMIT = 140; +const fieldCounts = {instance: 0, static: 0}; +const activeFieldBuilder = new Map(); +const FIELD_NODE_SAMPLE_LIMIT = 180; +let observedFieldNodeCandidates = 0; +let observedFieldAccepts = 0; +const insertionCounts = {append: 0, 'basic-block': 0}; +const optimizationByThread = new Map(); +// Scoped to an actual out-of-line HGraphVisitor::VisitBasicBlock call. +const activeVisitorBlockByThread = new Map(); +const knownFieldVtables = new Map(); +// Read-only SSA producer classification from actual exported primary vtables. +// A missing symbol produces an explicit unknown kind; no ART methods are called. +const knownValueVtables = new Map(); +const SSA_VALUE_KINDS = [ + 'HParameterValue', 'HIntConstant', 'HLongConstant', 'HNullConstant', + 'HFloatConstant', 'HDoubleConstant', 'HPhi', 'HAdd', 'HSub', + 'HSelect', 'HNullCheck', 'HBoundsCheck', 'HLoadClass', + 'HInvokeStaticOrDirect', 'HInvokeVirtual', 'HNewInstance', + 'HInstanceFieldGet', 'HStaticFieldGet', 'HArrayGet', + 'HTypeConversion', 'HAnd', 'HOr', 'HNeg', 'HNot', 'HReturn' +]; +const MAX_FIELD_PASSES = 20; +const MAX_FIELDS_PER_PASS = 20; +function discoverValueVtables(compiler) { + const available = []; + for (const kind of SSA_VALUE_KINDS) { + const symbol = '_ZTVN3art' + kind.length + kind + 'E'; + const site = getExport(compiler, symbol); + if (!site) continue; + knownValueVtables.set(site.address.add(2 * Process.pointerSize).toString(),kind); + available.push(kind); + } + log('ssa-value-vtables=' + available.join(',')); + send({type:'artwatch-ssa-vtables',available}); +} +function classifySSAValue(value) { + if (!value || value.isNull()) return null; + try { + const range = Process.findRangeByAddress(value); + if (!range || !range.protection.includes('r')) return null; + return knownValueVtables.get(value.readPointer().toString()) || null; + } catch (_) { return null; } +} +let shadowShim = null; +let shadowModuleAttempted = false; +let shadowGraphLogged = 0; +let shadowNodeLogged = 0; +// Real compiler-built invoke nodes are our ABI oracle; no mutation here. +const INVOKE_ACCEPT = '_ZN3art21HInvokeStaticOrDirect6AcceptEPNS_13HGraphVisitorE'; +const INVOKE_VTABLE = '_ZTVN3art21HInvokeStaticOrDirectE'; +const INVOKE_BACKEND_LOCATIONS = + '_ZN3art6x86_6422LocationsBuilderX86_6425VisitInvokeStaticOrDirectEPNS_21HInvokeStaticOrDirectE'; +const INVOKE_BACKEND_EMISSION = + '_ZN3art6x86_6430InstructionCodeGeneratorX86_6425VisitInvokeStaticOrDirectEPNS_21HInvokeStaticOrDirectE'; +const MAX_EXISTING_INVOKES = 80; +let existingInvokeCount = 0; +let p3PendingMethod = null; +const targetDexByMethod = new Map(); +let backendVisitOrdinal = 0; +const BACKEND_VISIT_LIMIT = 160; +const backendCounts = {locations: 0, emission: 0}; +const targetMethodPointers = new Set(); +const targetStates = new Map(); +const targetReportLimit = 36; +const lseByThread = new Map(); +const mutationHookCounts = {replace: 0, replace_remove: 0, remove: 0, remove_or_phi: 0, lse: 0}; +let lseTraceEmitted = 0; +const LSE_TRACE_LIMIT = 80; +let fieldMutationTraceEmitted = 0; +const FIELD_MUTATION_TRACE_LIMIT = 160; +function fieldKind(ptr) { + try { return knownFieldVtables.get(ptr.readPointer().toString()) || null; } + catch (_) { return null; } +} +function reportTargetEvent(state, event) { + if (state.reported++ >= targetReportLimit) return; + send(event); + log('TARGET_IR ' + JSON.stringify(event)); +} +const FIELD_VTABLE_SYMBOLS = [ + ['HInstanceFieldGet', '_ZTVN3art17HInstanceFieldGetE'], + ['HInstanceFieldSet', '_ZTVN3art17HInstanceFieldSetE'], + ['HStaticFieldGet', '_ZTVN3art15HStaticFieldGetE'], + ['HStaticFieldSet', '_ZTVN3art15HStaticFieldSetE'], + ['HUnresolvedInstanceFieldGet', '_ZTVN3art27HUnresolvedInstanceFieldGetE'], + ['HUnresolvedInstanceFieldSet', '_ZTVN3art27HUnresolvedInstanceFieldSetE'], + ['HUnresolvedStaticFieldGet', '_ZTVN3art25HUnresolvedStaticFieldGetE'], + ['HUnresolvedStaticFieldSet', '_ZTVN3art25HUnresolvedStaticFieldSetE'] +]; +function sdkLevel() { + try { + const p = Process.getModuleByName('libc.so').findExportByName('__system_property_get'); + if (p === null) return NaN; + const get = new NativeFunction(p, 'int', ['pointer', 'pointer']); + const buf = Memory.alloc(128); + const rc = get(Memory.allocUtf8String('ro.build.version.sdk'), buf); + return rc > 0 ? Number(buf.readUtf8String()) : NaN; + } catch (e) { log('sdk-error=' + e); return NaN; } +} +const NAMES = { + internal: '_ZN3art3jit3Jit21CompileMethodInternalEPNS_9ArtMethodEPNS_6ThreadENS_15CompilationKindEb', + publicCompile: '_ZN3art3jit3Jit13CompileMethodEPNS_9ArtMethodEPNS_6ThreadENS_15CompilationKindEb', + compiler: '_ZN3art3jit11JitCompiler13CompileMethodEPNS_6ThreadEPNS0_15JitMemoryRegionEPNS_9ArtMethodENS_15CompilationKindE', + instance: '_ZN3art3jit3Jit13jit_compiler_E', + buildGraph: '_ZN3art13HGraphBuilder10BuildGraphEv', + runOptimizations: '_ZNK3art18OptimizingCompiler16RunOptimizationsEPNS_6HGraphEPNS_13CodeGeneratorERKNS_18DexCompilationUnitEPNS_12PassObserverE', + graphAddBlock: '_ZN3art6HGraph8AddBlockEPNS_11HBasicBlockE', + graphCheckerBlock: '_ZN3art12GraphChecker15VisitBasicBlockEPNS_11HBasicBlockE', + // Ordinary graph visitor exports are stronger evidence of traversal + // than GraphChecker, which is not necessarily run on release builds. + graphVisitorBlock: '_ZN3art13HGraphVisitor15VisitBasicBlockEPNS_11HBasicBlockE', + graphVisitorInsertion: '_ZN3art13HGraphVisitor19VisitInsertionOrderEv', + graphVisitorRpo: '_ZN3art13HGraphVisitor21VisitReversePostOrderEv', + // Candidate exported signatures from instruction_builder.cc. Only use if + // this exact ELF symbol exists on the running device. + fieldInstance: '_ZN3art19HInstructionBuilder24BuildInstanceFieldAccessERKNS_11InstructionEjb', + fieldStatic: '_ZN3art19HInstructionBuilder22BuildStaticFieldAccessERKNS_11InstructionEjb', + appendInstruction: '_ZN3art19HInstructionBuilder17AppendInstructionEPNS_12HInstructionE', + addInstruction: '_ZN3art11HBasicBlock14AddInstructionEPNS_12HInstructionE', + // ABI candidates; check exact runtime exports and archive matching ELF names. + // All are read-only observers, no replacement or mutation is performed. + replaceWith: '_ZN3art12HInstruction11ReplaceWithEPS0_', + replaceAndRemove: '_ZN3art11HBasicBlock31ReplaceAndRemoveInstructionWithEPNS_12HInstructionES2_', + removeInstruction: '_ZN3art11HBasicBlock17RemoveInstructionEPNS_12HInstructionEb', + removeInstructionOrPhi: '_ZN3art11HBasicBlock22RemoveInstructionOrPhiEPNS_12HInstructionEb', + x64LocationsFieldGet: '_ZN3art6x86_6422LocationsBuilderX86_6421VisitInstanceFieldGetEPNS_17HInstanceFieldGetE', + x64LocationsFieldSet: '_ZN3art6x86_6422LocationsBuilderX86_6421VisitInstanceFieldSetEPNS_17HInstanceFieldSetE', + x64EmitFieldGet: '_ZN3art6x86_6430InstructionCodeGeneratorX86_6421VisitInstanceFieldGetEPNS_17HInstanceFieldGetE', + x64EmitFieldSet: '_ZN3art6x86_6430InstructionCodeGeneratorX86_6421VisitInstanceFieldSetEPNS_17HInstanceFieldSetE', + lseRun: '_ZN3art20LoadStoreElimination3RunEv', + lseRunBool: '_ZN3art20LoadStoreElimination3RunEb' +}; +function getExport(module, exactName) { + const address = module.findExportByName(exactName); + return address === null ? null : {name: exactName, address}; +} +// Passive P1: only the CI script can opt in to loading the exact shim. +// It contains no ART write API; invalid build IDs fail closed. +function loadPassiveShadow() { + if (typeof globalThis.__artwatchShadowPath !== 'string' || + Process.arch !== 'x64') return; + try { + // Do not dlopen from Frida's namespace or from /data/local/tmp. + // The Android app loads its own library via System.loadLibrary() first. + const module = Process.findModuleByName(globalThis.__artwatchShadowPath); + if (module === null) return; + if (shadowModuleAttempted) return; + shadowModuleAttempted = true; + function exported(name, ret, args) { + const address = module.findExportByName(name); + if (address === null) throw new Error('missing native shadow export=' + name); + return new NativeFunction(address, ret, args); + } + if (exported('artwatch_shadow_init','int',[])() !== 1) { + send({type:'artwatch-shadow-init', ready:false, + reason:'SDK or mapped ART ELF build-ID verification failed'}); + return; + } + shadowShim = { + graph: exported('artwatch_shadow_graph','int',['pointer','pointer']), + node: exported('artwatch_shadow_node','int',['pointer','pointer','int']), + report: exported('artwatch_shadow_report','int',['pointer','uint']), + scopeBegin: exported('artwatch_shadow_scope_begin','int',['pointer']), + scopeEnd: exported('artwatch_shadow_scope_end','int',['pointer','uint']), + block: exported('artwatch_shadow_block','int',['pointer','pointer','pointer']), + linkedGetInvoke: exported('artwatch_shadow_linked_get_invoke','int', + ['pointer','pointer','pointer','pointer']), + instructionDexPc: exported('artwatch_shadow_instruction_dex_pc','int', + ['pointer','pointer','pointer']), + cloneTemplate: exported('artwatch_shadow_clone_template_invoke','int', + ['pointer','pointer','pointer','pointer','uint','uint','pointer']), + cloneBefore: exported('artwatch_shadow_clone_invoke_before','int', + ['pointer','pointer','pointer','uint','uint','pointer','pointer','int','pointer']) + }; + send({type:'artwatch-shadow-init',ready:true,source:'native', + buildIdVerified:true,mutable:false}); + log('native-shadow=ready with verified ART build IDs'); + } catch(e) { + log('native-shadow-load-error=' + (e.stack || e)); + send({type:'artwatch-shadow-init',ready:false,reason:String(e)}); + } +} +function reportPassiveShadow() { + if (!shadowShim) return; + try { + const buf = Memory.alloc(384); + if (shadowShim.report(buf, 384) !== 1) return; + send({type:'artwatch-shadow-stats',...JSON.parse(buf.readUtf8String())}); + } catch(e) { log('native-shadow-report-error=' + e); } +} +function compilerViaVtable(runtime, compiler) { + // This is an ABI-specific experiment, NOT a generic C++ vtable scanner. + // In the AOSP JitCompilerInterface declaration, virtual ~JitCompilerInterface() + // is followed by virtual CompileMethod(). For the Itanium C++ ABI used by + // Android x86_64/arm64, the destructor occupies slots 0/1 and CompileMethod slot 2. + const symbol = getExport(runtime, NAMES.instance); + if (!symbol) { log('compiler-vtable=unavailable (jit_compiler_ not exported)'); return null; } + try { + const instance = symbol.address.readPointer(); // Existing compiler instance; NEVER call jit_load(). + if (instance.isNull()) { log('compiler-vtable=unavailable (instance null)'); return null; } + const vtable = instance.readPointer(); + const vtableOwner = Process.findModuleByAddress(vtable); + if (!vtableOwner || vtableOwner.name !== compiler.name) { + log('compiler-vtable=rejected (vtable outside ' + compiler.name + ')'); + return null; + } + const fn = vtable.add(2 * Process.pointerSize).readPointer(); + const fnOwner = Process.findModuleByAddress(fn); + if (!fnOwner || fnOwner.name !== compiler.name) { + log('compiler-vtable=rejected (slot2 outside ' + compiler.name + ')'); + return null; + } + log('compiler-vtable instance=' + instance + ' vtable=' + vtable + ' slot2=' + fn); + return {address: fn, name: 'JitCompilerInterface::CompileMethod [vtable slot2]', + source: 'vtable-slot2'}; + } catch (e) { log('compiler-vtable-error=' + e); return null; } +} +function attach(layer, site) { + try { + Interceptor.attach(site.address, { + onEnter(args) { + // x86_64/arm64 non-static member calls: args[0] is this. + // Internal: (this, ArtMethod*, Thread*, CompilationKind, bool). + // Compiler: (this, Thread*, JitMemoryRegion*, ArtMethod*, CompilationKind). + this.method = (layer === 'compiler' ? args[3] : args[1]).toString(); + this.compilationKind = (layer === 'compiler' ? args[4] : args[3]).toInt32(); + this.ordinal = ++count[layer]; + if (layer === 'compiler') { + this.nativeThread = this.threadId; + this.previousCompilation = compiling.get(this.nativeThread); + this.previousTargetState = targetStates.get(this.nativeThread); + this.mutationCountsAtEnter = {...mutationHookCounts}; + targetStates.set(this.nativeThread, { + method: this.method, kind: this.compilationKind, + existingInvokeVisits: 0, existingInvokeNodes: new Set(), + existingInvokeBlockVisits: 0, + p3Builder: null, p3ClonedNodes: new Map(), + existingInvokeLocations: new Set(), + existingInvokeEmitted: new Set(), + adjacencyProbes: 0, adjacencyMatches: 0, + adjacencyRejected: 0, adjacencySamples: [], + adjacencyWithin8: 0, adjacencyBlockMismatch: 0, + adjacencyBrokenLinks: 0, adjacencyNoGetWithin8: 0, + adjacencyPreviousSamples: [], targetAdjacencyProbes: 0, + targetGetPcMatches: 0, targetGetPcMismatches: 0, + targetGetPcUnavailable: 0, + seenVisits: new Set(), seenKinds: new Set(), uniqueNodes: new Set(), + visitsByPhase: {}, mutations: [], reported: 0, + optimizationEntries: 0, lseInvocations: 0, + backendLocations: new Set(), backendEmitted: new Set(), + constructionGraph: null, constructedBlocks: new Set(), + checkerBlocks: new Set(), visitorBlocks: new Set(), + visitorBlocksUnknown: new Set(), + visitorFieldNodes: new Map(), visitorFieldPairs: new Map(), + visitorFieldVisits: 0, visitorFieldGetVisits: 0, + visitorFieldSetVisits: 0, visitorPointerMismatch: 0, + blockVisitOrdinal: 0, fieldPassesObserved: 0, + fieldVisitOrderSamples: [], fieldOrderTruncated: 0, + blockInstructionMap: new Map(), fieldNodeInserts: 0, + graphAddInstructionCalls: 0, fieldVisitBlockMatches: 0, + unmatchedBlockCalls: 0 + }); + compiling.set(this.nativeThread, {method: this.method, kind: this.compilationKind}); + builtByThread.delete(this.nativeThread); + } + if (this.ordinal <= SAMPLE_LIMIT) + log('JIT enter layer=' + layer + ' method=' + this.method + + ' kind=' + this.compilationKind); + }, + onLeave(ret) { + if (layer === 'compiler') { + const state = targetStates.get(this.nativeThread); + if (p3PendingMethod === this.method) { + const succeeded = ret.toInt32() !== 0; + p3PendingMethod = null; + const module = Process.findModuleByName('libartwatch_events.so'); + const fn = module && module.findExportByName('artwatch_events_set_p3'); + const configFn=module && module.findExportByName('artwatch_events_configure_p3'); + const proofs = ['write','read'].map(kind => { + const node=state && state.p3ClonedNodes.get(kind); + return {kind,node:node||null, + locations:!!node && state.existingInvokeLocations.has(node), + emitted:!!node && state.existingInvokeEmitted.has(node)}; + }); + const codegenProven=proofs.every(p => p.node && p.locations && p.emitted) && + proofs[0].node !== proofs[1].node; + const f=globalThis.__artwatchP3Fixture; + const metadataValid=f && ['dexId','carrierMethodIndex','fieldIndex', + 'setDexPc','getDexPc'].every(k=>Number.isSafeInteger(f[k]) && f[k]>=0); + if (succeeded && codegenProven && fn !== null && + configFn !== null && metadataValid) { + const configured=new NativeFunction(configFn,'int', + ['uint','uint','uint','uint','uint'])( + f.dexId,f.carrierMethodIndex,f.fieldIndex,f.setDexPc,f.getDexPc); + if (configured===1) { + new NativeFunction(fn,'void',['int'])(1); + send({type:'artwatch-p3-compiled',method:this.method, + codegenSuccess:true,metadataConfigured:true, + metadata:{dexId:f.dexId,methodId:f.carrierMethodIndex, + fieldId:f.fieldIndex,writePc:f.setDexPc,readPc:f.getDexPc}, + cloneProof:proofs}); + } else { + send({type:'artwatch-p3-clone-error',method:this.method, + error:'P3 metadata configuration rejected'}); + } + } else { + send({type:'artwatch-p3-clone-error',method:this.method, + error:'compiler completion, cloned invoke codegen, or event setter failed', + compilerSucceeded:succeeded,cloneProof:proofs}); + } + } + if (state && state.existingInvokeVisits > 0) { + send({type:'artwatch-existing-invoke-summary', + method:this.method,compilationKind:this.compilationKind, + visits:state.existingInvokeVisits, + uniqueNodes:state.existingInvokeNodes.size, + blockCorrelated:state.existingInvokeBlockVisits, + backendLocations:state.existingInvokeLocations.size, + backendEmitted:state.existingInvokeEmitted.size, + adjacencyProbes:state.adjacencyProbes, + adjacencyMatches:state.adjacencyMatches, + adjacencyRejected:state.adjacencyRejected, + adjacencySamples:state.adjacencySamples, + adjacencyWithin8:state.adjacencyWithin8, + adjacencyBlockMismatch:state.adjacencyBlockMismatch, + adjacencyBrokenLinks:state.adjacencyBrokenLinks, + adjacencyNoGetWithin8:state.adjacencyNoGetWithin8, + adjacencyPreviousSamples:state.adjacencyPreviousSamples, + fieldTarget:targetMethodPointers.has(this.method), + targetAdjacencyProbes:state.targetAdjacencyProbes, + targetGetPcMatches:state.targetGetPcMatches, + targetGetPcMismatches:state.targetGetPcMismatches, + targetGetPcUnavailable:state.targetGetPcUnavailable, + emittedInvokeNodes:[...state.existingInvokeEmitted].slice(0,12), + compilationSucceeded:ret.toInt32() !== 0}); + } + if (state && targetMethodPointers.has(this.method)) { + send({type: 'artwatch-target-summary', + method: this.method, compilationKind: this.compilationKind, + kinds: [...state.seenKinds].sort(), + uniqueNodeCount: state.uniqueNodes.size, + visitsByPhase: state.visitsByPhase, + mutations: state.mutations, + locationsNodes: [...state.backendLocations], + codeEmittedNodes: [...state.backendEmitted], + compilationSucceeded: ret.toInt32() !== 0 + }); + log('TARGET_SUMMARY method=' + this.method + ' kind=' + + this.compilationKind + ' nodes=' + state.uniqueNodes.size + + ' kinds=' + [...state.seenKinds].join(',') + + ' mutations=' + state.mutations.length); + } + // Validate elimination on the same compilation and exact node. + // Only string identities are retained; node memory is never dereferenced + // after removal or after the JIT compilation returns. + if (state && targetMethodPointers.has(this.method) && state.mutations.length) { + const lifecycleByNode = new Map(); + for (const mutation of state.mutations) { + if (!mutation.duringLse) continue; + const identity = mutation.kind + '@' + mutation.node; + let entry = lifecycleByNode.get(identity); + if (!entry) { + entry = {kind: mutation.kind, node: mutation.node, + operations: [], replacement: null, + visitedBeforeMutation: false}; + lifecycleByNode.set(identity, entry); + } + entry.operations.push(mutation.op); + entry.visitedBeforeMutation ||= mutation.visitedBeforeMutation === true; + if (mutation.op === 'replace') { + entry.replacement = mutation.substitute; + entry.replacementKind = mutation.substituteKind; + } + } + const entries = Array.from(lifecycleByNode.values()).map(entry => { + const identity = entry.kind + '@' + entry.node; + // Historical evidence from actual ART block visitor + // callbacks, joined by exact instruction pointer. A node + // can be moved between blocks by optimizer passes; this + // does not claim a live GetBlock() after removal. + const observedBlocks = []; + for (const pair of state.visitorFieldPairs.values()) { + if (pair.kind === entry.kind && pair.node === entry.node) { + observedBlocks.push({ + block: pair.block, visits: pair.visits, + constructed: pair.constructed + }); + } + } + return {...entry, observedBlocks, + lowered: state.backendLocations.has(identity), + emitted: state.backendEmitted.has(identity)}; + }); + if (entries.length) { + const event = {type: 'artwatch-field-lifecycle', + method: this.method, compilationKind: this.compilationKind, + compilationSucceeded: ret.toInt32() !== 0, + entries}; + send(event); + log('FIELD_LIFECYCLE ' + JSON.stringify(event)); + } + } + if (state && this.ordinal <= SAMPLE_LIMIT) { + const mutationCallDeltas = {}; + for (const [op, value] of Object.entries(mutationHookCounts)) { + mutationCallDeltas[op] = value - (this.mutationCountsAtEnter[op] || 0); + } + send({type: 'artwatch-mutation-call-summary', method:this.method, + compilationKind:this.compilationKind, calls:mutationCallDeltas}); + send({type: 'artwatch-phase-summary', method: this.method, + compilationKind: this.compilationKind, + isFieldTarget: targetMethodPointers.has(this.method), + optimizationEntries: state.optimizationEntries, + lseInvocations: state.lseInvocations, + success: ret.toInt32() !== 0}); + } + if (shadowShim && this.ordinal <= SAMPLE_LIMIT) reportPassiveShadow(); + if (this.previousTargetState) targetStates.set(this.nativeThread, this.previousTargetState); + else targetStates.delete(this.nativeThread); + if (this.previousCompilation) compiling.set(this.nativeThread, this.previousCompilation); + else compiling.delete(this.nativeThread); + builtByThread.delete(this.nativeThread); + } + const event = {type: 'artwatch-jit', layer, method: this.method, + kind: this.compilationKind, success: ret.toInt32() !== 0, + ordinal: this.ordinal}; + if (this.ordinal <= SAMPLE_LIMIT) { + send(event); + log('JIT leave ' + JSON.stringify(event)); + } + } + }); + log('Attached compilation observer: ' + layer + ' via=' + site.source + + ' at=' + site.address + ' name=' + site.name); + send({type: 'artwatch-hook-attached', layer, source: site.source, address: site.address.toString()}); + return true; + } catch (e) { + log('JIT hook failed for ' + layer + ': ' + (e.stack || e)); + return false; + } +} +// API 33 x86_64 only. Exact exported symbols were confirmed by readelf +// on the emulator binary. Observe graph identities; never mutate ART memory. +function attachGraphBoundary(layer, site) { + try { + Interceptor.attach(site.address, { + onEnter(args) { + this.nativeThread = this.threadId; + this.ordinal = ++count[layer]; + const active = compiling.get(this.nativeThread); + this.method = active ? active.method : null; + this.kind = active ? active.kind : null; + if (layer === 'graph_builder') { + this.builder = args[0].toString(); + // AOSP HGraphBuilder derives from ValueObject and its first member is + // graph_. This is an ABI-specific C++ layout hypothesis to validate. + try { this.graphCandidate = args[0].readPointer().toString(); } + catch (_) { this.graphCandidate = null; } + this.previousGraphBuild = activeGraphBuild.get(this.nativeThread); + activeGraphBuild.set(this.nativeThread, this.graphCandidate); + const state = targetStates.get(this.nativeThread); + if (state) state.constructionGraph = this.graphCandidate; + } else { + if (!shadowShim) loadPassiveShadow(); + // const OptimizingCompiler* this, HGraph*, CodeGenerator*, ... + this.previousOptimization = optimizationByThread.get(this.nativeThread); + optimizationByThread.set(this.nativeThread, args[1].toString()); + const state = targetStates.get(this.nativeThread); + if (state) state.optimizationEntries++; + this.graph = args[1].toString(); + const previous = builtByThread.get(this.nativeThread); + const matches = previous && previous.graphCandidate !== null + ? previous.graphCandidate === this.graph : null; + if (state && matches === true) { + const observation = {type:'artwatch-block-discovery', + method:this.method,compilationKind:this.kind,thread:this.nativeThread, + graph:this.graph,source:'HGraph::AddBlock', + uniqueBlocks:state.constructedBlocks.size, + unmatched:state.unmatchedBlockCalls, + samples:[...state.constructedBlocks].slice(0,12)}; + send(observation); + if (this.ordinal <= SAMPLE_LIMIT) + log('BLOCK_DISCOVERY ' + JSON.stringify(observation)); + } + if (state && matches === true) { + const event = {type:'artwatch-block-instruction-evidence', + method:this.method,compilationKind:this.kind,thread:this.nativeThread, + graph:this.graph, + addInstructionCalls:state.graphAddInstructionCalls, + fieldNodeInserts:state.fieldNodeInserts, + mappedFieldNodes:state.blockInstructionMap.size, + mappedExamples:[...state.blockInstructionMap.entries()].slice(0,8)}; + send(event); + if (this.ordinal <= SAMPLE_LIMIT) + log('BLOCK_INSTRUCTIONS ' + JSON.stringify(event)); + } + this.shadowScopeStarted = false; + if (shadowShim && matches === true) { + try { + const range = Process.findRangeByAddress(args[1]); + if (range && range.protection.includes('r') && + shadowShim.graph(args[1], ptr(previous.graphCandidate)) === 1) { + this.shadowScopeStarted = shadowShim.scopeBegin(args[1]) === 1; + if (!this.shadowScopeStarted) + log('native-shadow-scope-start-rejected graph=' + this.graph); + if (shadowGraphLogged++ < 14) + send({type:'artwatch-shadow-graph',method:this.method, + graph:this.graph,matched:true}); + } + } catch(e) { log('native-shadow-graph-error=' + e); } + } + const event = {type: 'artwatch-graph', phase: 'pre-opt', + ordinal: this.ordinal, thread: this.nativeThread, + method: this.method, kind: this.kind, graph: this.graph, + builderGraph: previous ? previous.graphCandidate : null, + graphMatchesBuilder: matches}; + if (this.ordinal <= SAMPLE_LIMIT) { + send(event); + log('GRAPH ' + JSON.stringify(event)); + } + } + }, + onLeave(_retval) { + if (layer === 'pre_opt') { + const state = targetStates.get(this.nativeThread); + if (state && state.visitorBlocks.size > 0) { + const orderEvent = {type:'artwatch-field-visit-order', + method:this.method,compilationKind:this.kind, + thread:this.nativeThread,graph:this.graph, + visitedBlockCalls:state.blockVisitOrdinal, + passesWithFields:state.fieldPassesObserved, + passesCaptured:state.fieldVisitOrderSamples.length, + truncatedFieldEntries:state.fieldOrderTruncated, + passes:state.fieldVisitOrderSamples}; + send(orderEvent); + if (this.ordinal <= SAMPLE_LIMIT) + log('FIELD_VISIT_ORDER ' + JSON.stringify({ + ...orderEvent,passes:orderEvent.passes.slice(0,3)})); + const fieldExamples = [...state.visitorFieldPairs.values()].slice(0,24); + const blockFieldEvent = {type:'artwatch-field-block-ownership', + method:this.method,compilationKind:this.kind, + thread:this.nativeThread,graph:this.graph, + correlatedVisits:state.visitorFieldVisits, + getVisits:state.visitorFieldGetVisits, + setVisits:state.visitorFieldSetVisits, + uniqueFieldNodes:state.visitorFieldNodes.size, + uniqueFieldBlockPairs:state.visitorFieldPairs.size, + visitorPointerMismatches:state.visitorPointerMismatch, + examples:fieldExamples}; + send(blockFieldEvent); + if (this.ordinal <= SAMPLE_LIMIT) + log('FIELD_BLOCK_OWNERSHIP ' + JSON.stringify(blockFieldEvent)); + const event = {type:'artwatch-block-visitor', + method:this.method,compilationKind:this.kind,thread:this.nativeThread, + graph:this.graph,uniqueBlocks:state.visitorBlocks.size, + newlySeenBlocks:state.visitorBlocksUnknown.size, + fieldVisitBlockMatches:state.fieldVisitBlockMatches, + samples:[...state.visitorBlocks].slice(0,12)}; + send(event); + if (this.ordinal <= SAMPLE_LIMIT) + log('BLOCK_VISITOR ' + JSON.stringify(event)); + } + if (state && state.checkerBlocks.size > 0) { + const event = {type:'artwatch-block-checker', + method:this.method,compilationKind:this.kind,thread:this.nativeThread, + graph:this.graph,uniqueBlocks:state.checkerBlocks.size, + samples:[...state.checkerBlocks].slice(0,12)}; + send(event); + if (this.ordinal <= SAMPLE_LIMIT) + log('BLOCK_CHECKER ' + JSON.stringify(event)); + } + if (this.shadowScopeStarted && shadowShim) { + try { + const buffer = Memory.alloc(512); + if (shadowShim.scopeEnd(buffer, 512) === 1) { + const result = JSON.parse(buffer.readUtf8String()); + const event = {type:'artwatch-shadow-scope', + method:this.method,compilationKind:this.kind, + thread:this.nativeThread, ...result}; + send(event); + if (this.ordinal <= SAMPLE_LIMIT) + log('SHADOW_SCOPE ' + JSON.stringify(event)); + } else { + log('native-shadow-scope-end-rejected method=' + this.method); + } + } catch(e) { log('native-shadow-scope-error=' + e); } + } + if (this.previousOptimization === undefined) optimizationByThread.delete(this.nativeThread); + else optimizationByThread.set(this.nativeThread, this.previousOptimization); + return; + } + if (layer !== 'graph_builder') return; + if (this.previousGraphBuild === undefined) activeGraphBuild.delete(this.nativeThread); + else activeGraphBuild.set(this.nativeThread, this.previousGraphBuild); + builtByThread.set(this.nativeThread, {graphCandidate: this.graphCandidate}); + const event = {type: 'artwatch-graph', phase: 'build-complete', + ordinal: this.ordinal, thread: this.nativeThread, + method: this.method, kind: this.kind, builder: this.builder, + graphCandidate: this.graphCandidate}; + if (this.ordinal <= SAMPLE_LIMIT) { + send(event); + log('GRAPH ' + JSON.stringify(event)); + } + } + }); + log('Attached graph observer: ' + layer + ' via=export at=' + site.address); + send({type: 'artwatch-hook-attached', layer, source: 'export', + address: site.address.toString()}); + return true; + } catch (e) { + log('Graph hook failed for ' + layer + ': ' + (e.stack || e)); + return false; + } +} +// Source-backed and optional read-only graph/block function hooks. + // The two entry points are probes, not required compiler ABI exports. +function attachBlockBoundary(layer, site) { + try { + Interceptor.attach(site.address, { + onEnter(args) { + const thread = this.threadId; + const state = targetStates.get(thread); + if (!state || !compiling.has(thread)) return; + if (layer === 'graph_add_block') { + const graph = args[0].toString(); + const candidate = state.constructionGraph; + if (candidate === null || graph !== candidate) { + state.unmatchedBlockCalls++; + return; + } + const block = args[1]; + if (block.isNull() || !Process.findRangeByAddress(block)) return; + if (!shadowShim) loadPassiveShadow(); + if (shadowShim && shadowShim.block(args[0], ptr(candidate), block) !== 1) { + log('native-shadow-block-validation-rejected'); + return; + } + if (state.constructedBlocks.size < 4096) + state.constructedBlocks.add(block.toString()); + } else { + // HGraphVisitor::VisitBasicBlock executes during baseline too. + // The previous RunOptimizations-only gate excluded all five + // field-target methods in the API33 debug trace. + if (layer === 'graph_checker_block' && + !optimizationByThread.has(thread)) return; + const block = args[1]; + if (block.isNull() || !Process.findRangeByAddress(block)) return; + if (layer === 'graph_checker_block') { + if (state.checkerBlocks.size < 4096) + state.checkerBlocks.add(block.toString()); + } else { + // Keep the active visitor+block pair only for the dynamic + // extent of this exact HGraphVisitor::VisitBasicBlock call. + // Frida onLeave restores nested calls without leaking state. + this.visitorBlockThread = thread; + this.previousVisitorBlock = activeVisitorBlockByThread.get(thread); + this.visitorBlockActive = true; + this.visitorBlockRecord = { + visitor: args[0].toString(), block: block.toString(), + callOrdinal: ++state.blockVisitOrdinal, + fieldCount: 0, fields: [] + }; + activeVisitorBlockByThread.set(thread,this.visitorBlockRecord); + if (state.visitorBlocks.size < 4096) + state.visitorBlocks.add(block.toString()); + // Inlining or loop transformations can add blocks after the + // construction boundary; log them, do not assume corruption. + if (!state.constructedBlocks.has(block.toString()) && + state.visitorBlocksUnknown.size < 4096) + state.visitorBlocksUnknown.add(block.toString()); + } + } + }, + onLeave() { + if (this.visitorBlockActive !== true) return; + const state = targetStates.get(this.visitorBlockThread); + const sample = this.visitorBlockRecord; + if (state && sample && sample.fieldCount > 0) { + state.fieldPassesObserved++; + if (state.fieldVisitOrderSamples.length < MAX_FIELD_PASSES) { + state.fieldVisitOrderSamples.push({ + block:sample.block, visitor:sample.visitor, + callOrdinal:sample.callOrdinal, + fieldCount:sample.fieldCount,fields:sample.fields, + constructed:state.constructedBlocks.has(sample.block) + }); + } + } + if (this.previousVisitorBlock === undefined) + activeVisitorBlockByThread.delete(this.visitorBlockThread); + else + activeVisitorBlockByThread.set(this.visitorBlockThread, + this.previousVisitorBlock); + } + }); + send({type:'artwatch-hook-attached',layer,source:'export', + address:site.address.toString()}); + log('Attached read-only block boundary=' + layer + ' at=' + site.address); + return true; + } catch(e) { + log('block-boundary-attach-error=' + layer + ' ' + (e.stack || e)); + return false; + } +} +// Observe DEX field operations as the compiler builds their IR. +// This does NOT identify HInstanceFieldGet/HInstanceFieldSet objects yet. +// It only provides a pre-optimization DEX PC + access-direction signal. +function attachFieldBuilder(access, site) { + try { + Interceptor.attach(site.address, { + onEnter(args) { + const thread = this.threadId; + const active = compiling.get(thread); + if (!active) return; + const ordinal = ++fieldCounts[access]; + this.fieldThread = thread; + this.previousFieldBuilder = activeFieldBuilder.get(thread); + this.hasFieldBuilder = true; + const instruction = args[1]; + let opcode = null; + let fieldIndexRaw = null; + try { + // DEX formats 22c (iget/iput) and 21c (sget/sput): + // opcode is byte 0; the two-byte C/B index occupies code unit 1. + opcode = instruction.readU8(); + fieldIndexRaw = instruction.add(2).readU16(); + } catch (e) { + log('field-instruction-read-failed=' + e); + } + const event = {type: 'artwatch-field-build', access, + method: active.method, compilationKind: active.kind, thread, + graphCandidate: activeGraphBuild.get(thread) || null, + dexPc: args[2].toUInt32(), isPut: args[3].toInt32() !== 0, + opcode, fieldIndexRaw, ordinal}; + activeFieldBuilder.set(thread, {...event, builder: args[0].toString()}); + // Keep the builder only in this live compilation's state. + // P3 requires ART to initialize a new invoke's SSA environment. + const targetState=targetStates.get(thread); + if (targetState && access==='instance' && + opcode===0x52 && !event.isPut) + targetState.p3Builder=args[0]; + // Identify self-contained field read/write methods from DEX patterns, + // not only the old iput@0/iget@2 pattern. The release fixture adds + // identity(this) between iput and iget so both survive D8. + if (access === 'instance' && fieldIndexRaw !== null && + (opcode === 0x59 || opcode === 0x52)) { + let byField = targetDexByMethod.get(active.method); + if (!byField) { + byField = new Map(); + targetDexByMethod.set(active.method, byField); + } + const prior = byField.get(fieldIndexRaw) || {bits: 0, putPc: null, getPc: null}; + const updated = { + bits: prior.bits | (opcode === 0x59 ? 1 : 2), + putPc: opcode === 0x59 ? event.dexPc : prior.putPc, + getPc: opcode === 0x52 ? event.dexPc : prior.getPc + }; + byField.set(fieldIndexRaw, updated); + if (updated.bits === 3 && !targetMethodPointers.has(active.method)) { + targetMethodPointers.add(active.method); + const identified = {type: 'artwatch-target-dex', + method: active.method, fieldIndexRaw, + dexPattern: 'iput+iget,same-field-index', + putPc: updated.putPc, getPc: updated.getPc}; + send(identified); + log('TARGET_DEX ' + JSON.stringify(identified)); + } + } + if (ordinal <= FIELD_SAMPLE_LIMIT) { + send(event); + log('FIELD_BUILD ' + JSON.stringify(event)); + } + }, + onLeave(_ret) { + if (!this.hasFieldBuilder) return; + if (this.previousFieldBuilder === undefined) activeFieldBuilder.delete(this.fieldThread); + else activeFieldBuilder.set(this.fieldThread, this.previousFieldBuilder); + } + }); + log('Attached field-builder observer: ' + access + ' at=' + site.address); + send({type: 'artwatch-hook-attached', layer: 'field_' + access, + source: 'export', address: site.address.toString()}); + return true; + } catch (e) { + log('field-builder-hook-error=' + access + ': ' + (e.stack || e)); + return false; + } +} +// Itanium C++ ABI: a complete-object vptr normally points 2 words past +// its exported primary vtable symbol. This is a candidate ABI mapping, +// validated by observed matches; not an assumed type ID or a layout parser. +function discoverFieldVtables(compiler) { + for (const [kind, symbol] of FIELD_VTABLE_SYMBOLS) { + const site = getExport(compiler, symbol); + if (site === null) { + log('field-vtable-not-exported=' + kind); + continue; + } + const addressPoint = site.address.add(2 * Process.pointerSize).toString(); + knownFieldVtables.set(addressPoint, kind); + log('field-vtable=' + kind + ' addressPoint=' + addressPoint); + } + send({type: 'artwatch-ir-vtables', available: Array.from(knownFieldVtables.values())}); +} +// The HInstructionBuilder::AppendInstruction argument is a constructed +// HInstruction*. HBasicBlock::AddInstruction is a version-specific fallback. +// Capture it only within active field-building calls and never mutate it. +function attachFieldNodeCandidate(site, source) { + try { + Interceptor.attach(site.address, { + onEnter(args) { + const thread = this.threadId; + insertionCounts[source]++; + // Independent out-of-line AddInstruction experiment. This call + // supplies HBasicBlock* and HInstruction* without decoding either. + // The original field-builder-context experiment remains below. + if (source === 'basic-block') { + const state = targetStates.get(thread); + const block = args[0].toString(); + if (state && state.constructedBlocks.has(block)) { + state.graphAddInstructionCalls++; + const kind = fieldKind(args[1]); + if (kind !== null && /Field(Get|Set)$/.test(kind)) { + state.fieldNodeInserts++; + if (state.blockInstructionMap.size < 4096) + state.blockInstructionMap.set(kind + '@' + args[1].toString(), block); + } + } + } + const field = activeFieldBuilder.get(thread); + if (!field) return; + if (source === 'append' && args[0].toString() !== field.builder) return; + const node = args[1].toString(); + // An append forwarding into AddInstruction is one logical insertion. + if (!field.seenNodes) field.seenNodes = new Set(); + if (field.seenNodes.has(node)) return; + field.seenNodes.add(node); + const ordinal = ++observedFieldNodeCandidates; + if (ordinal > FIELD_NODE_SAMPLE_LIMIT) return; + let vtable = null; + let kind = null; + try { + vtable = args[1].readPointer().toString(); + kind = knownFieldVtables.get(vtable) || null; + } catch (e) { + log('field-node-vtable-read-failed=' + e); + } + const event = {type: 'artwatch-ir-node', source, + access: field.access, isPut: field.isPut, fieldIndexRaw: field.fieldIndexRaw, + dexPc: field.dexPc, opcode: field.opcode, graphCandidate: field.graphCandidate, + method: field.method, compilationKind: field.compilationKind, + thread, ordinal, node, vtable, kind}; + send(event); + log('IR_NODE ' + JSON.stringify(event)); + } + }); + log('Attached field IR append observer via=' + source + ' at=' + site.address); + send({type: 'artwatch-hook-attached', layer: 'ir_append', + source, address: site.address.toString()}); + return true; + } catch (e) { + log('field-node-hook-error=' + source + ': ' + (e.stack || e)); + return false; + } +} +// Every HInstruction field subclass has a virtual Accept(HGraphVisitor*). +// On this API 33 ELF some of those functions are exported even when the +// builder's call to AppendInstruction has been inlined into its caller. +// These are observation-only callbacks during normal ART visitor passes. +function attachFieldAccept(compiler) { + let attached = 0; + for (const [kind, symbol] of FIELD_VTABLE_SYMBOLS) { + const acceptName = symbol.replace('_ZTVN', '_ZN').replace(/E$/, '6AcceptEPNS_13HGraphVisitorE'); + const site = getExport(compiler, acceptName); + if (!site) { + log('field-accept-not-exported=' + kind); + continue; + } + try { + Interceptor.attach(site.address, { + onEnter(args) { + const thread = this.threadId; + const compilation = compiling.get(thread); + if (!compilation) return; + const ordinal = ++observedFieldAccepts; + const node = args[0].toString(); + const visitor = args[1].toString(); + let vtable = null; + try { vtable = args[0].readPointer().toString(); } + catch (e) { log('field-accept-vtable-read-failed=' + e); } + const inferred = vtable ? knownFieldVtables.get(vtable) || null : null; + if (!shadowShim) loadPassiveShadow(); + if (shadowShim && inferred === kind && + (kind === 'HInstanceFieldGet' || kind === 'HInstanceFieldSet')) { + try { + const vt = getExport(compiler, symbol); + if (vt && shadowShim.node(args[0], vt.address, + kind === 'HInstanceFieldGet' ? 1 : 2) === 1 && + shadowNodeLogged++ < 16) { + send({type:'artwatch-shadow-node',kind,node,thread, + method:compilation.method,compilationKind:compilation.kind}); + } + } catch(e) { log('native-shadow-node-error=' + e); } + } + const phase = optimizationByThread.has(thread) ? 'optimizing' : + (activeGraphBuild.has(thread) ? 'building' : 'other'); + // Join a vtable-confirmed instruction with its containing block + // only when a real AddInstruction callback supplied both pointers. + const blockState = targetStates.get(thread); + if (blockState && + blockState.blockInstructionMap.has(kind + '@' + node)) { + blockState.fieldVisitBlockMatches++; + } + // ART's source-backed VisitBasicBlock iterates the instruction + // list and invokes instruction->Accept(this). Match the actual + // visitor object (args[1]) rather than guessing HInstruction + // block_ offsets. This is only a *visited* block ownership record, + // not construction-time insertion or a stable post-pass layout. + const currentBlock = activeVisitorBlockByThread.get(thread); + if (blockState && currentBlock && + phase === 'optimizing' && inferred === kind) { + if (currentBlock.visitor === visitor) { + const isGet = /FieldGet$/.test(kind); + const isSet = /FieldSet$/.test(kind); + if (isGet || isSet) { + // Captures only relative order of *field* instructions + // encountered by one real VisitBasicBlock traversal. + // Other IR instructions and phi nodes are omitted. + const position = currentBlock.fieldCount++; + if (currentBlock.fields.length < MAX_FIELDS_PER_PASS) { + currentBlock.fields.push({kind,node,ordinal:position}); + } else { + blockState.fieldOrderTruncated++; + } + const id = kind + '@' + node; + const pairId = id + '|block=' + currentBlock.block; + blockState.visitorFieldVisits++; + if (isGet) blockState.visitorFieldGetVisits++; + if (isSet) blockState.visitorFieldSetVisits++; + if (blockState.visitorFieldNodes.size < 4096 && + !blockState.visitorFieldNodes.has(id)) + blockState.visitorFieldNodes.set(id, currentBlock.block); + if (blockState.visitorFieldPairs.size < 4096) { + const existing = blockState.visitorFieldPairs.get(pairId); + if (existing) existing.visits++; + else blockState.visitorFieldPairs.set(pairId, { + kind,node,block:currentBlock.block,visits:1, + constructed: blockState.constructedBlocks.has(currentBlock.block) + }); + } + } + } else { + blockState.visitorPointerMismatch++; + } + } + if (targetMethodPointers.has(compilation.method)) { + const state = targetStates.get(thread); + if (state) { + state.seenKinds.add(kind); + state.uniqueNodes.add(kind + '@' + node); + const key = kind + '@' + node + '/' + phase; + if (!state.seenVisits.has(key)) { + state.seenVisits.add(key); + state.visitsByPhase[phase] = (state.visitsByPhase[phase] || 0) + 1; + reportTargetEvent(state, {type:'artwatch-target-ir', + kind, node, phase, method: compilation.method, + compilationKind: compilation.kind, thread, + vtableMatches: inferred === kind}); + } + } + } + if (ordinal > FIELD_NODE_SAMPLE_LIMIT) return; + const event = {type: 'artwatch-ir-visit', source: 'accept', + ordinal, kind, vtableKind: inferred, vtableMatches: inferred === kind, + node, vtable, visitor, thread, method: compilation.method, + compilationKind: compilation.kind, + phase}; + send(event); + log('IR_VISIT ' + JSON.stringify(event)); + } + }); + attached++; + log('Attached field Accept observer kind=' + kind + ' at=' + site.address); + send({type: 'artwatch-hook-attached', layer: 'ir_accept', kind, + source: 'export', address: site.address.toString()}); + } catch (e) { log('field-accept-hook-error=' + kind + ': ' + e); } + } + log('field-accept-hooks=' + attached); +} +// Candidate mutation boundaries. Only inspect a field node's vptr on an +// active JIT thread, and never call ReplaceWith/RemoveInstruction ourselves. +function attachMutationObserver(site, op) { + try { + Interceptor.attach(site.address, { + onEnter(args) { + const thread = this.threadId; + const compilation = compiling.get(thread); + const state = targetStates.get(thread); + if (!compilation || !state) return; + mutationHookCounts[op]++; + if (op === 'lse') { + this.lseThread = thread; + this.lseMethod = compilation.method; + this.lseKind = compilation.kind; + this.lsePrevious = lseByThread.get(thread); + lseByThread.set(thread, true); + state.lseInvocations++; + this.lseReport = lseTraceEmitted++ < LSE_TRACE_LIMIT; + if (this.lseReport) { + const event = {type:'artwatch-lse', phase:'enter', + method:compilation.method, compilationKind:compilation.kind, + thread, isFieldTarget:targetMethodPointers.has(compilation.method), + partialMode: args[1].toInt32() !== 0}; + send(event); + log('LSE ' + JSON.stringify(event)); + } + if (targetMethodPointers.has(compilation.method)) { + reportTargetEvent(state, {type:'artwatch-target-lse-enter', + method:compilation.method, compilationKind:compilation.kind, + thread}); + } + return; + } + // Observe all field instructions, not just a fixture method whose + // redundant load may already have disappeared in release DEX. + const instruction = op === 'replace' ? args[0] : args[1]; + const kind = fieldKind(instruction); + if (!kind) return; + const replacement = op === 'replace' ? args[1] : + (op === 'replace_remove' ? args[2] : null); + const record = {op, kind, node: instruction.toString(), + substitute: replacement === null ? null : replacement.toString(), + substituteKind: replacement === null ? null : classifySSAValue(replacement), + duringLse: lseByThread.has(thread), + duringOptimizations: optimizationByThread.has(thread), + visitedBeforeMutation: targetMethodPointers.has(compilation.method) + ? state.uniqueNodes.has(kind + '@' + instruction.toString()) : null}; + if (fieldMutationTraceEmitted++ < FIELD_MUTATION_TRACE_LIMIT) { + const event = {type:'artwatch-field-ir-mutation', + method:compilation.method, compilationKind:compilation.kind, + thread, isFieldTarget:targetMethodPointers.has(compilation.method), + ...record}; + send(event); + log('FIELD_MUTATION ' + JSON.stringify(event)); + } + if (targetMethodPointers.has(compilation.method)) { + state.mutations.push(record); + reportTargetEvent(state, {type:'artwatch-ir-mutation', + method:compilation.method, compilationKind:compilation.kind, + thread, ...record}); + } + }, + onLeave(retval) { + if (op !== 'lse' || this.lseThread === undefined) return; + if (this.lseReport) { + const event = {type:'artwatch-lse', phase:'exit', + method:this.lseMethod, compilationKind:this.lseKind, + thread:this.lseThread, result:retval.and(0xff).toInt32() !== 0}; + send(event); + log('LSE ' + JSON.stringify(event)); + } + if (this.lsePrevious === undefined) lseByThread.delete(this.lseThread); + else lseByThread.set(this.lseThread, this.lsePrevious); + } + }); + log('Attached mutation observer=' + op + ' at=' + site.address); + send({type:'artwatch-hook-attached',layer:'ir_mutation_' + op, + source:'export',address:site.address.toString()}); + return true; + } catch (e) { log('mutation-observer-error=' + op + ': ' + e); return false; } +} +// ART x86_64 backend visitors receive a concrete field HInstruction*. + // LocationsBuilder runs after IR optimizations; InstructionCodeGenerator + // emits machine instructions for the surviving nodes. This is a + // read-only estimate of which field nodes reach the lowering boundary. +function attachBackendFieldVisitor(compiler, symbol, stage, expectedKind) { + const site = getExport(compiler, symbol); + if (!site) { + log('backend-field-export-not-found stage=' + stage + ' kind=' + expectedKind); + return false; + } + try { + Interceptor.attach(site.address, { + onEnter(args) { + const thread = this.threadId; + const active = compiling.get(thread); + if (!active) return; + const node = args[1].toString(); + const observedKind = fieldKind(args[1]); + if (observedKind !== expectedKind) { + log('backend-kind-mismatch expected=' + expectedKind + + ' observed=' + observedKind); + return; + } + const state = targetStates.get(thread); + if (state) { + const key = expectedKind + '@' + node; + if (stage === 'locations') state.backendLocations.add(key); + else state.backendEmitted.add(key); + } + backendCounts[stage]++; + const ordinal = ++backendVisitOrdinal; + if (ordinal > BACKEND_VISIT_LIMIT) return; + const event = {type: 'artwatch-backend-field', + stage, expectedKind, node, ordinal, thread, + method: active.method, compilationKind: active.kind, + isFieldTarget: targetMethodPointers.has(active.method)}; + send(event); + log('BACKEND_FIELD ' + JSON.stringify(event)); + } + }); + send({type:'artwatch-hook-attached',layer:'backend_field_' + stage, + kind:expectedKind,source:'export',address:site.address.toString()}); + log('Attached backend field=' + stage + ' kind=' + expectedKind + + ' at=' + site.address); + return true; + } catch (e) { + log('backend-field-hook-error=' + stage + ' ' + expectedKind + ': ' + e); + return false; + } +} +// Inspect a live invoke's immediate predecessor and at most seven earlier +// instructions, without relying on a field Accept callback having run first. +// The previous observation had 0 *attempted* probes: lastGet was never set +// in the same visitor scope as an invoke. Do not infer non-adjacency from that. +// +// Android 13 x86_64 Itanium ABI layout under exact mapped Build-ID gate: +// vptr +0, HInstruction::previous_ +8, next_ +16, block_ +24. +// Frida readPointer throws on unreadable memory; the native shim confirms +// matching reciprocal links only when a direct get predecessor is found. +// This is read-only and never retains HInstruction* past this callback. +function observeInvokePredecessors(node, scope, getVtable, invokeVtable) { + const size = Process.pointerSize; + const expectedBlock = scope ? ptr(scope.block) : null; + const expectedGet = getVtable.address.add(2 * size); + let block; + try { + block = node.add(3 * size).readPointer(); + if (block.isNull() || !Process.findRangeByAddress(block)) + return {reason:'block'}; + if (expectedBlock !== null && !block.equals(expectedBlock)) + return {reason:'block'}; + let cursor = node; + for (let depth = 1; depth <= 8; depth++) { + const previous = cursor.add(size).readPointer(); + if (previous.isNull()) return {reason:'no-get'}; + const mapped = Process.findRangeByAddress(previous); + if (!mapped || !mapped.protection.includes('r')) return {reason:'links'}; + if (!previous.add(2 * size).readPointer().equals(cursor) || + !previous.add(3 * size).readPointer().equals(block)) + return {reason:'links'}; + const previousVtable = previous.readPointer(); + if (previousVtable.equals(expectedGet)) { + if (depth === 1 && shadowShim && shadowShim.linkedGetInvoke) { + const rc = shadowShim.linkedGetInvoke( + previous,node,getVtable.address,invokeVtable.address); + return {reason:rc === 1 ? 'direct' : 'rejected',depth, + get:previous.toString()}; + } + return {reason:'nearby',depth,get:previous.toString()}; + } + cursor = previous; + } + return {reason:'no-get'}; + } catch (_) { + return {reason:'links'}; + } +} +function attachExistingInvokeObserver(compiler) { + const site = getExport(compiler, INVOKE_ACCEPT); + const vt = getExport(compiler, INVOKE_VTABLE); + send({type:'artwatch-existing-invoke-abi',acceptExported:site !== null, + vtableExported:vt !== null,writesArtMemory:false}); + if (!site || !vt) return false; + const expected = vt.address.add(2 * Process.pointerSize); + const getVtable = getExport(compiler, '_ZTVN3art17HInstanceFieldGetE'); + try { + Interceptor.attach(site.address, { + onEnter(args) { + const thread = this.threadId; + const active = compiling.get(thread); + if (!active) return; + try { + if (!args[0].readPointer().equals(expected)) return; + } catch (_) { return; } + const scope = activeVisitorBlockByThread.get(thread); + const matchesBlock = !!scope && scope.visitor === args[1].toString(); + const state = targetStates.get(thread); + // For this read-only layout walk, require the native shim's exact + // runtime/compiler ELF IDs; never probe unknown Android builds. + const fieldTarget = targetMethodPointers.has(active.method); + // A baseline compiler may run Invoke::Accept without an active + // HGraphVisitor::VisitBasicBlock scope. Use the live invoke's own + // basic-block pointer for that exact field-target compilation. + if (state && (matchesBlock || fieldTarget) && getVtable && shadowShim && + state.adjacencyProbes < 256) { + const seen = observeInvokePredecessors( + args[0],matchesBlock ? scope : null,getVtable,vt); + state.adjacencyProbes++; + if (fieldTarget) state.targetAdjacencyProbes++; + switch (seen.reason) { + case 'direct': state.adjacencyMatches++; break; + case 'nearby': state.adjacencyWithin8++; break; + case 'block': state.adjacencyBlockMismatch++; break; + case 'links': state.adjacencyBrokenLinks++; break; + case 'no-get': state.adjacencyNoGetWithin8++; break; + default: state.adjacencyRejected++; break; + } + if (seen.get) { + // Match the get's actual live C++ DEX PC to the DEX-PC + // observed by HInstructionBuilder *for this ArtMethod*. + // This prevents mistaking another field get for the P3 template. + let getDexPc = null, invokeDexPc = null; + if (shadowShim.instructionDexPc) { + const p = Memory.alloc(4); + if (shadowShim.instructionDexPc( + ptr(seen.get),getVtable.address,p) === 1) + getDexPc = p.readU32(); + if (shadowShim.instructionDexPc( + args[0],vt.address,p) === 1) + invokeDexPc = p.readU32(); + } + let expectedField = null; + let pcMatch = false; + const known = targetDexByMethod.get(active.method); + if (known && getDexPc !== null) { + for (const [fieldIndex, field] of known) { + if (field.getPc === getDexPc) { + expectedField = fieldIndex; + pcMatch = true; + break; + } + } + } + if (fieldTarget) { + if (pcMatch) state.targetGetPcMatches++; + else if (getDexPc === null || !known) state.targetGetPcUnavailable++; + else state.targetGetPcMismatches++; + } + if (state.adjacencySamples.length < 12) + state.adjacencySamples.push({ + get:seen.get,invoke:args[0].toString(), + block:matchesBlock ? scope.block : null,depth:seen.depth, + fieldTarget,getDexPc,invokeDexPc,expectedField,pcMatch}); + } + if (state.adjacencyPreviousSamples.length < 12) + state.adjacencyPreviousSamples.push({ + node:args[0].toString(),reason:seen.reason, + depth:seen.depth || null, + block:matchesBlock ? scope.block : null,fieldTarget}); + } + if (state) { + state.existingInvokeVisits++; + if (state.existingInvokeNodes.size < 4096) + state.existingInvokeNodes.add(args[0].toString()); + if (matchesBlock) state.existingInvokeBlockVisits++; + } + const ordinal = ++existingInvokeCount; + if (ordinal > MAX_EXISTING_INVOKES) return; + send({type:'artwatch-existing-invoke',node:args[0].toString(), + method:active.method,compilationKind:active.kind,thread,ordinal, + inOptimization:optimizationByThread.has(thread), + block:matchesBlock ? scope.block : null}); + } + }); + send({type:'artwatch-hook-attached',layer:'existing_invoke_accept', + source:'export',address:site.address.toString()}); + return true; + } catch(e) { + log('existing-invoke-hook-error=' + e); + return false; + } +} +// Verify stock ART's real x86_64 invoke backend on the same node identity. +// Both callbacks are read-only. A successful compilation with an emitted +// invoke establishes codegen reachability, not field-event insertion. +function attachExistingInvokeBackend(compiler, symbol, stage) { + const site = getExport(compiler,symbol); + const vt = getExport(compiler,INVOKE_VTABLE); + if (!site || !vt) { + send({type:'artwatch-invoke-backend-availability',stage,available:false}); + return false; + } + const expected = vt.address.add(2 * Process.pointerSize); + try { + Interceptor.attach(site.address,{ + onEnter(args) { + const thread=this.threadId; + const active=compiling.get(thread); + const state=targetStates.get(thread); + if (!active || !state) return; + const node=args[1]; + try { if (!node.readPointer().equals(expected)) return; } + catch (_) { return; } + const key=node.toString(); + if (stage==='locations') state.existingInvokeLocations.add(key); + else state.existingInvokeEmitted.add(key); + } + }); + send({type:'artwatch-hook-attached',layer:'existing_invoke_'+stage, + source:'export',address:site.address.toString()}); + return true; + } catch(e) { + log('existing-invoke-backend-attach-error='+stage+' '+e); + return false; + } +} +// The first opt-in compiler mutation. Only a packaged APK fixture can +// enable this. We clone the already-resolved zero-site native sink invoke, +// preserving the original SSA value and using ART's own AppendInstruction +// to attach and initialize it. No allocation or object mutation in JS. +function attachP3CloneCanary(compiler) { + if (globalThis.__artwatchP3Inject !== true) return false; + const fixture=globalThis.__artwatchP3Fixture; + if (!fixture || ['setDexPc','writeInvokeDexPc','getDexPc','readInvokeDexPc'] + .some(k=>!Number.isInteger(fixture[k]))) return false; + const site=getExport(compiler,INVOKE_ACCEPT); + const insert=getExport(compiler, + '_ZN3art11HBasicBlock23InsertInstructionBeforeEPNS_12HInstructionES2_'); + const copyEnv=getExport(compiler,'_ZN3art12HEnvironment8CopyFromEPS0_'); + const invokeVt=getExport(compiler,INVOKE_VTABLE); + const getVt=getExport(compiler,'_ZTVN3art17HInstanceFieldGetE'); + const setVt=getExport(compiler,'_ZTVN3art17HInstanceFieldSetE'); + if (!site || !insert || !copyEnv || !invokeVt || !getVt || !setVt) + return false; + let cloning=false; + const successfulKinds=new Set(); + let successfulMethod=null; + let attempts=0; + let missedBuilder=0; + try { + Interceptor.attach(site.address,{ + onEnter(args) { + if (cloning || successfulKinds.size===2) return; + const thread=this.threadId; + const active=compiling.get(thread); + const state=targetStates.get(thread); + if (!active || !state || !targetMethodPointers.has(active.method) || + (successfulMethod!==null && successfulMethod!==active.method)) + return; + if (!shadowShim) loadPassiveShadow(); + if (!shadowShim || !shadowShim.cloneBefore || + !shadowShim.instructionDexPc) return; + const node=args[0]; + const size=Process.pointerSize; + try { + if (!node.readPointer().equals(invokeVt.address.add(2*size))) + return; + const pc=Memory.alloc(4); + if (shadowShim.instructionDexPc(node,invokeVt.address,pc)!==1) + return; + const invokePc=pc.readU32(); + const isWrite=invokePc===fixture.writeInvokeDexPc; + const isRead=invokePc===fixture.readInvokeDexPc; + if (!isWrite && !isRead) return; + const kind=isWrite?'write':'read'; + if (successfulKinds.has(kind)) return; + const fieldVt=isWrite?setVt:getVt; + const fieldPc=isWrite?fixture.setDexPc:fixture.getDexPc; + if (isRead) { + // Read case remains the verified adjacent get -> invoke path. + const previous=node.add(size).readPointer(); + if (previous.isNull() || + !previous.readPointer().equals(fieldVt.address.add(2*size))) + return; + if (shadowShim.instructionDexPc(previous,fieldVt.address,pc)!==1 || + pc.readU32()!==fieldPc) return; + } + // For stores, ART can insert an HIntConstant between iput and + // invoke. The build-ID-gated native routine walks and verifies + // up to eight reciprocal links in the same HBasicBlock. + // Same-graph clone immediately before original invoke. + // No HInstructionBuilder state is required, so this also works + // when ART inlines AppendInstruction. + attempts++; + cloning=true; + try { + const cloneOut=Memory.alloc(size); + cloneOut.writePointer(ptr(0)); + const rc=shadowShim.cloneBefore(node, + fieldVt.address,invokeVt.address, + fieldPc,invokePc,insert.address,copyEnv.address, + isWrite?2:1,cloneOut); + const cloned=rc===1 ? cloneOut.readPointer() : ptr(0); + send({type:'artwatch-p3-clone',rc,method:active.method, + kind,attempt:attempts,trigger:'invoke_accept', + clonedNode:cloned.isNull()?null:cloned.toString(), + fieldDexPc:fieldPc,invokeDexPc:invokePc}); + if (rc===1 && !cloned.isNull()) { + state.p3ClonedNodes.set(kind,cloned.toString()); + if (successfulMethod===null) successfulMethod=active.method; + successfulKinds.add(kind); + if (successfulKinds.size===2) p3PendingMethod=active.method; + } else if (rc===1) { + send({type:'artwatch-p3-clone-error',method:active.method, + error:'native insertion returned success without a clone identity'}); + } + } finally {cloning=false;} + } catch(e) { + cloning=false; + send({type:'artwatch-p3-clone-error',error:String(e), + method:active.method}); + } + } + }); + send({type:'artwatch-hook-attached',layer:'p3_clone_canary', + address:site.address.toString(),source:'invoke-accept'}); + return true; + } catch(e) { + send({type:'artwatch-p3-clone-error',error:String(e)}); + return false; + } +} +function main() { + const api = sdkLevel(); + log('pid=' + Process.id + ' arch=' + Process.arch + + ' pointerSize=' + Process.pointerSize + ' api=' + api); + const modules = Process.enumerateModules().filter(m => artLibraries.has(m.name)); + for (const module of modules) { + log('module=' + module.name + ' base=' + module.base + ' path=' + module.path); + // Targeted export lookup avoids potentially fragile full export-table scans + // in injected processes (especially API 33 in earlier CI attempts). + for (const name of [NAMES.internal, NAMES.publicCompile, + NAMES.compiler, NAMES.instance, NAMES.buildGraph, + NAMES.runOptimizations, NAMES.graphAddBlock, + NAMES.graphCheckerBlock, NAMES.graphVisitorBlock, + NAMES.graphVisitorInsertion, NAMES.graphVisitorRpo, + NAMES.fieldInstance, + NAMES.fieldStatic, NAMES.appendInstruction, + NAMES.addInstruction, NAMES.replaceWith, + NAMES.replaceAndRemove, NAMES.removeInstruction, + NAMES.removeInstructionOrPhi, NAMES.lseRun, + NAMES.x64LocationsFieldGet, NAMES.x64LocationsFieldSet, + NAMES.x64EmitFieldGet, NAMES.x64EmitFieldSet, + NAMES.lseRunBool, 'jit_load']) { + try { + const site = getExport(module, name); + if (site) log('export=' + module.name + ' name=' + name + + ' address=' + site.address); + } catch (e) { log('export-lookup-error ' + name + ': ' + e); } + } + } + // Only claim argument decoding for the tested, architecture-specific ABI profiles. + if (Process.pointerSize !== 8 || !['x64', 'arm64'].includes(Process.arch) || + ![33, 34].includes(api)) { + log('Inventory only: ABI profile not enabled'); return; + } + const runtime = modules.find(m => m.name === 'libart.so' || m.name === 'libartd.so'); + const compiler = modules.find(m => m.name === 'libart-compiler.so' || + m.name === 'libartd-compiler.so'); + let hooked = 0; + if (runtime) { + const internal = getExport(runtime, NAMES.internal); + if (internal) { + hooked += Number(attach('runtime_internal', + {address: internal.address, name: internal.name, source: 'export'})); + } else { + log('runtime-internal-export=not-found'); + } + } + if (runtime && compiler) { + const exported = getExport(compiler, NAMES.compiler); + const fromVtable = compilerViaVtable(runtime, compiler); + if (exported && fromVtable && !exported.address.equals(fromVtable.address)) + log('compiler-export-vtable-address-mismatch export=' + exported.address + + ' vtable=' + fromVtable.address); + const site = exported + ? {address: exported.address, name: exported.name, source: 'export'} + : fromVtable; + if (site) hooked += Number(attach('compiler', site)); + else log('compiler-boundary=not-found'); + } + // Strictly gate read-only compiler IR observation to the tested export profile. + if (api === 33 && Process.arch === 'x64' && compiler) { + for (const [layer, name] of [ + ['graph_builder', NAMES.buildGraph], + ['pre_opt', NAMES.runOptimizations] + ]) { + const site = getExport(compiler, name); + if (site) attachGraphBoundary(layer, site); + else log('graph-boundary-not-exported=' + layer); + } + for (const [access, name] of [ + ['instance', NAMES.fieldInstance], + ['static', NAMES.fieldStatic] + ]) { + const site = getExport(compiler, name); + if (site) attachFieldBuilder(access, site); + else log('field-builder-not-exported=' + access); + } + for (const [layer, name] of [ + ['graph_add_block', NAMES.graphAddBlock], + ['graph_checker_block', NAMES.graphCheckerBlock], + ['graph_visitor_block', NAMES.graphVisitorBlock] + ]) { + const site = getExport(compiler, name); + if (site) attachBlockBoundary(layer, site); + else log('block-boundary-not-exported=' + layer); + } + for (const [role, symbol] of [ + ['insertion-order', NAMES.graphVisitorInsertion], + ['reverse-post-order', NAMES.graphVisitorRpo] + ]) { + const site = getExport(compiler, symbol); + // Only record export availability. Calling these methods ourselves + // would require constructing a valid ART visitor object. + log('graph-traversal-export ' + role + '=' + + (site ? site.address : 'not-exported')); + } + discoverFieldVtables(compiler); + discoverValueVtables(compiler); + attachExistingInvokeObserver(compiler); + attachP3CloneCanary(compiler); + attachExistingInvokeBackend(compiler,INVOKE_BACKEND_LOCATIONS,'locations'); + attachExistingInvokeBackend(compiler,INVOKE_BACKEND_EMISSION,'emission'); + // The app's onCreate() has not run at agent load time. Resolve the + // already-loaded shim lazily from compiler callbacks instead. + loadPassiveShadow(); + // Do not assume the builder's exported AppendInstruction is called. + // Both out-of-line functions can coexist with inlined call sites. + const append = getExport(compiler, NAMES.appendInstruction); + const add = getExport(compiler, NAMES.addInstruction); + const appendHook = append ? attachFieldNodeCandidate(append, 'append') : false; + const addHook = add ? attachFieldNodeCandidate(add, 'basic-block') : false; + log('ir-insertion-hooks=' + JSON.stringify({append: appendHook, add: addHook})); + attachFieldAccept(compiler); + for (const [stage, kind, symbol] of [ + ['locations', 'HInstanceFieldGet', NAMES.x64LocationsFieldGet], + ['locations', 'HInstanceFieldSet', NAMES.x64LocationsFieldSet], + ['emission', 'HInstanceFieldGet', NAMES.x64EmitFieldGet], + ['emission', 'HInstanceFieldSet', NAMES.x64EmitFieldSet] + ]) attachBackendFieldVisitor(compiler, symbol, stage, kind); + for (const [op, names] of [ + ['replace', [NAMES.replaceWith]], + ['replace_remove', [NAMES.replaceAndRemove]], + ['remove', [NAMES.removeInstruction]], + ['remove_or_phi', [NAMES.removeInstructionOrPhi]], + ['lse', [NAMES.lseRun, NAMES.lseRunBool]] + ]) { + const site = names.map(n => getExport(compiler, n)).find(p => p !== null); + if (site) attachMutationObserver(site, op); + else log('mutation-boundary-not-exported=' + op); + } + } else { + log('graph-boundaries=disabled (unverified binary profile)'); + } + log('compile-hooks=' + hooked); + log('No field interception or compiler IR mutation implemented'); +} +// Host-facing runtime event transport. Does not rely on compiler tracing. +// This is a real JNI event recorder populated by executed application code. +rpc.exports = { + jvmtievents() { + const module=Process.findModuleByName('libartwatch_jvmti.so'); + if (!module) return {ready:false,reason:'JVMTI agent not loaded'}; + const address=module.findExportByName('artwatch_jvmti_snapshot'); + if (!address) return {ready:false,reason:'JVMTI snapshot export absent'}; + const fn=new NativeFunction(address,'int',['pointer','uint']); + const buffer=Memory.alloc(65536); + if (fn(buffer,65536)!==1) return {ready:false,reason:'JVMTI snapshot incomplete'}; + return {ready:true,...JSON.parse(buffer.readUtf8String())}; + }, + p3fieldmeta() { + const module = Process.findModuleByName('libartwatch_events.so'); + if (!module) return {ready:false,reason:'native event module not loaded'}; + const address = module.findExportByName('artwatch_events_p3_field_snapshot'); + if (address === null) return {ready:false,reason:'P3 metadata archive absent'}; + const snapshot = new NativeFunction(address,'int',['pointer','uint']); + const buffer=Memory.alloc(65536); + if (snapshot(buffer,65536)!==1) + return {ready:false,reason:'P3 metadata not verified'}; + return {ready:true,...JSON.parse(buffer.readUtf8String())}; + }, + fieldmeta() { + const module = Process.findModuleByName('libartwatch_events.so'); + if (!module) return {ready:false,reason:'native event module not loaded'}; + const address = module.findExportByName('artwatch_events_field_snapshot'); + if (address === null) return {ready:false,reason:'metadata export absent'}; + const snapshot = new NativeFunction(address,'int',['pointer','uint']); + const buffer = Memory.alloc(524288); + if (snapshot(buffer,524288) !== 1) + return {ready:false,reason:'metadata event buffer not ready or full'}; + return {ready:true,...JSON.parse(buffer.readUtf8String())}; + }, + p3events() { + const module = Process.findModuleByName('libartwatch_events.so'); + if (!module) return {ready:false,reason:'native event module not loaded'}; + const address = module.findExportByName('artwatch_events_p3_snapshot'); + if (address === null) return {ready:false,reason:'P3 archive export absent'}; + const snapshot = new NativeFunction(address,'int',['pointer','uint']); + const buffer = Memory.alloc(65536); + if (snapshot(buffer,65536) !== 1) + return {ready:false,reason:'P3 archive not verified or buffer insufficient'}; + return {ready:true,...JSON.parse(buffer.readUtf8String())}; + }, + runtimeevents() { + const module = Process.findModuleByName('libartwatch_events.so'); + if (!module) return {ready:false,reason:'native event module not loaded'}; + const address = module.findExportByName('artwatch_events_snapshot'); + if (address === null) return {ready:false,reason:'snapshot export absent'}; + const snapshot = new NativeFunction(address,'int',['pointer','uint']); + const buffer = Memory.alloc(65536); + if (snapshot(buffer,65536) !== 1) + return {ready:false,reason:'event publication incomplete or buffer insufficient'}; + return {ready:true,...JSON.parse(buffer.readUtf8String())}; + } +}; +main(); diff --git a/art-fieldwatch-phase1/native/jvmti-fieldwatch.cc b/art-fieldwatch-phase1/native/jvmti-fieldwatch.cc new file mode 100644 index 0000000..4c16dbd --- /dev/null +++ b/art-fieldwatch-phase1/native/jvmti-fieldwatch.cc @@ -0,0 +1,193 @@ +// Android ART/JVMTI no-template field watch backend (API 28+, debuggable). +// This intentionally does not claim coverage in non-debuggable applications. +// Read events are JVMTI notifications BEFORE the load: primitive values are +// sampled by JNI and can race another thread's write. Write events contain +// JVMTI's proposed value, not a guarantee the store ultimately committed. +// The ART compiler-injection path remains required for exact successful reads. +#include +#include +#include +#include +#include +#include +#include + +#define AW_EXPORT extern "C" __attribute__((visibility("default"))) +#define AW_LOG(...) __android_log_print(ANDROID_LOG_INFO,"ARTWATCH_JVMTI",__VA_ARGS__) + +namespace { +constexpr uint32_t kCapacity=256; +struct Entry { + uint32_t kind; + int64_t location; + uint64_t bits; + char field[48]; + char method[48]; +}; +Entry entries[kCapacity]={}; +std::atomic next_entry{0}, watched{0}; +char wanted[192]="Lcom/example/artfieldwatch/JvmtiTarget;"; +thread_local bool in_callback=false; + +void Dealloc(jvmtiEnv* ti,char* str) { + if (str!=nullptr) ti->Deallocate(reinterpret_cast(str)); +} +void Copy(char* out,size_t size,const char* value) { + if (size==0) return; + snprintf(out,size,"%s",value==nullptr?"?":value); +} +uint64_t Bits(jvalue v,char signature) { + uint32_t narrow=0; + uint64_t wide=0; + switch(signature) { + case 'Z': return v.z?1u:0u; + case 'B': return static_cast(static_cast(v.b)); + case 'C': return static_cast(v.c); + case 'S': return static_cast(static_cast(v.s)); + case 'I': return static_cast(static_cast(v.i)); + case 'J': return static_cast(v.j); + case 'F': memcpy(&narrow,&v.f,sizeof(narrow));return narrow; + case 'D': memcpy(&wide,&v.d,sizeof(wide));return wide; + default: return 0; // Reference values are never dereferenced/published. + } +} +void Record(jvmtiEnv* ti,jmethodID method,jlocation location,jclass declaring, + jfieldID field,uint32_t kind,jvalue value,char signature) { + if (in_callback) return; + in_callback=true; + const uint32_t n=next_entry.fetch_add(1,std::memory_order_relaxed); + if (nGetFieldName(declaring,field,&field_name,&type_sig,nullptr)==JVMTI_ERROR_NONE && + ti->GetMethodName(method,&method_name,nullptr,nullptr)==JVMTI_ERROR_NONE) { + Copy(e.field,sizeof(e.field),field_name); + Copy(e.method,sizeof(e.method),method_name); + e.kind=kind;e.location=static_cast(location); + e.bits=Bits(value,signature); + } + Dealloc(ti,field_name); + Dealloc(ti,type_sig); + Dealloc(ti,method_name); + } + in_callback=false; +} +void JNICALL OnWrite(jvmtiEnv* ti,JNIEnv*,jthread,jmethodID method,jlocation location, + jclass klass,jobject,jfieldID field,char signature,jvalue new_value) { + Record(ti,method,location,klass,field,2u,new_value,signature); +} +void JNICALL OnRead(jvmtiEnv* ti,JNIEnv* env,jthread,jmethodID method,jlocation location, + jclass klass,jobject object,jfieldID field) { + if (in_callback) return; + char* name=nullptr,*sig=nullptr; + if (ti->GetFieldName(klass,field,&name,&sig,nullptr)!=JVMTI_ERROR_NONE) return; + const char type=sig!=nullptr?sig[0]:'?'; + Dealloc(ti,name);Dealloc(ti,sig); + // JNI sampling is only a best-effort value demonstration. The JVMTI read + // callback has no exact value parameter and cannot prove race-free reads. + // Prevent JNI Get*Field from recursively triggering another field callback. + in_callback=true; + jvalue value={}; + switch(type) { + case 'I': + value.i=object?env->GetIntField(object,field):env->GetStaticIntField(klass,field); + break; + case 'J': + value.j=object?env->GetLongField(object,field):env->GetStaticLongField(klass,field); + break; + case 'Z': + value.z=object?env->GetBooleanField(object,field):env->GetStaticBooleanField(klass,field); + break; + default: in_callback=false;return; + } + if (env->ExceptionCheck()) {env->ExceptionClear();in_callback=false;return;} + in_callback=false; + Record(ti,method,location,klass,field,1u,value,type); +} +void Watch(jvmtiEnv* ti,JNIEnv* env,jclass klass) { + char* signature=nullptr; + if (ti->GetClassSignature(klass,&signature,nullptr)!=JVMTI_ERROR_NONE) return; + const bool match=(signature!=nullptr && + strncmp(signature,wanted,strlen(wanted))==0); + Dealloc(ti,signature); + if (!match) return; + jint count=0;jfieldID* fields=nullptr; + if (ti->GetClassFields(klass,&count,&fields)!=JVMTI_ERROR_NONE) return; + for(jint i=0;iSetFieldAccessWatch(klass,fields[i]); + jvmtiError b=ti->SetFieldModificationWatch(klass,fields[i]); + if (a==JVMTI_ERROR_NONE && b==JVMTI_ERROR_NONE) + watched.fetch_add(1,std::memory_order_relaxed); + } + if(fields!=nullptr)ti->Deallocate(reinterpret_cast(fields)); + AW_LOG("WATCH_REGISTERED fields=%u",watched.load()); + (void)env; +} +void JNICALL OnClassPrepare(jvmtiEnv* ti,JNIEnv* env,jthread,jclass klass) { + Watch(ti,env,klass); +} +} // namespace + +AW_EXPORT jint Agent_OnAttach(JavaVM* vm,char* options,void*) { + jvmtiEnv* ti=nullptr; + if (vm->GetEnv(reinterpret_cast(&ti),JVMTI_VERSION_1_2)!=JNI_OK || + ti==nullptr) { + AW_LOG("ATTACH_FAILED missing JVMTI"); + return JNI_ERR; + } + if(options && options[0] && strlen(options)AddCapabilities(&caps); + if (cap_err!=JVMTI_ERROR_NONE) { + AW_LOG("ATTACH_FAILED capabilities=%d",cap_err); + return JNI_ERR; + } + jvmtiEventCallbacks callbacks={}; + callbacks.FieldAccess=OnRead; + callbacks.FieldModification=OnWrite; + callbacks.ClassPrepare=OnClassPrepare; + if(ti->SetEventCallbacks(&callbacks,sizeof(callbacks))!=JVMTI_ERROR_NONE || + ti->SetEventNotificationMode(JVMTI_ENABLE,JVMTI_EVENT_FIELD_ACCESS,nullptr)!=JVMTI_ERROR_NONE || + ti->SetEventNotificationMode(JVMTI_ENABLE,JVMTI_EVENT_FIELD_MODIFICATION,nullptr)!=JVMTI_ERROR_NONE || + ti->SetEventNotificationMode(JVMTI_ENABLE,JVMTI_EVENT_CLASS_PREPARE,nullptr)!=JVMTI_ERROR_NONE) { + AW_LOG("ATTACH_FAILED callbacks"); + return JNI_ERR; + } + JNIEnv* env=nullptr; + if(vm->GetEnv(reinterpret_cast(&env),JNI_VERSION_1_6)==JNI_OK && + env!=nullptr) { + jint count=0;jclass* classes=nullptr; + if(ti->GetLoadedClasses(&count,&classes)==JVMTI_ERROR_NONE) { + for(jint i=0;iDeallocate(reinterpret_cast(classes)); + } + } + AW_LOG("ATTACHED target=%s watched=%u",wanted,watched.load()); + return JNI_OK; +} +AW_EXPORT int artwatch_jvmti_snapshot(char* out,uint32_t length) { + if(!out||length<100) return 0; + const uint32_t total=next_entry.load(std::memory_order_acquire); + const uint32_t count=total(n)>=length)return 0; + used+=static_cast(n); + for(uint32_t i=0;i(e.location),e.field,e.method, + static_cast(e.bits)); + if(n<0||static_cast(n)>=length-used)return 0; + used+=static_cast(n); + } + if(used+3>length)return 0; + out[used++]=']';out[used++]='}';out[used]=0; + return 1; +} diff --git a/art-fieldwatch-phase1/native/p3-clone-injector-art.cc b/art-fieldwatch-phase1/native/p3-clone-injector-art.cc new file mode 100644 index 0000000..2fda4f6 --- /dev/null +++ b/art-fieldwatch-phase1/native/p3-clone-injector-art.cc @@ -0,0 +1,377 @@ +// P3 experimental ART-source build unit (NOT an NDK / on-device ABI shim). +// +// Build inside a source-matched Android ART compiler tree, after validating +// the exact device libart-compiler.so/libart.so build IDs. The existing CI +// intentionally does NOT compile, dlopen, or invoke this unit. +// This is the first real IR mutation implementation, not yet a deployed hook. +// +// Caller responsibilities: +// - Locate an exact same-graph FieldEventSink.recordInt(0,0,observed) +// template, a matching int field GET, and the resolved ArtMethod*. +// - Invoke only on the compilation worker with HGraph and nodes alive. +// - Select API33 x86_64 verified library identities before calling. +// - Hold the ART compiler's normal graph-mutation context; no concurrent walk. +// - Do not invoke from Frida JS or a JNI runtime thread. +// +// Safety: this is a narrowly gated *read event* proof. Refuse all other +// fields, unresolved calls, clinit checks, mixed blocks, or invalid source +// instruction placement. Writes and generalized method resolution are next. +#include "nodes.h" + +namespace art { +namespace artwatch_p3 { + +enum class CloneResult : int { + kInserted = 1, + kMissing = -1, + kGraphMismatch = -2, + kTypeMismatch = -3, + kNotAdjacent = -4, + kTemplateMismatch = -5, + kEnvironmentMismatch = -6, + kUnsupportedDispatch = -7 +}; + +// The injected clone records a real successful read with the existing JNI +// recorder. The template itself passes (0,0,observed), so the recorder ignores +// its own execution; only an inserted clone with (9002,1,observed) produces +// events. Value is the actual HInstanceFieldGet SSA output. +CloneResult CloneIntReadFromResolvedTemplate( + HGraph* graph, + HInstanceFieldGet* field_get, + HInvokeStaticOrDirect* template_invoke, + ArtMethod* expected_sink_method, + int32_t read_site) { + if (graph == nullptr || field_get == nullptr || + template_invoke == nullptr || expected_sink_method == nullptr) { + return CloneResult::kMissing; + } + HBasicBlock* block = field_get->GetBlock(); + if (block == nullptr || template_invoke->GetBlock() != block || + block->GetGraph() != graph || !graph->IsInSsaForm()) { + return CloneResult::kGraphMismatch; + } + if (field_get->GetType() != DataType::Type::kInt32 || + field_get->GetFieldType() != DataType::Type::kInt32 || + field_get->IsVolatile()) { + return CloneResult::kTypeMismatch; + } + // This deliberately accepts only adjacent field-get -> invoke templates. + // The already-correct call environment describes precisely this point. + // Never move a throwing call over unrelated operations. + if (field_get->GetNext() != template_invoke) { + return CloneResult::kNotAdjacent; + } + if (!template_invoke->IsStatic() || + template_invoke->GetResolvedMethod() != expected_sink_method || + template_invoke->GetNumberOfArguments() != 3u || + template_invoke->InputCount() != 3u || + template_invoke->InputAt(2) != field_get || + template_invoke->GetType() != DataType::Type::kVoid || + !template_invoke->IsClonable()) { + return CloneResult::kTemplateMismatch; + } + HInstruction* site = template_invoke->InputAt(0); + HInstruction* kind = template_invoke->InputAt(1); + if (site == nullptr || kind == nullptr || + !site->IsIntConstant() || !kind->IsIntConstant() || + site->AsIntConstant()->GetValue() != 0 || + kind->AsIntConstant()->GetValue() != 0 || + read_site <= 0) { + return CloneResult::kTemplateMismatch; + } + if (!template_invoke->HasEnvironment() || + template_invoke->GetEnvironment() == nullptr) { + return CloneResult::kEnvironmentMismatch; + } + // Reject dispatch modes requiring additional current-method/clinit input, + // even though the cloned source method reference would otherwise be valid. + if (template_invoke->GetClinitCheckRequirement() != + HInvokeStaticOrDirect::ClinitCheckRequirement::kNone || + template_invoke->HasCurrentMethodInput()) { + return CloneResult::kUnsupportedDispatch; + } + // All checks above run before the first mutation. Clone inherits the + // real DEX method reference and dispatch, but not its block, ID, + // environment or use-list links (those are rebuilt by ART). + HInstruction* raw = template_invoke->Clone(graph->GetAllocator()); + HInvokeStaticOrDirect* invoke = raw->AsInvokeStaticOrDirect(); + invoke->SetArgumentAt(0, graph->GetIntConstant(read_site, field_get->GetDexPc())); + invoke->SetArgumentAt(1, graph->GetIntConstant(1, field_get->GetDexPc())); + // Argument 2 already refers to field_get from the source template. + block->InsertInstructionBefore(invoke, template_invoke); + // Copy uses and inlined parent environment through ART, not a memcpy. + invoke->CopyEnvironmentFrom(template_invoke->GetEnvironment()); + return CloneResult::kInserted; +} + +// Select the template by *exact* DEX identities within the compiler's +// current graph, never by a global ArtMethod pointer or a stale node address. +// The caller obtains these IDs from the currently compiled APK and resolves +// expected_sink_method using ART's normal class/method resolution. +CloneResult CloneUniqueIntReadInGraph( + HGraph* graph, + const DexFile* expected_dex, + uint32_t expected_compiled_method_idx, + uint32_t expected_field_idx, + uint32_t expected_get_dex_pc, + uint32_t expected_sink_method_idx, + ArtMethod* expected_sink_method, + int32_t read_site) { + if (graph == nullptr || expected_dex == nullptr || + expected_sink_method == nullptr) { + return CloneResult::kMissing; + } + // A DEX method index is not globally unique across class loaders. + if (&graph->GetDexFile() != expected_dex || + graph->GetMethodIdx() != expected_compiled_method_idx || + !graph->IsInSsaForm()) { + return CloneResult::kGraphMismatch; + } + HInstanceFieldGet* selected_get = nullptr; + HInvokeStaticOrDirect* selected_invoke = nullptr; + for (HBasicBlock* block : graph->GetActiveBlocks()) { + for (HInstruction* inst = block->GetFirstInstruction(); + inst != nullptr; inst = inst->GetNext()) { + if (!inst->IsInvokeStaticOrDirect()) continue; + HInvokeStaticOrDirect* invoke = inst->AsInvokeStaticOrDirect(); + const MethodReference reference = invoke->GetMethodReference(); + if (reference.dex_file != expected_dex || + reference.index != expected_sink_method_idx || + invoke->GetResolvedMethod() != expected_sink_method) continue; + HInstruction* previous = inst->GetPrevious(); + if (previous == nullptr || !previous->IsInstanceFieldGet()) continue; + HInstanceFieldGet* get = previous->AsInstanceFieldGet(); + if (get->GetFieldInfo().GetFieldIndex() != expected_field_idx || + get->GetDexPc() != expected_get_dex_pc || + &get->GetFieldInfo().GetDexFile() != expected_dex) continue; + if (selected_invoke != nullptr) return CloneResult::kTemplateMismatch; + selected_get = get; + selected_invoke = invoke; + } + } + if (selected_invoke == nullptr) return CloneResult::kMissing; + return CloneIntReadFromResolvedTemplate( + graph, selected_get, selected_invoke, expected_sink_method, read_site); +} + + +/* + * Source-matched four-way integer access injector (instance/static, get/set). + * + * Unlike the earlier two-PC fixture specialization, this accepts field + * identities from the live IR itself, not from a hard-coded field index. + * For safety this deployment stage still REQUIRES a resolved inert + * recordInt(0, 0, value) template immediately after each field instruction, + * in its own basic block. Uninstrumented DEX has no such template and is + * intentionally skipped. We do not fabricate HEnvironment objects or + * relocate a resolved call across throwing/volatile/class-init operations. + * + * The clone itself calls recordInt(field_index + 1, operation, exact_ssa_value). + * field_index + 1 avoids the zero sentinel namespace. The host joins + * (DexFile identity, field_index, compiled method index, field dex_pc) + * with the APK-wide catalog. This three-argument sink cannot directly + * carry the full metadata tuple; use the generic seven-argument ABI for + * production field events after a verified invoke constructor is available. + * + * This is ART-source code, not a build-tested NDK binary or an enabled Frida + * hook. It must be compiled against the source corresponding to the actual + * ART runtime build IDs. + */ +struct IntFieldInsertionStats { + uint32_t candidates = 0; + uint32_t inserted = 0; + uint32_t no_template = 0; + uint32_t unsupported = 0; + uint32_t identity_rejected = 0; +}; + +CloneResult CloneIntAccessFromResolvedTemplate( + HGraph* graph, + HInstruction* access, + HInvokeStaticOrDirect* template_invoke, + ArtMethod* expected_sink_method, + const DexFile* expected_dex, + uint32_t expected_field_index, + uint32_t expected_access_pc) { + if (graph == nullptr || access == nullptr || + template_invoke == nullptr || expected_sink_method == nullptr || + expected_dex == nullptr) { + return CloneResult::kMissing; + } + + HBasicBlock* block = access->GetBlock(); + if (block == nullptr || block->GetGraph() != graph || + template_invoke->GetBlock() != block || !graph->IsInSsaForm()) { + return CloneResult::kGraphMismatch; + } + + // All four HFieldAccess classes expose verified FieldInfo. The field + // access's own source PC is used, never the following invoke's PC. + uint32_t field_index = 0; + const DexFile* field_dex = nullptr; + HInstruction* value = nullptr; + uint32_t operation = 0; // READ=1, WRITE=2 + bool is_volatile = false; + DataType::Type field_type = DataType::Type::kVoid; + if (access->IsInstanceFieldGet()) { + auto* field = access->AsInstanceFieldGet(); + field_index = field->GetFieldInfo().GetFieldIndex(); + field_dex = &field->GetFieldInfo().GetDexFile(); + field_type = field->GetFieldType(); + is_volatile = field->IsVolatile(); + value = field; + operation = 1; + } else if (access->IsInstanceFieldSet()) { + auto* field = access->AsInstanceFieldSet(); + field_index = field->GetFieldInfo().GetFieldIndex(); + field_dex = &field->GetFieldInfo().GetDexFile(); + field_type = field->GetFieldType(); + is_volatile = field->IsVolatile(); + value = field->GetValue(); + operation = 2; + } else if (access->IsStaticFieldGet()) { + auto* field = access->AsStaticFieldGet(); + field_index = field->GetFieldInfo().GetFieldIndex(); + field_dex = &field->GetFieldInfo().GetDexFile(); + field_type = field->GetFieldType(); + is_volatile = field->IsVolatile(); + value = field; + operation = 1; + } else if (access->IsStaticFieldSet()) { + auto* field = access->AsStaticFieldSet(); + field_index = field->GetFieldInfo().GetFieldIndex(); + field_dex = &field->GetFieldInfo().GetDexFile(); + field_type = field->GetFieldType(); + is_volatile = field->IsVolatile(); + value = field->GetValue(); + operation = 2; + } else { + return CloneResult::kTypeMismatch; + } + + // Preserve exact field identity and avoid accidental capture of inlined + // accesses from another DexFile or an unrelated field with the same index. + if (field_dex != expected_dex || + field_index != expected_field_index || + access->GetDexPc() != expected_access_pc) { + return CloneResult::kGraphMismatch; + } + if (field_type != DataType::Type::kInt32 || is_volatile || + value == nullptr || value->GetType() != DataType::Type::kInt32 || + field_index >= static_cast(INT32_MAX)) { + return CloneResult::kTypeMismatch; + } + if (access->GetNext() != template_invoke) { + return CloneResult::kNotAdjacent; + } + + const MethodReference method = template_invoke->GetMethodReference(); + if (!template_invoke->IsStatic() || + method.dex_file != expected_dex || + template_invoke->GetResolvedMethod() != expected_sink_method || + template_invoke->GetNumberOfArguments() != 3u || + template_invoke->InputCount() != 3u || + template_invoke->GetType() != DataType::Type::kVoid || + !template_invoke->IsClonable() || + !template_invoke->HasEnvironment() || + template_invoke->GetEnvironment() == nullptr || + template_invoke->GetEnvironment()->GetParent() != nullptr) { + return CloneResult::kTemplateMismatch; + } + HInstruction* site = template_invoke->InputAt(0); + HInstruction* kind = template_invoke->InputAt(1); + if (site == nullptr || kind == nullptr || + !site->IsIntConstant() || !kind->IsIntConstant() || + site->AsIntConstant()->GetValue() != 0 || + kind->AsIntConstant()->GetValue() != 0 || + template_invoke->GetClinitCheckRequirement() != + HInvokeStaticOrDirect::ClinitCheckRequirement::kNone || + template_invoke->HasCurrentMethodInput()) { + return CloneResult::kUnsupportedDispatch; + } + + // All guards precede mutation. Use ART's own clone, SSA updates, block + // insertion and environment-copy logic, never raw C++ layout copying. + HInstruction* cloned = template_invoke->Clone(graph->GetAllocator()); + if (cloned == nullptr || !cloned->IsInvokeStaticOrDirect()) { + return CloneResult::kTemplateMismatch; + } + HInvokeStaticOrDirect* invoke = cloned->AsInvokeStaticOrDirect(); + invoke->SetArgumentAt( + 0, graph->GetIntConstant(static_cast(field_index + 1u), + access->GetDexPc())); + invoke->SetArgumentAt( + 1, graph->GetIntConstant(static_cast(operation), + access->GetDexPc())); + invoke->SetArgumentAt(2, value); + block->InsertInstructionBefore(invoke, template_invoke); + invoke->CopyEnvironmentFrom(template_invoke->GetEnvironment()); + return CloneResult::kInserted; +} + +// Caller passes the resolved native sink and exact compiled DexFile. +// No site allowlist: every qualifying int field get/set in this compiled +// method is considered, regardless of declaring class/field name. +// Only a verified same-block adjacent template can make it executable. +IntFieldInsertionStats CloneAllAdjacentIntFieldTemplates( + HGraph* graph, + const DexFile* expected_dex, + uint32_t expected_compiled_method_index, + uint32_t expected_sink_method_index, + ArtMethod* expected_sink_method) { + IntFieldInsertionStats stats; + if (graph == nullptr || expected_dex == nullptr || + expected_sink_method == nullptr || !graph->IsInSsaForm() || + &graph->GetDexFile() != expected_dex || + graph->GetMethodIdx() != expected_compiled_method_index) { + ++stats.identity_rejected; + return stats; + } + + for (HBasicBlock* block : graph->GetActiveBlocks()) { + for (HInstruction* inst = block->GetFirstInstruction(); + inst != nullptr; inst = inst->GetNext()) { + if (!inst->IsInstanceFieldGet() && !inst->IsInstanceFieldSet() && + !inst->IsStaticFieldGet() && !inst->IsStaticFieldSet()) { + continue; + } + ++stats.candidates; + HInstruction* next = inst->GetNext(); + if (next == nullptr || !next->IsInvokeStaticOrDirect()) { + ++stats.no_template; + continue; + } + HInvokeStaticOrDirect* invoke = next->AsInvokeStaticOrDirect(); + const MethodReference method = invoke->GetMethodReference(); + if (method.dex_file != expected_dex || + method.index != expected_sink_method_index || + invoke->GetResolvedMethod() != expected_sink_method) { + ++stats.no_template; + continue; + } + const FieldInfo* info = nullptr; + if (inst->IsInstanceFieldGet()) { + info = &inst->AsInstanceFieldGet()->GetFieldInfo(); + } else if (inst->IsInstanceFieldSet()) { + info = &inst->AsInstanceFieldSet()->GetFieldInfo(); + } else if (inst->IsStaticFieldGet()) { + info = &inst->AsStaticFieldGet()->GetFieldInfo(); + } else { + info = &inst->AsStaticFieldSet()->GetFieldInfo(); + } + const CloneResult result = CloneIntAccessFromResolvedTemplate( + graph, inst, invoke, expected_sink_method, expected_dex, + info->GetFieldIndex(), inst->GetDexPc()); + if (result == CloneResult::kInserted) { + ++stats.inserted; + } else { + ++stats.unsupported; + } + } + } + return stats; +} + +} // namespace artwatch_p3 +} // namespace art diff --git a/art-fieldwatch-phase1/native/p3-direct-injector-art.cc b/art-fieldwatch-phase1/native/p3-direct-injector-art.cc new file mode 100644 index 0000000..71794eb --- /dev/null +++ b/art-fieldwatch-phase1/native/p3-direct-injector-art.cc @@ -0,0 +1,202 @@ +// ART-source build unit: direct typed field-event insertion, no Java-authored +// invoke template required in the method being instrumented. +// +// IMPORTANT: compile as part of a source-matched ART optimizing compiler, NOT +// as an NDK library. This code has not been linked into stock emulator ART. +// The injector must run on the compiler worker after SSA construction and +// before optimizations capable of removing/merging field operations. +// +// The host must resolve a preloaded, class-initialized, native static method +// with signature recordFieldInt(IIIIII)V, and supply BOTH the exact ArtMethod* +// and the method's DexFile/MethodId pair. Cross-DEX target-method references +// must be validated with the selected compiler backend before deployment. +// +// Unlike the earlier CloneUniqueIntReadInGraph, the field-accessing Java +// method needs NO FieldEventSink reference and NO adjacent sink call. +// Field identity and runtime value come directly from the HGraph itself. +// +// Follow-on: build matched native module, export entrypoint, and exercise +// live JIT/compilation on API33 x86_64 before enabling other versions. +// TODO: wide, reference, volatile, unresolved field accesses, inlined callee +// attribution, interpreter and AOT code; do not silently claim coverage. +#include +#include "art_method.h" +#include "nodes.h" + +namespace art { +namespace artwatch_direct { + +enum class RejectReason : uint32_t { + kNone, kInvalidGraph, kBadSink, kNoEnvironment, kUnresolvedField, + kOtherDex, kUnsupportedType, kVolatile, kNoValue, kUnsupportedBlock, +}; + +struct Result { + uint32_t examined = 0; + uint32_t inserted = 0; + uint32_t missing_environment = 0; + uint32_t mismatched_dex = 0; + uint32_t unsupported_type = 0; + uint32_t volatile_fields = 0; + uint32_t no_value = 0; +}; + +struct Sink { + const DexFile* dex_file; + uint32_t method_index; + ArtMethod* method; // Pre-resolved and class-initialized JNI method. + uint32_t dex_id; // Stable APK DEX ID from the per-APK catalog. +}; + +struct FieldAccess { + HInstruction* value; + const FieldInfo* info; + uint32_t operation; // READ=1, WRITE=2 +}; + +static FieldAccess Describe(HInstruction* inst) { + if (inst->IsInstanceFieldGet()) { + auto* get = inst->AsInstanceFieldGet(); + return {get, &get->GetFieldInfo(), 1u}; + } + if (inst->IsInstanceFieldSet()) { + auto* set = inst->AsInstanceFieldSet(); + return {set->GetValue(), &set->GetFieldInfo(), 2u}; + } + if (inst->IsStaticFieldGet()) { + auto* get = inst->AsStaticFieldGet(); + return {get, &get->GetFieldInfo(), 1u}; + } + if (inst->IsStaticFieldSet()) { + auto* set = inst->AsStaticFieldSet(); + return {set->GetValue(), &set->GetFieldInfo(), 2u}; + } + return {nullptr, nullptr, 0u}; +} + +static RejectReason InsertIntEventAfter(HGraph* graph, + HInstruction* access, + const FieldAccess& field, + const Sink& sink) { + if (field.info == nullptr || field.value == nullptr) { + return RejectReason::kNoValue; + } + if (&field.info->GetDexFile() != &graph->GetDexFile()) { + // A field in an inlined callee needs that callee's MethodReference, + // not the compiled caller's method index. + return RejectReason::kOtherDex; + } + if (field.info->GetFieldType() != DataType::Type::kInt32 || + field.value->GetType() != DataType::Type::kInt32) { + return RejectReason::kUnsupportedType; + } + if (field.info->IsVolatile()) { + // Volatile/atomic ordering needs an explicit contract of its own. + return RejectReason::kVolatile; + } + if (!access->HasEnvironment()) { + // Never copy an unrelated HEnvironment from a later instruction: + // its deoptimization state may describe a DIFFERENT DEX PC. + return RejectReason::kNoEnvironment; + } + if (graph->GetArtMethod() == nullptr || + access->GetEnvironment()->GetMethod() != graph->GetArtMethod() || + access->GetEnvironment()->GetParent() != nullptr) { + // Same DexFile alone does not distinguish an inlined callee from + // its compiled caller. An inlined method needs its own method ID. + return RejectReason::kOtherDex; + } + HBasicBlock* block = access->GetBlock(); + if (block == nullptr || block->GetGraph() != graph || + access->IsControlFlow() || block->GetLastInstruction() == access) { + // No mutation across block boundaries or control-flow terminators. + return RejectReason::kUnsupportedBlock; + } + + const uint32_t dex_pc = access->GetDexPc(); + const uint32_t field_id = field.info->GetFieldIndex(); + const uint32_t method_id = graph->GetMethodIdx(); + ArenaAllocator* allocator = graph->GetAllocator(); + const MethodReference sink_ref(sink.dex_file, sink.method_index); + + // ART's JIT direct-address dispatch is the source-supported choice + // for a resolved ArtMethod*. No HCurrentMethod or clinit input is needed. + // The sink class must ALREADY be initialized; otherwise reject at caller. + HInvokeStaticOrDirect::DispatchInfo dispatch = { + MethodLoadKind::kJitDirectAddress, + CodePtrLocation::kCallArtMethod, + static_cast(reinterpret_cast(sink.method)) + }; + HInvokeStaticOrDirect* call = new (allocator) HInvokeStaticOrDirect( + allocator, + 6u, + DataType::Type::kVoid, + dex_pc, + sink_ref, + sink.method, + dispatch, + kStatic, + sink_ref, + HInvokeStaticOrDirect::ClinitCheckRequirement::kNone); + + // The six arguments make provenance explicit in the executed native call. + // Values are SSA inputs, not post-hoc field reads or call-count inference. + call->SetArgumentAt(0u, graph->GetIntConstant(static_cast(sink.dex_id),dex_pc)); + call->SetArgumentAt(1u, graph->GetIntConstant(static_cast(method_id),dex_pc)); + call->SetArgumentAt(2u, graph->GetIntConstant(static_cast(field_id),dex_pc)); + call->SetArgumentAt(3u, graph->GetIntConstant(static_cast(dex_pc),dex_pc)); + call->SetArgumentAt(4u, graph->GetIntConstant(static_cast(field.operation),dex_pc)); + call->SetArgumentAt(5u, field.value); + // Insertion AFTER the field access matters: null checks and class + // initialization errors must happen before a successful-access event. + block->InsertInstructionAfter(call, access); + call->CopyEnvironmentFrom(access->GetEnvironment()); + return RejectReason::kNone; +} + +// Called at an ART compiler boundary with an already-built SSA graph, +// under normal compilation thread confinement. No Frida callback may +// mutate the graph concurrently with this pass. +Result InsertAllIntFieldEvents(HGraph* graph, const Sink& sink) { + Result result; + if (graph == nullptr || !graph->IsInSsaForm() || + sink.dex_file == nullptr || sink.method == nullptr || + !sink.method->IsStatic() || !sink.method->IsNative()) { + return result; + } + if (sink.dex_file != &graph->GetDexFile()) { + // ART MethodReference indices are scoped to their DexFile. Refuse + // cross-DEX dispatch until verified against the target compiler. + ++result.mismatched_dex; + return result; + } + // Avoid recursively instrumenting the sink itself. + if (sink.dex_file == &graph->GetDexFile() && + sink.method_index == graph->GetMethodIdx()) { + return result; + } + for (HBasicBlock* block : graph->GetActiveBlocks()) { + for (HInstruction* access = block->GetFirstInstruction(); + access != nullptr;) { + HInstruction* next = access->GetNext(); + FieldAccess field = Describe(access); + if (field.info != nullptr) { + ++result.examined; + switch (InsertIntEventAfter(graph, access, field, sink)) { + case RejectReason::kNone: ++result.inserted; break; + case RejectReason::kNoEnvironment: ++result.missing_environment; break; + case RejectReason::kOtherDex: ++result.mismatched_dex; break; + case RejectReason::kUnsupportedType: ++result.unsupported_type; break; + case RejectReason::kVolatile: ++result.volatile_fields; break; + default: ++result.no_value; break; + } + } + // Do not re-enter a freshly inserted invocation. + access = next; + } + } + return result; +} + +} // namespace artwatch_direct +} // namespace art diff --git a/art-fieldwatch-phase1/native/passive-shadow.c b/art-fieldwatch-phase1/native/passive-shadow.c new file mode 100644 index 0000000..63ce827 --- /dev/null +++ b/art-fieldwatch-phase1/native/passive-shadow.c @@ -0,0 +1,492 @@ +// P1 native shadow: read-only, strict Android API 33 x86_64 ART build IDs. +// No ART objects are modified and no private C++ layout is assumed. +#define _GNU_SOURCE 1 +#include +#include +#include +#include +#include +#include +#include +#include +#include +#define EXPORT __attribute__((visibility("default"))) +#define COMPILER_ID "0b33b00205f7151b4fce7490c3715d99" +#define RUNTIME_ID "c8b6a2df9893030c07b3b96dc24a7d30" + +static int ready = 0; +static uint64_t graphs = 0, gets = 0, sets = 0, rejected = 0, blocks = 0; +static uint64_t opaque_graph_word = 0; +static int named(const char *path, const char *base) { + if (path == NULL) return 0; + size_t a = strlen(path), b = strlen(base); + return a >= b && strcmp(path + a - b, base) == 0 && + (a == b || path[a - b - 1] == '/'); +} +static size_t pad4(size_t n) { return (n + 3u) & ~(size_t)3u; } +static int note_build_id(const struct dl_phdr_info *info, char out[41]) { + for (ElfW(Half) i = 0; i < info->dlpi_phnum; ++i) { + const ElfW(Phdr) *ph = &info->dlpi_phdr[i]; + if (ph->p_type != PT_NOTE || ph->p_filesz > 65536) continue; + const uint8_t *notes = (const uint8_t *)(info->dlpi_addr + ph->p_vaddr); + size_t at = 0, length = (size_t)ph->p_filesz; + while (at + sizeof(ElfW(Nhdr)) <= length) { + ElfW(Nhdr) nh; + memcpy(&nh, notes + at, sizeof(nh)); + at += sizeof(nh); + if (nh.n_namesz > length - at) break; + const uint8_t *name = notes + at; + size_t name_bytes = pad4((size_t)nh.n_namesz); + if (name_bytes > length - at) break; + at += name_bytes; + size_t desc_bytes = pad4((size_t)nh.n_descsz); + if (desc_bytes > length - at) break; + const uint8_t *desc = notes + at; + at += desc_bytes; + // Android ART may use 16-byte GNU Build IDs (32 hex digits), + // rather than the common 20-byte IDs (40 hex digits). The output + // buffer holds at most 40 digits plus a NUL terminator. + if (nh.n_type != NT_GNU_BUILD_ID || + nh.n_namesz < 4 || memcmp(name, "GNU", 4) != 0 || + (nh.n_descsz != 16 && nh.n_descsz != 20)) continue; + static const char digits[] = "0123456789abcdef"; + for (size_t k = 0; k < nh.n_descsz; ++k) { + out[2*k] = digits[desc[k] >> 4]; + out[2*k+1] = digits[desc[k] & 15]; + } + out[2u * nh.n_descsz] = '\0'; + return 1; + } + } + return 0; +} +struct modules { char art[41], compiler[41]; int has_art, has_compiler; }; +static int scan(struct dl_phdr_info *info, size_t length, void *arg) { + (void)length; + struct modules *m = (struct modules *)arg; + if (named(info->dlpi_name, "libart.so")) + m->has_art = note_build_id(info, m->art); + if (named(info->dlpi_name, "libart-compiler.so")) + m->has_compiler = note_build_id(info, m->compiler); + return 0; +} +static int aligned(const void *p) { + return p != NULL && (((uintptr_t)p) & (sizeof(void *) - 1u)) == 0; +} +EXPORT int artwatch_shadow_init(void) { + if (ready != 0) return ready == 1; + char sdk[PROP_VALUE_MAX] = {0}; + if (sizeof(void*) != 8 || __system_property_get("ro.build.version.sdk", sdk) <= 0 || + strcmp(sdk, "33") != 0) { ready = -1; return 0; } + struct modules m = {0}; + dl_iterate_phdr(scan, &m); + if (!m.has_art || !m.has_compiler || + strcmp(m.art, RUNTIME_ID) != 0 || + strcmp(m.compiler, COMPILER_ID) != 0) { ready = -1; return 0; } + ready = 1; + return 1; +} +// Entry only while the exact matched HGraph* is alive. The first eight bytes +// are opaque; never assume an HGraph layout or retain an object pointer. +// Per-native-thread, fixed-capacity, observation-only visitor inventory. +// Compiler workers are not asked to allocate or call back into Java. +// This records only field nodes whose Accept() method is invoked while +// RunOptimizations() is executing. It is NOT an HGraph block traversal. +#define SHADOW_MAX_UNIQUE 512u +struct scope { + const void *graph; + uint32_t get_visits, set_visits, unique_gets, unique_sets, overflow; + const void *nodes[SHADOW_MAX_UNIQUE]; + uint8_t kinds[SHADOW_MAX_UNIQUE]; +}; +static __thread struct scope scoped; +EXPORT int artwatch_shadow_scope_begin(const void *graph) { + if (ready != 1 || !aligned(graph) || scoped.graph != NULL) return 0; + memset(&scoped, 0, sizeof(scoped)); + scoped.graph = graph; + return 1; +} +EXPORT int artwatch_shadow_scope_end(char *out, uint32_t length) { + if (ready != 1 || out == NULL || length < 128 || scoped.graph == NULL) + return 0; + int n = snprintf(out, length, + "{\"graph\":\"%p\",\"getVisits\":%u,\"setVisits\":%u," + "\"uniqueGets\":%u,\"uniqueSets\":%u,\"overflow\":%u}", + scoped.graph, scoped.get_visits, scoped.set_visits, + scoped.unique_gets, scoped.unique_sets, scoped.overflow); + // Clear the observation window even if formatting somehow fails. + scoped.graph = NULL; + return n > 0 && (uint32_t)n < length ? 1 : 0; +} +EXPORT int artwatch_shadow_graph(const void *graph, const void *builder_graph) { + if (ready != 1 || !aligned(graph) || graph != builder_graph) { + __atomic_fetch_add(&rejected, 1u, __ATOMIC_RELAXED); + return 0; + } + uint64_t word = 0; + memcpy(&word, graph, sizeof(word)); + __atomic_store_n(&opaque_graph_word, word, __ATOMIC_RELAXED); + __atomic_fetch_add(&graphs, 1u, __ATOMIC_RELAXED); + return 1; +} +// Read-only validation of pointers exposed by HGraph::AddBlock. + // We never dereference an HBasicBlock, and we store no block pointers. +EXPORT int artwatch_shadow_block(const void *graph, + const void *builder_graph, + const void *block) { + if (ready != 1 || !aligned(graph) || graph != builder_graph || + !aligned(block)) { + __atomic_fetch_add(&rejected, 1u, __ATOMIC_RELAXED); + return 0; + } + __atomic_fetch_add(&blocks, 1u, __ATOMIC_RELAXED); + return 1; +} +// Called in Get/Set::Accept. Itanium C++ vptr = exported vtable + 2 words. +// Resolve vtable owner/name, then compare only the first pointer. +EXPORT int artwatch_shadow_node(const void *node, const void *vt_symbol, int kind) { + if (ready != 1 || !aligned(node) || !aligned(vt_symbol) || + (kind != 1 && kind != 2)) { + __atomic_fetch_add(&rejected, 1u, __ATOMIC_RELAXED); return 0; + } + const char *expected = (kind == 1) ? "_ZTVN3art17HInstanceFieldGetE" : + "_ZTVN3art17HInstanceFieldSetE"; + Dl_info info = {0}; + if (!dladdr(vt_symbol, &info) || + !named(info.dli_fname, "libart-compiler.so") || + info.dli_sname == NULL || strcmp(info.dli_sname, expected) != 0 || + info.dli_saddr != vt_symbol) { + __atomic_fetch_add(&rejected, 1u, __ATOMIC_RELAXED); return 0; + } + void *vptr = NULL; + memcpy(&vptr, node, sizeof(vptr)); + if (vptr != (const uint8_t *)vt_symbol + 2*sizeof(void*)) { + __atomic_fetch_add(&rejected, 1u, __ATOMIC_RELAXED); return 0; + } + if (kind == 1) __atomic_fetch_add(&gets, 1u, __ATOMIC_RELAXED); + else __atomic_fetch_add(&sets, 1u, __ATOMIC_RELAXED); + if (scoped.graph != NULL) { + if (kind == 1) scoped.get_visits++; + else scoped.set_visits++; + uint32_t used = scoped.unique_gets + scoped.unique_sets; + int seen = 0; + for (uint32_t i = 0; i < used; i++) { + if (scoped.nodes[i] == node && scoped.kinds[i] == (uint8_t)kind) { + seen = 1; + break; + } + } + if (!seen) { + if (used < SHADOW_MAX_UNIQUE) { + scoped.nodes[used] = node; + scoped.kinds[used] = (uint8_t)kind; + if (kind == 1) scoped.unique_gets++; + else scoped.unique_sets++; + } else { + scoped.overflow++; + } + } + } + return 1; +} +// Source-layout experiment: the Itanium x86_64 HInstruction object has +// vptr, previous_, next_, block_ as its first four machine words in the +// Android 13 compiler. Match only *already live* vtable-confirmed nodes +// passed by Frida Accept observers, after the exact mapped-ELF gate. +// On any mismatch, fail closed. This function NEVER mutates ART memory. +// Return 1 for adjacent get->invoke with reciprocal links and block; +// 0 for nonadjacency; -1 for invalid gate / object identity. +EXPORT int artwatch_shadow_linked_get_invoke( + const void *getter, const void *invoke, + const void *get_vtable, const void *invoke_vtable) { + if (ready != 1 || !aligned(getter) || !aligned(invoke) || + !aligned(get_vtable) || !aligned(invoke_vtable)) return -1; + // Confirm that the public vtable symbols belong to the mapped compiler. + const char *symbol_names[2] = { + "_ZTVN3art17HInstanceFieldGetE", + "_ZTVN3art21HInvokeStaticOrDirectE" + }; + const void *vt[2] = {get_vtable, invoke_vtable}; + const void *objects[2] = {getter, invoke}; + for (size_t i = 0; i < 2; ++i) { + Dl_info info = {0}; + if (!dladdr(vt[i], &info) || + !named(info.dli_fname, "libart-compiler.so") || + info.dli_sname == NULL || + strcmp(info.dli_sname, symbol_names[i]) != 0 || + info.dli_saddr != vt[i]) return -1; + void *actual = NULL; + memcpy(&actual, objects[i], sizeof(actual)); + if (actual != (const uint8_t *)vt[i] + 2 * sizeof(void*)) return -1; + } + // First four pointers are vptr, previous_, next_, HBasicBlock*. + // Read only known, live, already-vtable-confirmed instruction objects. + const uint8_t *g = (const uint8_t *)getter; + const uint8_t *i = (const uint8_t *)invoke; + const void *g_next = NULL, *i_prev = NULL; + const void *g_block = NULL, *i_block = NULL; + memcpy(&g_next, g + 2 * sizeof(void*), sizeof(g_next)); + memcpy(&i_prev, i + 1 * sizeof(void*), sizeof(i_prev)); + memcpy(&g_block, g + 3 * sizeof(void*), sizeof(g_block)); + memcpy(&i_block, i + 3 * sizeof(void*), sizeof(i_block)); + return g_next == invoke && i_prev == getter && + g_block != NULL && i_block == g_block ? 1 : 0; +} +// Exact-ELF-gated Android 13 x86_64 HInstruction layout: +// vptr, previous_, next_, block_, dex_pc_. Read DEX PC only from a live +// vtable-verified node while the compiler visitor is executing. +// A return value of 0 means no output was written. Never retain the node. +EXPORT int artwatch_shadow_instruction_dex_pc( + const void *node, const void *vt_symbol, uint32_t *out_dex_pc) { + if (ready != 1 || !aligned(node) || !aligned(vt_symbol) || + out_dex_pc == NULL) return 0; + Dl_info info = {0}; + if (!dladdr(vt_symbol, &info) || + !named(info.dli_fname, "libart-compiler.so") || + info.dli_sname == NULL || info.dli_saddr != vt_symbol) return 0; + if (strcmp(info.dli_sname, "_ZTVN3art17HInstanceFieldGetE") != 0 && + strcmp(info.dli_sname, "_ZTVN3art21HInvokeStaticOrDirectE") != 0) + return 0; + const void *actual_vptr = NULL; + memcpy(&actual_vptr, node, sizeof(actual_vptr)); + if (actual_vptr != (const uint8_t *)vt_symbol + 2*sizeof(void*)) + return 0; + uint32_t dex_pc = UINT32_MAX; + memcpy(&dex_pc, (const uint8_t *)node + 4*sizeof(void*), sizeof(dex_pc)); + if (dex_pc == UINT32_MAX) return 0; + *out_dex_pc = dex_pc; + return 1; +} + +/* + * P3 opt-in experimental mutation, API33 x86_64 and exact ART build IDs. + * This first canary clones an existing *resolved* JNI invoke with identical + * (0,0,value) arguments, and asks the original HInstructionBuilder to append + * the clone. The fixture JNI sink verifies two calls per access. There is NO + * general arbitrary-field support in this proof. + * + * Android 13 AOSP HInstruction has 21 virtual entries (two destructor + * slots); Clone(ArenaAllocator*) is entry 14. HBasicBlock::graph_ and + * HGraph::allocator_ are each at offset zero in this particular source + * revision. If any of the binary/ABI identity checks fail, do NOT mutate. + * The caller must invoke this in HInstructionBuilder::AppendInstruction's + * onLeave, before the builder leaves its current block, and never recurse. + */ +EXPORT int artwatch_shadow_clone_template_invoke( + void *builder, const void *source, + const void *get_vtable, const void *invoke_vtable, + uint32_t expected_get_pc, uint32_t expected_invoke_pc, + const void *append_address) { + if (ready != 1 || !aligned(builder) || !aligned(source) || + !aligned(get_vtable) || !aligned(invoke_vtable)) return -1; + Dl_info iv = {0}, gv = {0}; + if (!dladdr(invoke_vtable, &iv) || !dladdr(get_vtable, &gv) || + !named(iv.dli_fname,"libart-compiler.so") || + !named(gv.dli_fname,"libart-compiler.so") || + iv.dli_sname == NULL || gv.dli_sname == NULL || + strcmp(iv.dli_sname,"_ZTVN3art21HInvokeStaticOrDirectE") || + strcmp(gv.dli_sname,"_ZTVN3art17HInstanceFieldGetE") || + iv.dli_saddr != invoke_vtable || gv.dli_saddr != get_vtable) + return -2; + const uint8_t *src=(const uint8_t *)source; + const void *vptr=NULL,*previous=NULL,*block=NULL,*get_vptr=NULL; + uint32_t invoke_pc=UINT32_MAX,get_pc=UINT32_MAX; + memcpy(&vptr,src,sizeof(vptr)); + memcpy(&previous,src+sizeof(void*),sizeof(previous)); + memcpy(&block,src+3*sizeof(void*),sizeof(block)); + memcpy(&invoke_pc,src+4*sizeof(void*),sizeof(invoke_pc)); + if (vptr!=(const uint8_t *)invoke_vtable+2*sizeof(void*) || + !aligned(previous) || !aligned(block) || + invoke_pc!=expected_invoke_pc) return -3; + memcpy(&get_vptr,previous,sizeof(get_vptr)); + memcpy(&get_pc,(const uint8_t*)previous+4*sizeof(void*),sizeof(get_pc)); + if (get_vptr!=(const uint8_t*)get_vtable+2*sizeof(void*) || + get_pc!=expected_get_pc) return -4; + const void *next=NULL,*prev_block=NULL; + memcpy(&next,(const uint8_t*)previous+2*sizeof(void*),sizeof(next)); + memcpy(&prev_block,(const uint8_t*)previous+3*sizeof(void*),sizeof(prev_block)); + if (next!=source || prev_block!=block) return -5; + // HBasicBlock::graph_ and HGraph::allocator_ (exact version only). + const void *graph=NULL,*arena=NULL; + memcpy(&graph,block,sizeof(graph)); + if (!aligned(graph)) return -6; + memcpy(&arena,graph,sizeof(arena)); + if (!aligned(arena)) return -6; + // Use the real virtual Clone, never reinterpret/allocate an ART node. + const void *clone_entry=NULL; + memcpy(&clone_entry,(const uint8_t*)vptr+14*sizeof(void*),sizeof(clone_entry)); + Dl_info ci={0}; + if (!aligned(clone_entry) || !dladdr(clone_entry,&ci) || + !named(ci.dli_fname,"libart-compiler.so")) return -7; + // Resolve the already-observed exported compiler method in Frida's + // namespace and pass its exact address: app JNI namespaces cannot assume + // dlopen("libart-compiler.so") is permitted by Android's linker policy. + Dl_info ai={0}; + if (!aligned(append_address) || !dladdr(append_address,&ai) || + !named(ai.dli_fname,"libart-compiler.so") || + ai.dli_sname==NULL || + strcmp(ai.dli_sname, + "_ZN3art19HInstructionBuilder17AppendInstructionEPNS_12HInstructionE")) + return -8; + typedef void *(*CloneFn)(const void*,void*); + void *copy=((CloneFn)clone_entry)(source,(void*)arena); + if (!aligned(copy)) return -9; + // ART's own AppendInstruction maintains SSA uses and environment state. + ((void (*)(void*,void*))append_address)(builder,copy); + const void *copy_block=NULL,*copy_prev=NULL; + memcpy(©_block,(const uint8_t*)copy+3*sizeof(void*),sizeof(copy_block)); + memcpy(©_prev,(const uint8_t*)copy+sizeof(void*),sizeof(copy_prev)); + return copy_block==block && copy_prev==source ? 1 : -10; +} + +/* + * Exact API33 x86_64 *fixture-only* invoke insertion. + * + * The earlier builder append experiment proved Clone() is callable but + * appended to the wrong basic block (rc=-10). InsertInstructionBefore() + * works directly on the actual source block, preserving instruction order. + * + * HEnvironment is an ART arena vector, not an object to share with a second + * holder. This prototype clones its source-matched layout into independent + * one-shot malloc storage (intentionally retained for the life of the process) + * and invokes ART's exported HEnvironment::CopyFrom() to rebuild env-use + * records in the graph's own arena. This is NOT production memory management. + * + * Source layout: Android 13 ART HInstruction and HEnvironment, libc++ x86_64 + * vector + ArenaAllocatorAdapter. Runtime and compiler ELF Build IDs MUST + * match exactly before touching the graph. Inlined environments are rejected. + */ +EXPORT int artwatch_shadow_clone_invoke_before( + const void *source, const void *get_vtable, const void *invoke_vtable, + uint32_t expected_get_pc, uint32_t expected_invoke_pc, + const void *insert_address, const void *copy_env_address, + int field_kind, void **out_clone) { + if (out_clone==NULL || !aligned(out_clone)) return -1; + *out_clone=NULL; + if ((field_kind!=1 && field_kind!=2) || ready != 1 || !aligned(source) || !aligned(get_vtable) || + !aligned(invoke_vtable) || !aligned(insert_address) || + !aligned(copy_env_address)) return -1; + struct {const void *address; const char *name;} syms[4] = { + {get_vtable,field_kind==2 ? + "_ZTVN3art17HInstanceFieldSetE" : "_ZTVN3art17HInstanceFieldGetE"}, + {invoke_vtable,"_ZTVN3art21HInvokeStaticOrDirectE"}, + {insert_address, + "_ZN3art11HBasicBlock23InsertInstructionBeforeEPNS_12HInstructionES2_"}, + {copy_env_address,"_ZN3art12HEnvironment8CopyFromEPS0_"} + }; + for (size_t n=0;n<4;n++) { + Dl_info info={0}; + if (!dladdr(syms[n].address,&info) || + !named(info.dli_fname,"libart-compiler.so") || + info.dli_sname==NULL || info.dli_saddr!=syms[n].address || + strcmp(info.dli_sname,syms[n].name)!=0) return -2; + } + const uint8_t *src=(const uint8_t*)source; + const void *vptr=NULL,*get=NULL,*block=NULL; + uint32_t get_pc=UINT32_MAX,invoke_pc=UINT32_MAX; + memcpy(&vptr,src,sizeof(vptr)); + memcpy(&get,src+8,sizeof(get)); + memcpy(&block,src+24,sizeof(block)); + memcpy(&invoke_pc,src+32,sizeof(invoke_pc)); + if (vptr!=(const uint8_t*)invoke_vtable+16 || !aligned(get) || + !aligned(block) || invoke_pc!=expected_invoke_pc) return -3; + // A write may have compiler-generated HIntConstant nodes between + // iput and the resolved sink invoke. Follow at most eight reciprocal + // same-block links for writes; keep the proved direct-read path. + const void *cursor=source; + const void *field=NULL; + const unsigned limit=field_kind==2 ? 8u : 1u; + for (unsigned n=0;n(uintptr_t)v_end || + (uintptr_t)v_end>(uintptr_t)v_cap) return -7; + size_t bytes=(uintptr_t)v_end-(uintptr_t)v_begin; + if ((bytes%16u)!=0u || bytes>128u*16u) return -7; + void *graph=NULL,*arena=NULL,*clone_entry=NULL; + memcpy(&graph,block,sizeof(graph)); + if (!aligned(graph)) return -8; + memcpy(&arena,graph,sizeof(arena)); + if (!aligned(arena)) return -8; + memcpy(&clone_entry,(const uint8_t*)vptr+14*8,sizeof(clone_entry)); + Dl_info ci={0}; + if (!aligned(clone_entry)||!dladdr(clone_entry,&ci)|| + !named(ci.dli_fname,"libart-compiler.so"))return -9; + + // Allocate before any IR mutation, so failure cannot leave a partial node. + void *environment=calloc(1,96); + void *records=calloc(1,bytes==0?16:bytes); + if (!environment || !records) { + free(environment); free(records); return -10; + } + memcpy(environment,old_env,96); + const uint8_t *begin=(const uint8_t*)records; + const void *new_end=begin+bytes; + memcpy((uint8_t*)environment+0,&records,8); + memcpy((uint8_t*)environment+8,&new_end,8); + memcpy((uint8_t*)environment+16,&new_end,8); + typedef void *(*CloneFn)(const void*,void*); + void *copy=((CloneFn)clone_entry)(source,arena); + if (!aligned(copy)) {free(environment);free(records);return -11;} + memcpy((uint8_t*)environment+88,©,8); + // Insert updates input users, IDs, and block links through ART itself. + ((void(*)(void*,void*,void*))insert_address)((void*)block,copy,(void*)source); + // CopyFrom creates *new* env-use list entries on graph-owned allocators. + ((void(*)(void*,void*))copy_env_address)(environment,(void*)old_env); + memcpy((uint8_t*)copy+64,&environment,8); + // Heap environment is intentionally retained after graph lifetime. + const void *copy_block=NULL,*copy_next=NULL,*copy_env=NULL; + memcpy(©_block,(const uint8_t*)copy+24,8); + memcpy(©_next,(const uint8_t*)copy+16,8); + memcpy(©_env,(const uint8_t*)copy+64,8); + if (copy_block==block && copy_next==source && copy_env==environment) { + *out_clone=copy; + return 1; + } + return -12; +} +// Writes only into the caller's scratch buffer, never to ART memory. +EXPORT int artwatch_shadow_report(char *out, uint32_t length) { + if (out == NULL || length < 96) return 0; + int n = snprintf(out, length, + "{\"ready\":%s,\"graphs\":%llu,\"gets\":%llu,\"sets\":%llu," + "\"blocks\":%llu,\"rejected\":%llu,\"opaqueGraphWord\":\"0x%llx\"}", + ready == 1 ? "true" : "false", + (unsigned long long)__atomic_load_n(&graphs, __ATOMIC_RELAXED), + (unsigned long long)__atomic_load_n(&gets, __ATOMIC_RELAXED), + (unsigned long long)__atomic_load_n(&sets, __ATOMIC_RELAXED), + (unsigned long long)__atomic_load_n(&blocks, __ATOMIC_RELAXED), + (unsigned long long)__atomic_load_n(&rejected, __ATOMIC_RELAXED), + (unsigned long long)__atomic_load_n(&opaque_graph_word, __ATOMIC_RELAXED)); + return n > 0 && (uint32_t)n < length ? 1 : 0; +} diff --git a/art-fieldwatch-phase1/native/runtime-events.c b/art-fieldwatch-phase1/native/runtime-events.c new file mode 100644 index 0000000..57d654a --- /dev/null +++ b/art-fieldwatch-phase1/native/runtime-events.c @@ -0,0 +1,395 @@ +// Executable P2 event transport. No ART C++ or compiler internals. +// JNI is called only by a deliberately explicit Java fixture in this +// milestone. Compiler-side insertion is a separate, unimplemented step. +// Runtime hot path: bounded fixed storage, atomics, no allocation or locks. +#include +#include +#include +#include +#include +#include + +#define EVENT_EXPORT __attribute__((visibility("default"))) +#define EVENT_CAPACITY 512u +struct field_event { + uint32_t site; + uint32_t kind; // 1 = successful read, 2 = successful write + int32_t value; +}; +static struct field_event events[EVENT_CAPACITY]; +static atomic_uint ready[EVENT_CAPACITY]; +static atomic_uint next_index = 0; +static atomic_uint dropped = 0; +static atomic_uint p3_enabled = 0; +static atomic_uint p3_sentinel_sequence = 0; +// Frozen after P3 verification, before the independent P2 workload resets events. +static struct field_event p3_verified_events[256]; +static atomic_uint p3_archive_ready = 0; +static void reset_detailed_events(void); +static int archive_p3_field_metadata(void); +// P3's concrete DEX field identity is installed only after the exact cloned +// invoke nodes survived backend emission. This metadata is immutable while +// the measured fixture runs; it does not establish general app-wide coverage. +static atomic_uint p3_dex_id, p3_method_id, p3_field_id; +static atomic_uint p3_write_pc, p3_read_pc; +static atomic_uint p3_metadata_ready; +EVENT_EXPORT void artwatch_events_record_field( + uint32_t dex_id, uint32_t method_id, uint32_t field_id, + uint32_t dex_pc, uint32_t kind, uint32_t type, uint64_t bits); +EVENT_EXPORT int artwatch_events_configure_p3( + uint32_t dex_id, uint32_t method_id, uint32_t field_id, + uint32_t write_pc, uint32_t read_pc) { + if (atomic_load_explicit(&p3_enabled,memory_order_acquire) || + atomic_load_explicit(&p3_metadata_ready,memory_order_acquire)) + return 0; + atomic_store_explicit(&p3_dex_id,dex_id,memory_order_relaxed); + atomic_store_explicit(&p3_method_id,method_id,memory_order_relaxed); + atomic_store_explicit(&p3_field_id,field_id,memory_order_relaxed); + atomic_store_explicit(&p3_write_pc,write_pc,memory_order_relaxed); + atomic_store_explicit(&p3_read_pc,read_pc,memory_order_relaxed); + atomic_store_explicit(&p3_metadata_ready,1u,memory_order_release); + return 1; +} +// Only the controlled fixture sets P3; ordinary P2 events are unchanged. +EVENT_EXPORT void artwatch_events_set_p3(int enabled) { + atomic_store_explicit(&p3_enabled, enabled ? 1u : 0u, memory_order_release); +} +JNIEXPORT jboolean JNICALL +Java_com_example_artfieldwatch_FieldEventSink_p3Enabled(JNIEnv *env,jclass cls) { + (void)env; (void)cls; + return atomic_load_explicit(&p3_enabled,memory_order_acquire) ? JNI_TRUE : JNI_FALSE; +} +JNIEXPORT jboolean JNICALL +Java_com_example_artfieldwatch_FieldEventSink_p3Verified(JNIEnv *env,jclass cls) { + (void)env; (void)cls; + if (atomic_load_explicit(&next_index,memory_order_acquire)!=256u || + atomic_load_explicit(&dropped,memory_order_acquire)!=0u) + return JNI_FALSE; + for (uint32_t i=0;i<128u;++i) { + if (atomic_load_explicit(&ready[2u*i],memory_order_acquire)!=1u || + atomic_load_explicit(&ready[2u*i+1u],memory_order_acquire)!=1u || + events[2u*i].site!=9001u || events[2u*i].kind!=2u || + events[2u*i].value!=(int32_t)(7u+3u*i) || + events[2u*i+1u].site!=9002u || events[2u*i+1u].kind!=1u || + events[2u*i+1u].value!=(int32_t)(7u+3u*i)) + return JNI_FALSE; + } + // P3 completion must verify both legacy transport AND typed DEX metadata. + // Archive before P2 resets their independent live measurement buffers. + if (!archive_p3_field_metadata()) return JNI_FALSE; + memcpy(p3_verified_events, events, sizeof(p3_verified_events)); + atomic_store_explicit(&p3_archive_ready, 1u, memory_order_release); + return JNI_TRUE; +} + +// Only the single-purpose CI producer may call reset, after warmup +// finishes and before the measured 128 invocations. Not safe to reset +// while any thread is producing or consuming. +static void clear_events(void) { + atomic_store_explicit(&next_index, 0, memory_order_relaxed); + atomic_store_explicit(&dropped, 0, memory_order_relaxed); + atomic_store_explicit(&p3_sentinel_sequence, 0, memory_order_relaxed); + reset_detailed_events(); + for (uint32_t i = 0; i < EVENT_CAPACITY; ++i) + atomic_store_explicit(&ready[i], 0, memory_order_relaxed); +} +JNIEXPORT void JNICALL +Java_com_example_artfieldwatch_FieldEventSink_reset(JNIEnv *env, jclass cls) { + (void)env; + (void)cls; + clear_events(); +} +JNIEXPORT void JNICALL +Java_com_example_artfieldwatch_FieldEventSink_recordInt( + JNIEnv *env, jclass cls, jint site, jint kind, jint value) { + (void)env; + (void)cls; + // Keep a real, resolved invoke in the P3 template carrier without + // counting the deliberately inactive site/kind (0,0) as a field event. + if (site == 0 && kind == 0) { + if (!atomic_load_explicit(&p3_enabled,memory_order_acquire)) return; + // ART inserts the cloned call immediately BEFORE the source invoke. + // Record only cloned write then cloned read calls, not Java source calls. + // Ignore the original Java-authored sentinel entirely. + uint32_t n=atomic_fetch_add_explicit(&p3_sentinel_sequence,1u, + memory_order_relaxed); + if ((n & 1u)!=0u) return; + site=(n & 2u)==0u ? 9001 : 9002; + kind=(n & 2u)==0u ? 2 : 1; + // This P3 adapter still identifies the cloned call by validated + // clone-before-original ordering. The generic ABI itself does not + // require that sentinel scheme. + if (atomic_load_explicit(&p3_metadata_ready,memory_order_acquire)) { + const uint32_t pc=atomic_load_explicit( + kind==2 ? &p3_write_pc : &p3_read_pc,memory_order_relaxed); + artwatch_events_record_field( + atomic_load_explicit(&p3_dex_id,memory_order_relaxed), + atomic_load_explicit(&p3_method_id,memory_order_relaxed), + atomic_load_explicit(&p3_field_id,memory_order_relaxed), + pc,(uint32_t)kind,5u,(uint64_t)(int64_t)value); + } + } + uint32_t index = atomic_fetch_add_explicit(&next_index, 1u, + memory_order_relaxed); + if (index >= EVENT_CAPACITY) { + atomic_fetch_add_explicit(&dropped, 1u, memory_order_relaxed); + return; + } + events[index].site = (uint32_t)site; + events[index].kind = (uint32_t)kind; + events[index].value = (int32_t)value; + atomic_store_explicit(&ready[index], 1u, memory_order_release); +} +// Single-producer negative-control counter. No reset during measurement. +JNIEXPORT jint JNICALL +Java_com_example_artfieldwatch_FieldEventSink_eventCount(JNIEnv *env, jclass cls) { + (void)env; + (void)cls; + return (jint)atomic_load_explicit(&next_index, memory_order_acquire); +} +// Frida polls this *after* Java logs RUNTIME_EVENTS_DONE. The hot +// recorder never formats JSON. Snapshot is read-only and bounded. +// Return 0 when buffer is insufficient or an event is not published yet. +static int format_events(char *out, uint32_t length, + const struct field_event *stored_events, + uint32_t total, uint32_t lost, uint32_t count, + int check_live_ready) { + if (out == NULL || length < 512) return 0; + size_t used = 0; + int written = snprintf(out, length, + "{\"version\":1,\"total\":%u,\"dropped\":%u,\"capacity\":%u,\"events\":[", + total, lost, EVENT_CAPACITY); + if (written < 0 || (size_t)written >= length) return 0; + used += (size_t)written; + for (uint32_t i = 0; i < count; ++i) { + if (check_live_ready && + atomic_load_explicit(&ready[i], memory_order_acquire) != 1u) return 0; + if (used >= length) return 0; + written = snprintf(out + used, length - used, + "%s{\"seq\":%u,\"site\":%u,\"kind\":%u,\"value\":%d}", + i == 0 ? "" : ",", i + 1u, + stored_events[i].site, stored_events[i].kind, stored_events[i].value); + if (written < 0 || (size_t)written >= length - used) return 0; + used += (size_t)written; + } + if (used + 3u > length) return 0; + out[used++] = ']'; + out[used++] = '}'; + out[used] = '\0'; + return 1; +} + +// Export the verified P3 data independently of the later P2 reset. +EVENT_EXPORT int artwatch_events_p3_snapshot(char *out, uint32_t length) { + if (atomic_load_explicit(&p3_archive_ready, memory_order_acquire) != 1u) + return 0; + return format_events(out, length, p3_verified_events, 256u, 0u, 256u, 0); +} + +EVENT_EXPORT int artwatch_events_snapshot(char *out, uint32_t length) { + const uint32_t total = atomic_load_explicit(&next_index, memory_order_acquire); + const uint32_t lost = atomic_load_explicit(&dropped, memory_order_acquire); + const uint32_t count = total < EVENT_CAPACITY ? total : EVENT_CAPACITY; + return format_events(out, length, events, total, lost, count, 1); +} + +/* + * Generic compiler-event ABI (no Java fixture site constants): + * dex_id identifies the per-APK DEX, method/field IDs are DEX table indices, + * dex_pc is the instruction's actual DEX code-unit PC. + * type: 1 boolean, 2 byte, 3 char, 4 short, 5 int, 6 long, + * 7 float, 8 double, 9 object identity (opaque unsigned bits). + * value_bits is the exact primitive bit pattern or an opaque reference token. + * JNI refs must not be held here. Java object identity requires a separate + * GC-safe producer before it can be supported end-to-end. + * + * The ABI is ready for source-matched compiler-side calls. Existing P2/P3 + * recordInt is intentionally untouched until the injector migrates to this. + */ +#define FIELD_METADATA_CAPACITY 4096u +struct detailed_field_event { + uint32_t dex_id, method_id, field_id, dex_pc, kind, type; + uint64_t bits; +}; +static struct detailed_field_event detailed_events[FIELD_METADATA_CAPACITY]; +static atomic_uint detailed_ready[FIELD_METADATA_CAPACITY]; +static atomic_uint detailed_count = 0; +static atomic_uint detailed_dropped = 0; +// P3 validated snapshot survives later resets and the explicitly authored P2 workload. +static struct detailed_field_event p3_detailed_verified[256]; +static atomic_uint p3_detailed_archive_ready = 0; +static void reset_detailed_events(void) { + atomic_store_explicit(&detailed_count,0u,memory_order_relaxed); + atomic_store_explicit(&detailed_dropped,0u,memory_order_relaxed); + for(uint32_t i=0;idex_id!=dex || ev->method_id!=method || ev->field_id!=field || + ev->kind!=kind || ev->dex_pc!=(kind==2u?wpc:rpc) || + ev->type!=5u || ev->bits!=(uint64_t)(7u+3u*(i/2u))) + return 0; + } + memcpy(p3_detailed_verified,detailed_events,sizeof(p3_detailed_verified)); + atomic_store_explicit(&p3_detailed_archive_ready,1u,memory_order_release); + return 1; +} +EVENT_EXPORT void artwatch_events_record_field( + uint32_t dex_id, uint32_t method_id, uint32_t field_id, + uint32_t dex_pc, uint32_t kind, uint32_t type, uint64_t bits) { + if ((kind != 1u && kind != 2u) || type < 1u || type > 9u) return; + const uint32_t slot=atomic_fetch_add_explicit(&detailed_count,1u,memory_order_relaxed); + if (slot >= FIELD_METADATA_CAPACITY) { + atomic_fetch_add_explicit(&detailed_dropped,1u,memory_order_relaxed); + return; + } + detailed_events[slot]=(struct detailed_field_event){ + .dex_id=dex_id, .method_id=method_id, .field_id=field_id, + .dex_pc=dex_pc, .kind=kind, .type=type, .bits=bits + }; + atomic_store_explicit(&detailed_ready[slot],1u,memory_order_release); +} +// Exact six-int ABI called by the source-matched ART direct injector. +// Signed int32 values are sign-extended into the 64-bit transport. +JNIEXPORT void JNICALL +Java_com_example_artfieldwatch_FieldEventSink_recordFieldInt( + JNIEnv *env,jclass cls,jint dex_id,jint method_id,jint field_id, + jint dex_pc,jint kind,jint value) { + (void)env; (void)cls; + if (dex_id<0 || method_id<0 || field_id<0 || dex_pc<0) return; + artwatch_events_record_field((uint32_t)dex_id,(uint32_t)method_id, + (uint32_t)field_id,(uint32_t)dex_pc,(uint32_t)kind,5u, + (uint64_t)(int64_t)(int32_t)value); +} + +static int valid_field_ids(jint dex,jint method,jint field,jint pc) { + return dex>=0 && method>=0 && field>=0 && pc>=0; +} +// Primitive value transfer is explicit: no native re-read, reflection, +// heap allocation, or precision-losing float-to-JSON numeric conversion. +JNIEXPORT void JNICALL +Java_com_example_artfieldwatch_FieldEventSink_recordFieldLong( + JNIEnv *env,jclass cls,jint dex,jint method,jint field,jint pc,jint kind,jlong value) { + (void)env;(void)cls; + if (!valid_field_ids(dex,method,field,pc)) return; + artwatch_events_record_field((uint32_t)dex,(uint32_t)method,(uint32_t)field, + (uint32_t)pc,(uint32_t)kind,6u,(uint64_t)(int64_t)value); +} +JNIEXPORT void JNICALL +Java_com_example_artfieldwatch_FieldEventSink_recordFieldFloat( + JNIEnv *env,jclass cls,jint dex,jint method,jint field,jint pc,jint kind,jfloat value) { + (void)env;(void)cls; + if (!valid_field_ids(dex,method,field,pc)) return; + uint32_t raw=0; + _Static_assert(sizeof(jfloat)==sizeof(raw),"JNI float is not 32-bit"); + memcpy(&raw,&value,sizeof(raw)); + artwatch_events_record_field((uint32_t)dex,(uint32_t)method,(uint32_t)field, + (uint32_t)pc,(uint32_t)kind,7u,(uint64_t)raw); +} +JNIEXPORT void JNICALL +Java_com_example_artfieldwatch_FieldEventSink_recordFieldDouble( + JNIEnv *env,jclass cls,jint dex,jint method,jint field,jint pc,jint kind,jdouble value) { + (void)env;(void)cls; + if (!valid_field_ids(dex,method,field,pc)) return; + uint64_t raw=0; + _Static_assert(sizeof(jdouble)==sizeof(raw),"JNI double is not 64-bit"); + memcpy(&raw,&value,sizeof(raw)); + artwatch_events_record_field((uint32_t)dex,(uint32_t)method,(uint32_t)field, + (uint32_t)pc,(uint32_t)kind,8u,raw); +} +JNIEXPORT void JNICALL +Java_com_example_artfieldwatch_FieldEventSink_recordFieldNarrow( + JNIEnv *env,jclass cls,jint dex,jint method,jint field,jint pc, + jint kind,jint type,jint value) { + (void)env;(void)cls; + if (!valid_field_ids(dex,method,field,pc)) return; + uint64_t bits=0; + switch(type) { + case 1: + if (value!=0 && value!=1) return; + bits=(uint64_t)(uint32_t)value; + break; + case 2: bits=(uint64_t)(int64_t)(int8_t)value;break; + case 3: bits=(uint64_t)(uint16_t)value;break; + case 4: bits=(uint64_t)(int64_t)(int16_t)value;break; + case 5: bits=(uint64_t)(int64_t)(int32_t)value;break; + default:return; + } + artwatch_events_record_field((uint32_t)dex,(uint32_t)method,(uint32_t)field, + (uint32_t)pc,(uint32_t)kind,(uint32_t)type,bits); +} + +EVENT_EXPORT int artwatch_events_field_snapshot(char *out,uint32_t length) { + if (out==NULL || length<128u) return 0; + const uint32_t total=atomic_load_explicit(&detailed_count,memory_order_acquire); + const uint32_t dropped=atomic_load_explicit(&detailed_dropped,memory_order_acquire); + const uint32_t stored=total=length) return 0; + used+=(size_t)n; + for(uint32_t i=0;idex_id,e->method_id,e->field_id,e->dex_pc, + e->kind,e->type,(unsigned long long)e->bits); + if (n<0 || (size_t)n>=length-used) return 0; + used+=(size_t)n; + } + if (used+3u>length) return 0; + out[used++]=']';out[used++]='}';out[used]='\0'; + return 1; +} + +EVENT_EXPORT int artwatch_events_p3_field_snapshot(char *out,uint32_t length) { + if (atomic_load_explicit(&p3_detailed_archive_ready,memory_order_acquire)!=1u || + out==NULL || length<128u) return 0; + size_t used=0; + int n=snprintf(out,length, + "{\"version\":2,\"total\":256,\"dropped\":0,\"events\":["); + if (n<0 || (size_t)n>=length) return 0; + used+=(size_t)n; + for(uint32_t i=0;i<256u;i++) { + const struct detailed_field_event *e=&p3_detailed_verified[i]; + n=snprintf(out+used,length-used, + "%s{\"seq\":%u,\"dexId\":%u,\"methodId\":%u," + "\"fieldId\":%u,\"dexPc\":%u,\"kind\":%u,\"type\":%u," + "\"valueBits\":\"0x%016llx\"}",i?",":"", + i+1u,e->dex_id,e->method_id,e->field_id,e->dex_pc, + e->kind,e->type,(unsigned long long)e->bits); + if (n<0 || (size_t)n>=length-used) return 0; + used+=(size_t)n; + } + if (used+3u>length) return 0; + out[used++]=']';out[used++]='}';out[used]='\0'; + return 1; +} diff --git a/art-fieldwatch-phase1/test/app/build.gradle b/art-fieldwatch-phase1/test/app/build.gradle new file mode 100644 index 0000000..eecc2b4 --- /dev/null +++ b/art-fieldwatch-phase1/test/app/build.gradle @@ -0,0 +1,36 @@ +plugins { + id 'com.android.application' +} +android { + namespace 'com.example.artfieldwatch' + compileSdk 35 + defaultConfig { + applicationId 'com.example.artfieldwatch' + minSdk 21 + targetSdk 28 + versionCode 1 + versionName '0.1' + } + // Only an emulator research fixture, not a Play-distributed APK. + // Keep targetSdk 28 for Android compatibility while suppressing exactly + // the Play Store target-SDK expiry diagnostic in release lint. + lint { + disable 'ExpiredTargetSdkVersion' + } + // Ensure app-native libraries are extracted under the installed + // nativeLibraryDir, which has the correct executable file labeling. + packaging { + jniLibs { + useLegacyPackaging true + } + } + buildTypes { + release { + // Keep the build non-debuggable while signing it for emulator installation. + // A root frida-server can instrument non-debuggable packages. + debuggable false + minifyEnabled false + signingConfig signingConfigs.debug + } + } +} diff --git a/art-fieldwatch-phase1/test/app/src/main/AndroidManifest.xml b/art-fieldwatch-phase1/test/app/src/main/AndroidManifest.xml new file mode 100644 index 0000000..e40790c --- /dev/null +++ b/art-fieldwatch-phase1/test/app/src/main/AndroidManifest.xml @@ -0,0 +1,10 @@ + + + + + + + + + + diff --git a/art-fieldwatch-phase1/test/app/src/main/java/com/example/artfieldwatch/DirectAbiTarget.java b/art-fieldwatch-phase1/test/app/src/main/java/com/example/artfieldwatch/DirectAbiTarget.java new file mode 100644 index 0000000..b178360 --- /dev/null +++ b/art-fieldwatch-phase1/test/app/src/main/java/com/example/artfieldwatch/DirectAbiTarget.java @@ -0,0 +1,24 @@ +package com.example.artfieldwatch; + +/** Explicit JNI ABI contract for the direct compiler sink; NOT ART injection. */ +public final class DirectAbiTarget { + private int value; + private static int shared; + + public static int exercise() { + FieldEventSink.resetFieldMeta(); + DirectAbiTarget target = new DirectAbiTarget(); + target.value = -11; + FieldEventSink.recordFieldInt(0, 3, 17, 7, FieldEventSink.WRITE, -11); + int observed = target.value; + FieldEventSink.recordFieldInt(0, 3, 17, 9, FieldEventSink.READ, observed); + shared = 42; + FieldEventSink.recordFieldInt(0, 4, 18, 11, FieldEventSink.WRITE, 42); + int staticObserved = shared; + FieldEventSink.recordFieldInt(0, 4, 18, 13, FieldEventSink.READ, staticObserved); + if (observed != -11 || staticObserved != 42 || + FieldEventSink.fieldMetaCount() != 4) + throw new AssertionError("Direct JNI ABI contract failed"); + return 103; + } +} diff --git a/art-fieldwatch-phase1/test/app/src/main/java/com/example/artfieldwatch/FieldEventSink.java b/art-fieldwatch-phase1/test/app/src/main/java/com/example/artfieldwatch/FieldEventSink.java new file mode 100644 index 0000000..7cd9b63 --- /dev/null +++ b/art-fieldwatch-phase1/test/app/src/main/java/com/example/artfieldwatch/FieldEventSink.java @@ -0,0 +1,35 @@ +package com.example.artfieldwatch; + +/** + * Controlled prototype of the future side-effecting compiler event call. + * recordInt() is native, externally observable, and deliberately invoked + * by fixture bytecode. It is NOT yet inserted into ART HGraph. + */ +public final class FieldEventSink { + private FieldEventSink() {} + + public static final int READ = 1; + public static final int WRITE = 2; + public static final int SITE_WRITE_VALUE = 9001; + public static final int SITE_READ_VALUE = 9002; + + public static native void recordInt(int site, int kind, int value); + public static native void recordFieldInt(int dexId, int methodId, + int fieldId, int dexPc, int kind, int value); + // JNI inputs carry original field values; raw float/double bits are + // preserved as unsigned hexadecimal fields in the event transport. + public static native void recordFieldLong(int dexId,int methodId, + int fieldId,int dexPc,int kind,long value); + public static native void recordFieldFloat(int dexId,int methodId, + int fieldId,int dexPc,int kind,float value); + public static native void recordFieldDouble(int dexId,int methodId, + int fieldId,int dexPc,int kind,double value); + public static native void recordFieldNarrow(int dexId,int methodId, + int fieldId,int dexPc,int kind,int type,int value); + public static native void resetFieldMeta(); + public static native int fieldMetaCount(); + public static native void reset(); + public static native int eventCount(); + public static native boolean p3Enabled(); + public static native boolean p3Verified(); +} diff --git a/art-fieldwatch-phase1/test/app/src/main/java/com/example/artfieldwatch/FieldIRTarget.java b/art-fieldwatch-phase1/test/app/src/main/java/com/example/artfieldwatch/FieldIRTarget.java new file mode 100644 index 0000000..4ff98b2 --- /dev/null +++ b/art-fieldwatch-phase1/test/app/src/main/java/com/example/artfieldwatch/FieldIRTarget.java @@ -0,0 +1,212 @@ +package com.example.artfieldwatch; + +/** Deliberately tiny DEX iget/iput test for compiler IR experiments. */ +public final class FieldIRTarget { + private int value; + + public int test(int x) { + value = x; + return value; + } + + // An opaque helper prevents purely intra-method DEX simplification + // while giving ART's optimizing JIT an inlining opportunity. + private static FieldIRTarget identity(FieldIRTarget target) { + return target; + } + + public int testViaIdentity(int x) { + value = x; + return identity(this).value; + } + + // Keep these alternate JIT compilation sites structurally distinct. + // The helper makes the value read visible in release DEX while ART + // can inline the helper and eliminate redundant field operations. + public static int exerciseOverwrites(int iterations) { + FieldIRTarget target = new FieldIRTarget(); + int checksum = 0; + for (int i = 0; i < iterations; i++) { + target.value = i; + target.value = i + 1; + int observed = identity(target).value; + if (observed != i + 1) { + throw new AssertionError("Overwrite read mismatch at " + i); + } + checksum += observed & 1; + } + return checksum; + } + + public static int exerciseAlternating(int iterations) { + FieldIRTarget target = new FieldIRTarget(); + int checksum = 0; + for (int i = 0; i < iterations; i++) { + int expected; + if ((i & 1) == 0) { + target.value = i; + expected = i; + } else { + target.value = i + 1; + expected = i + 1; + } + int observed = identity(target).value; + if (observed != expected) { + throw new AssertionError("Alternating read mismatch at " + i); + } + checksum += observed & 1; + } + return checksum; + } + + // First executable field-event path. The calls are explicit in Java + // bytecode for now; future compiler injection must place equivalent + // side-effecting calls at the successful field-access IR boundary. + public static int watchedOn(FieldIRTarget receiver, int x) { + receiver.value = x; // Throws on null BEFORE any write event. + FieldEventSink.recordInt(FieldEventSink.SITE_WRITE_VALUE, + FieldEventSink.WRITE, x); + int observed = identity(receiver).value; + FieldEventSink.recordInt(FieldEventSink.SITE_READ_VALUE, + FieldEventSink.READ, observed); + return observed; + } + + // Same-graph native invoke template for a future ART Clone()/InsertInstructionAfter. + // The native sink ignores site=kind=0. No counted event can originate + // here without compiler injection changing the call's SSA operands. + public static int p3TemplateCarrierOn(FieldIRTarget receiver, int x) { + receiver.value = x; + FieldEventSink.recordInt(0, 0, x); // write template (cloned by ART) + int observed = identity(receiver).value; + FieldEventSink.recordInt(0, 0, observed); // read template (cloned by ART) + return observed; + } + + public static int exerciseP3TemplateCarrier(boolean requireInjection) + throws InterruptedException { + FieldIRTarget target = new FieldIRTarget(); + for (int i = 0; i < 100000; i++) { + if (p3TemplateCarrierOn(target, i) != i) + throw new AssertionError("P3 template warmup mismatch: " + i); + } + if (requireInjection) { + // JIT compilation is asynchronous. In prior CI the 128 reads ran at + // 09:18:32 while ART didn't insert the invoke until 09:18:34. + // Keep the call hot until the *successful compiler completion* + // signal, then allow the runtime to publish the JIT code. + long deadline = System.nanoTime() + 15_000_000_000L; + while (!FieldEventSink.p3Enabled()) { + for (int i = 0; i < 1000; i++) { + if (p3TemplateCarrierOn(target, i) != i) + throw new AssertionError("P3 asynchronous warmup mismatch"); + } + if (System.nanoTime() >= deadline) + throw new AssertionError("P3 compiler injection was not activated"); + Thread.sleep(20); + } + Thread.sleep(200); + for (int i = 0; i < 2000; i++) { + if (p3TemplateCarrierOn(target, i) != i) + throw new AssertionError("P3 published JIT mismatch"); + } + } + FieldEventSink.reset(); + int checksum = 0; + for (int i = 0; i < 128; i++) { + int expected = 7 + 3 * i; + int result = p3TemplateCarrierOn(target, expected); + if (result != expected) + throw new AssertionError("P3 template value mismatch: " + i); + checksum += result; + } + boolean threw = false; + try { p3TemplateCarrierOn(null, 777); } + catch (NullPointerException expected) { threw = true; } + if (!threw) throw new AssertionError("P3 template null write did not throw"); + if (requireInjection) { + if (!FieldEventSink.p3Enabled() || !FieldEventSink.p3Verified()) + throw new AssertionError("Compiler-cloned P3 reads missing or incorrect"); + } else if (FieldEventSink.eventCount() != 0) { + throw new AssertionError("P3 template polluted the event stream"); + } + return checksum; + } + + // No explicit sink calls. The only possible future event source is P3 injection. + public static int p3CanaryOn(FieldIRTarget receiver, int x) { + receiver.value = x; + return identity(receiver).value; + } + + public static int exerciseP3UninstrumentedCanary() { + FieldIRTarget target = new FieldIRTarget(); + for (int i = 0; i < 100000; i++) { + if (p3CanaryOn(target, i) != i) + throw new AssertionError("P3 warmup mismatch: " + i); + } + FieldEventSink.reset(); + int checksum = 0; + for (int i = 0; i < 128; i++) { + int expected = 7 + 3 * i; + int result = p3CanaryOn(target, expected); + if (result != expected) + throw new AssertionError("P3 canary value mismatch: " + i); + checksum += result; + } + boolean threw = false; + try { + p3CanaryOn(null, 777); + } catch (NullPointerException expected) { + threw = true; + } + if (!threw) throw new AssertionError("P3 null write did not throw"); + if (FieldEventSink.eventCount() != 0) + throw new AssertionError("Uninstrumented canary emitted events"); + return checksum; + } + + public static int exerciseRuntimeEvents() { + FieldIRTarget target = new FieldIRTarget(); + // Heat the same method before reset, allowing the JIT to compile it + // naturally. The measured phase contains exactly 128 calls. + for (int i = 0; i < 100000; i++) { + if (watchedOn(target, i) != i) + throw new AssertionError("Native event warmup mismatch at " + i); + } + FieldEventSink.reset(); + int checksum = 0; + for (int i = 0; i < 128; i++) { + int expected = 7 + 3 * i; + int result = watchedOn(target, expected); + if (result != expected) + throw new AssertionError("Native event value mismatch at " + i); + checksum += result; + } + // Null receiver must throw before any successful access callback. + boolean threw = false; + try { + watchedOn(null, 777); + } catch (NullPointerException expected) { + threw = true; + } + if (!threw) + throw new AssertionError("Null write did not throw NPE"); + return checksum; + } + + public static int warmup(int iterations) { + FieldIRTarget target = new FieldIRTarget(); + int observed = 0; + for (int i = 0; i < iterations; i++) { + if (target.test(i) != i) { + throw new AssertionError("FieldIRTarget direct read/write mismatch at " + i); + } + if (target.testViaIdentity(i) != i) { + throw new AssertionError("FieldIRTarget identity read/write mismatch at " + i); + } + observed++; + } + return observed; + } +} diff --git a/art-fieldwatch-phase1/test/app/src/main/java/com/example/artfieldwatch/FieldWatchTarget.java b/art-fieldwatch-phase1/test/app/src/main/java/com/example/artfieldwatch/FieldWatchTarget.java new file mode 100644 index 0000000..955131d --- /dev/null +++ b/art-fieldwatch-phase1/test/app/src/main/java/com/example/artfieldwatch/FieldWatchTarget.java @@ -0,0 +1,25 @@ +package com.example.artfieldwatch; +public final class FieldWatchTarget { + private int counter; + private volatile long published; + private static Object lastObject; + private static volatile int checksum; + private int readCounter() { return counter; } + private void writeCounter(int x) { counter = x; } + private long readPublished() { return published; } + private void writePublished(long x) { published = x; } + public static int exercise(int iterations) { + FieldWatchTarget target = new FieldWatchTarget(); + int sum = 0; + for (int i = 0; i < iterations; i++) { + target.writeCounter(i); + sum += target.readCounter(); + target.writePublished(sum); + sum += (int) target.readPublished(); + lastObject = target; + if (lastObject == null) throw new AssertionError(); + } + checksum = sum; + return checksum; + } +} diff --git a/art-fieldwatch-phase1/test/app/src/main/java/com/example/artfieldwatch/JvmtiTarget.java b/art-fieldwatch-phase1/test/app/src/main/java/com/example/artfieldwatch/JvmtiTarget.java new file mode 100644 index 0000000..829f607 --- /dev/null +++ b/art-fieldwatch-phase1/test/app/src/main/java/com/example/artfieldwatch/JvmtiTarget.java @@ -0,0 +1,20 @@ +package com.example.artfieldwatch; +/** Pure Java field access fixture: no callbacks or sink calls in bytecode. */ +public final class JvmtiTarget { + private int instanceValue; + private static long staticValue; + public static int exercise(int count) { + JvmtiTarget holder=new JvmtiTarget(); + int sum=0; + for(int i=0;i { + long accumulator = 0; + try { + for (int i = 0; i < 40; i++) + accumulator += FieldWatchTarget.exercise(100000); + accumulator += FieldIRTarget.warmup(150000); + // Give the non-debuggable app enough hot calls for optimized compilation. + // No deoptimization or reflective compiler calls are used. + if (!appDebuggable) { + // Distinct methods generate multiple natural JIT compilation + // opportunities. Brief pauses allow the worker to drain its queue. + // No deoptimization or hidden ART APIs are invoked. + for (int stage = 0; stage < 5; stage++) { + accumulator += FieldIRTarget.warmup(300000); + accumulator += FieldIRTarget.exerciseOverwrites(300000); + accumulator += FieldIRTarget.exerciseAlternating(300000); + Log.i("ARTWATCH_CI", "LSE_STAGE_DONE=" + stage); + Thread.sleep(400); + } + } + // Executed from the real app worker; the host Frida client drains + // the native records after this completion marker. + if (android.os.Build.VERSION.SDK_INT == 33) { + int carrierChecksum = FieldIRTarget.exerciseP3TemplateCarrier(appDebuggable); + Log.i("ARTWATCH_CI","P3_TEMPLATE_DONE count=" + + FieldEventSink.eventCount() + " checksum=" + + carrierChecksum + " nullCheck=true injected=" + + FieldEventSink.p3Enabled()); + accumulator += carrierChecksum; + int canaryChecksum = FieldIRTarget.exerciseP3UninstrumentedCanary(); + Log.i("ARTWATCH_CI","P3_CANARY_DONE count=0 checksum=" + + canaryChecksum + " nullCheck=true"); + accumulator += canaryChecksum; + int runtimeChecksum = FieldIRTarget.exerciseRuntimeEvents(); + Log.i("ARTWATCH_CI","RUNTIME_EVENTS_DONE count=256 checksum=" + + runtimeChecksum + " nullCheck=true"); + accumulator += runtimeChecksum; + // Explicit transport-only ABI check. NOT a compiler-injection result. + int abiChecksum = DirectAbiTarget.exercise(); + Log.i("ARTWATCH_CI","DIRECT_ABI_DONE count=" + + FieldEventSink.fieldMetaCount() + " checksum=" + abiChecksum); + accumulator += abiChecksum; + int primitiveChecksum = PrimitiveAbiTarget.exercise(); + Log.i("ARTWATCH_CI","PRIMITIVE_ABI_DONE count=" + + FieldEventSink.fieldMetaCount() + " checksum=" + primitiveChecksum); + accumulator += primitiveChecksum; + if (appDebuggable) { + int watchChecksum = JvmtiTarget.exercise(64); + Log.i("ARTWATCH_CI","JVMTI_NO_TEMPLATE_DONE checksum=" + watchChecksum); + accumulator += watchChecksum; + } + } + Log.i("ARTWATCH_CI","WARMUP_DONE checksum=" + accumulator); + } catch (Throwable t) { + Log.e("ARTWATCH_CI","WARMUP_FAILED",t); + } + }, "FieldwatchWarmup").start(); + } +} diff --git a/art-fieldwatch-phase1/test/app/src/main/java/com/example/artfieldwatch/PrimitiveAbiTarget.java b/art-fieldwatch-phase1/test/app/src/main/java/com/example/artfieldwatch/PrimitiveAbiTarget.java new file mode 100644 index 0000000..5d61dce --- /dev/null +++ b/art-fieldwatch-phase1/test/app/src/main/java/com/example/artfieldwatch/PrimitiveAbiTarget.java @@ -0,0 +1,35 @@ +package com.example.artfieldwatch; + +/** Wide/narrow primitive transport verification, separate from ART injection. */ +public final class PrimitiveAbiTarget { + private long wide; + private static float f32; + private double f64; + + public static int exercise() { + PrimitiveAbiTarget target = new PrimitiveAbiTarget(); + final long expected = -0x102030405060708L; + target.wide = expected; + FieldEventSink.recordFieldLong(0,5,21,2,FieldEventSink.WRITE,expected); + long observed = target.wide; + FieldEventSink.recordFieldLong(0,5,21,4,FieldEventSink.READ,observed); + f32 = -0.0f; + FieldEventSink.recordFieldFloat(0,5,22,6,FieldEventSink.WRITE,-0.0f); + float f = f32; + FieldEventSink.recordFieldFloat(0,5,22,8,FieldEventSink.READ,f); + target.f64 = -0.0d; + FieldEventSink.recordFieldDouble(0,5,23,10,FieldEventSink.WRITE,-0.0d); + double d = target.f64; + FieldEventSink.recordFieldDouble(0,5,23,12,FieldEventSink.READ,d); + + FieldEventSink.recordFieldNarrow(0,6,24,14,FieldEventSink.READ,1,1); + FieldEventSink.recordFieldNarrow(0,6,25,16,FieldEventSink.WRITE,2,-128); + FieldEventSink.recordFieldNarrow(0,6,26,18,FieldEventSink.READ,3,0xd7ff); + FieldEventSink.recordFieldNarrow(0,6,27,20,FieldEventSink.WRITE,4,-32768); + if (observed!=expected || Float.floatToRawIntBits(f)!=0x80000000 || + Double.doubleToRawLongBits(d)!=Long.MIN_VALUE || + FieldEventSink.fieldMetaCount()!=14) + throw new AssertionError("Primitive field-event JNI transport failed"); + return 61; + } +} diff --git a/art-fieldwatch-phase1/test/build.gradle b/art-fieldwatch-phase1/test/build.gradle new file mode 100644 index 0000000..e5ce0d9 --- /dev/null +++ b/art-fieldwatch-phase1/test/build.gradle @@ -0,0 +1 @@ +plugins { id 'com.android.application' version '8.7.3' apply false } diff --git a/art-fieldwatch-phase1/test/settings.gradle b/art-fieldwatch-phase1/test/settings.gradle new file mode 100644 index 0000000..45777ef --- /dev/null +++ b/art-fieldwatch-phase1/test/settings.gradle @@ -0,0 +1,9 @@ +pluginManagement { + repositories { google(); mavenCentral(); gradlePluginPortal() } +} +dependencyResolutionManagement { + repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS) + repositories { google(); mavenCentral() } +} +rootProject.name = 'ArtFieldwatchSmoke' +include ':app' diff --git a/docs/art-fieldwatch/ir-event-probe-design.md b/docs/art-fieldwatch/ir-event-probe-design.md new file mode 100644 index 0000000..64414d8 --- /dev/null +++ b/docs/art-fieldwatch/ir-event-probe-design.md @@ -0,0 +1,182 @@ +# Design: compiler-IR logical Java field events + +**Status:** proposal for research prototype; **not implemented**. No IR mutation +or runtime callback is shipped in phase 1. Retain the verified read-only probe. +**Initial target:** Android API 33 x86_64, ART compiler ELF Build ID +`0b33b00205f7151b4fce7490c3715d99`; runtime `libart.so` Build ID +`c8b6a2df9893030c07b3b96dc24a7d30`. Fail closed for other binaries. + +## Evidence and problem definition + +CI [44725544918](https://github.com/mnalmahmud/frida-scripts/actions/runs/44725544918) +passed API 33 debug/release and API 34 debug. The release test checked +**two** optimized `HInstanceFieldGet*` nodes visited by ART, replaced +and removed inside LSE, and absent from the same compilation's backend +location assignment/code emission; at least one baseline JIT compilation +did emit a field-get. The preceding run +[44722172785](https://github.com/mnalmahmud/frida-scripts/actions/runs/44722172785) +also verified that `FieldIRTarget.testViaIdentity(int)` contains both +`iput` and `iget` in **release** DEX. Unlike `test(int)`, its read +was not already eliminated by D8. + +**Two monitoring semantics, deliberately distinct:** + +* **Logical DEX event**: one event on each *successful execution* of + an instrumented DEX `iget/iput/sget/sput` instruction (not each + compiler visitor invocation or emitted machine load). +* **Physical event**: one event for each actual machine memory access + in compiled code. Optimization can legitimately remove this access, + so it cannot substitute for logical monitoring. + +This document designs *logical* events. It cannot reconstruct +source-level operations eliminated by D8 before DEX exists. + +## Candidate mechanism: a real side-effecting ART IR operation + +Work with a **source-matched native C++ compiler shim**, not JS-written +C++ object memory. The current Frida JS remains a read-only observer and +gates the shim on build ID, architecture and verified graph invariants. +Prefer an existing `HInvokeStaticOrDirect` to a dedicated, known +event sink, so the stock ART backend, stack maps and call lowering are +reused. An arbitrary C native function pointer is **not** a valid +`HInvokeStaticOrDirect` destination. It needs a real resolved +`ArtMethod*`, an acceptable dispatch method, DexCache / loader +resolution, correct invoke arguments and any required class-init +state. The source-matched shim must validate all of these; if not +possible, stop instead of constructing an invalid call. + +Prototype on the test APK only: predefine a minimal nonthrowing-in- +practice primitive event sink, e.g. `FieldEventSink.recordInt(siteId, +value)`, initialize it before warmup, make its observable side effect +undeniable and prohibit inlining if the ART variant supports a +documented, verified mechanism. Its goal is an event count/value +oracle, **not** production safety or a stable general application API. + +Proposed IR transformation, after valid SSA construction and **before +LSE**. Start with resolved, nonvolatile `HInstanceFieldGet/Set` of +type int: + +```text +DEX: iput v, obj, field DEX: iget dest, obj, field + | | +IR: HNullCheck(obj) HNullCheck(obj) + HInstanceFieldSet(obj,v) HInstanceFieldGet(obj) -> value + HInvoke sink(site,v) HInvoke sink(site,value) + | | + ordinary next IR ordinary next IR +``` + +**Place sink after the field operation** so it runs only after a +successful access, including any required null and resolution checks. +Connect its value operand to the actual SSA producer: `Get` result +for reads, `Set` value input for writes. If LSE replaces the +`Get` value with a substitute, the sink's SSA use should be +retargeted to that substitute; the event still uses the logically +observed value. The sink must itself be a visible, non-removable +side effect, not a pure helper that DCE/GVN drops. + +Do not assume this will leave LSE behavior unchanged: conservative +invoke side effects can inhibit load/store elimination and code motion. +**Compiled execution must be preserved; identical optimization output +is not a goal for this first prototype.** The stronger claim that an +optimized-away load still produces a synthetic logical event must be +demonstrated experimentally, not asserted from IR construction alone. + +## Insertion, order and provenance contracts + +1. **Version gate:** exact ART build IDs, 64-bit ABI, verified vtable + and graph layout, successful source-matched shim initialization. + Missing/unknown layout => survey-only, no mutation. +2. **Insertion window:** after instruction building/SSA validity and + before the first optimization that can eliminate the field node. + API 33 `RunOptimizations(HGraph*,...)` is a verified boundary; + test actual pass order and whether inlining introduces additional + field nodes *after* injection. Instrument cloned/inlined copies + exactly once if an inliner later imports them. +3. **Control flow:** sink must be on the same successful execution + path as the original field instruction. It must not execute on a + path that throws `NullPointerException`, field-resolution/access + errors, or class initialization failures. Compare CFG, dominance, + exceptional edges, and live SSA inputs before and after injection. +4. **Compiler representation:** verify method dispatch, argument + widths/types, environments, graph uses, graph allocator lifetime, + safepoint/stack-map requirements and side-effect flags. Run ART's + graph checker and post-codegen verification, not just a non-crashing + Android warmup. +5. **Field identity:** `(DexFile identity, declaring loader, field + index, access opcode, dex PC, inlined frame)`; the raw field index + alone is not globally stable. Preserve the resolved `ArtField` + metadata only using a supported lifetime-safe mechanism. +6. **Java semantics:** read event after a successful get and write + event after a successful set; do **not** accidentally duplicate + null checks or materialize a load purely to observe its value. + For initially optimized-out reads, use the compiler's *substitute* + SSA value if it is proven semantically equivalent. +7. **Volatile, static, unresolved, reference and wide/FP fields are + out of scope for the first mutation prototype.** Volatiles need + exact acquire/release ordering; statics need clinit ordering; + unresolved accesses can throw resolution/access exceptions. + A raw `mirror::Object*` must never be retained across GC. Expand + types only after a verified root/handle strategy. + +## Runtime sink and event transport + +Prototype first with `int` values only. Define an immutable event +schema (version, compilation site ID, thread sequence, dex source +identity + PC, kind, value bit pattern, dropped-count). Do not emit +raw object pointers as durable object identities. The eventual +production sink should be **bounded, allocation-free and +non-blocking on hot paths**, with explicit overflow reporting and +reentrancy suppression, but such a sink still needs ABI/GC/safepoint +proof. A Java-method sink is suitable only for a controlled first +count/value experiment; it may allocate, throw, trigger class +initialization, or perturb optimization if implemented incorrectly. + +When providing callbacks to `frida-java-bridge`, keep the Frida +consumer outside the compiler's internal locks and JIT worker. +The compiler injects a runtime site; it does not call user JavaScript +while constructing or optimizing the graph. + +## Coverage limitations (explicit) + +* Instruments **future matching JIT compilations only** after shim + installation. Existing AOT/JIT code is **not** retroactively covered. + Forcing deoptimization, Stalker and watchpoints are not part of this + design; completeness of preexisting compiled code is consequently + not promised. +* API 34's field IR boundary is not established, so **no API 34 + mutation**. API 21-37 and ARM/ARM64/x86 adapters require separate + evidence, codegen checks and exact ABI validation. +* Inlining, quickened DEX, constructor special cases, exception paths + and compiler-generated field nodes need their own provenance and + duplication checks. A field instruction is not always a one-to-one + representation of a Java source expression. + +## Prototype acceptance gates + +| Stage | Required CI evidence | Rollback condition | +|---|---|---| +| P0: immutable baseline | Existing `44725544918` debug/release lifecycle suite stays green | Baseline regression | +| P1: shadow shim | Native shim loads and enumerates *only* expected int field nodes; ART graph remains byte-for-byte unmodified | Unknown ABI, wrong ownership, graph-check failure | +| P2: one inserted event | The API 33 **release** `testViaIdentity` DEX still has iput+iget; one chosen compilation compiles; event counts/values match executed field instructions | Crash, changed return value, missing event or false event on null | +| P3: optimized code | Baseline & optimizing tiers pass; event operation appears at backend/code emission even if corresponding field node is replaced/removed | Event dropped, duplicated, reordered or exception behavior altered | +| P4: inlining and exceptions | Nested/inlined helper path and null receiver tests have correct site provenance and exactly-once behavior | Duplicate or false events | +| P5: types/versions | Long/FP, static, volatile, reference/GC, API34 and other ABIs added individually after safety tests | Unsupported/unstable ABI | + +**Immediate next action:** implement P1 **only**, a passive +version-checked native companion that inspects the same live graph +without modifying it. Then prototype P2 with a single int field +and compare its events with the Java fixture oracle. Keep all +injection behind an explicit opt-in environment flag, disabled by +default. + +## AOSP reference points + +- [ART instruction builder](https://android.googlesource.com/platform/art/+/master/compiler/optimizing/instruction_builder.cc): resolved and unresolved get/set, null-check ordering. +- [ART IR nodes](https://android.googlesource.com/platform/art/+/refs/heads/main/compiler/optimizing/nodes.h): HInstanceFieldGet/Set, HInvoke and side-effect/environment semantics. +- [ART load/store elimination](https://android.googlesource.com/platform/art/+/master/compiler/optimizing/load_store_elimination.cc): ReplaceWith, RemoveInstruction, debuggable graph restriction. +- [ART x86_64 code generator](https://android.googlesource.com/platform/art/+/refs/heads/main/compiler/optimizing/code_generator_x86_64.cc): backend lowering of invokes and field nodes. + +These are **structural** references; all on-device object layouts +and method signatures must be matched to the exact CI binary before +native compiler mutation. diff --git a/docs/art-fieldwatch/p3-injection-abi-gates.md b/docs/art-fieldwatch/p3-injection-abi-gates.md new file mode 100644 index 0000000..cc6100a --- /dev/null +++ b/docs/art-fieldwatch/p3-injection-abi-gates.md @@ -0,0 +1,258 @@ +# P3 research: first ART-inserted integer field event (API 33 x86_64) + +**Status (2026-11-21): implementation gate, not a working IR injector.** +Active branch: `ci/art-fieldwatch-phase1`; baseline head `2fe8fca967e8`. +Do not report arbitrary-field coverage from the explicit Java call-site P2 test. +The first mutation remains **off by default**, exact-ELF-gated, and APK-fixture-only. + +## What is already established + +- CI [44843045544](https://github.com/mnalmahmud/frida-scripts/actions/runs/44843045544) + passed API 33 debug, API 33 release and API 34 debug. The API 33 native + recorder delivered 256 real integer runtime events (128 read/write pairs), + with the expected values and ordering and zero dropped events. + **Those invocations come from explicit Java source calls** to + `FieldEventSink.recordInt` in `FieldIRTarget.watchedOn`, not compiler insertion. +- The API 33 release run also observed a successfully optimized compilation + where ART's LSE replaced an `HInstanceFieldGet` with an `HPhi` and then + removed the get. The removed node reached neither backend locations nor + emission. This is the live-value/optimization regression case for P3. +- `native/passive-shadow.c` has a fail-closed x86_64 API 33 gate for the + *observed emulator binary*, runtime GNU Build ID + `c8b6a2df9893030c07b3b96dc24a7d30` and compiler GNU Build ID + `0b33b00205f7151b4fce7490c3715d99`. + It only validates graph/node pointers and never mutates ART objects. + +## AOSP constraints that change the implementation + +1. **Use ART's IR insertion machinery, not a raw linked-list edit.** + AOSP `HBasicBlock::InsertInstructionAfter` validates the cursor/block, + assigns the new instruction's graph ID, sets its block and updates input + user lists. Even a correctly placed pointer without this accounting is + not a valid SSA node. Its actual callable ABI/export on our emulator is + *not yet established*. +2. **A call node is more than an address to a native C function.** + `HInvokeStaticOrDirect` construction includes the number/types of + arguments, return type, DEX PC and method index, an `ArtMethod*` and + dispatch metadata, invocation kind, target `MethodReference`, and + class-initialization requirements. Some dispatch modes add implicit + inputs such as the current method or class-init check. The compiler's + Java invocation lowering cannot be fed `artwatch_events_snapshot` or + `recordInt`'s native function pointer as if it were an `ArtMethod*`. +3. **An invoke may trigger GC or throw.** Validate the attached + `HEnvironment`, inlined parent chain, safepoints, register liveness, + stack maps, method resolution and class initialization. Loading an + unresolved helper inside the compiler worker is not a valid shortcut. + Pre-initialize the fixture's `FieldEventSink` before warmup. +4. **The helper method reference must be legal for the caller.** + For the *fixture-only* canary, the app's DEX already references + `FieldEventSink.recordInt(int,int,int)` from `watchedOn`; its + resolved method, DEX method ID, and prototype can be checked against + the existing ART-created invoke as an oracle. For arbitrary third-party + DEX files the helper method ID need not exist at all. A direct-address + dispatch mode does **not** by itself prove that the rest of + `HInvokeStaticOrDirect` accepts a nonexistent DEX method index. + Generalizing beyond the canary is a separate design gate. +5. **Logical rather than physical semantics.** Insert the side-effecting + callback after successful `HInstanceFieldSet` / `HInstanceFieldGet`, + not at backend emission. A get's event argument must use the *get's SSA + result*, and a set's argument the actual value stored. If LSE replaces + the get with `HPhi`, the event use must be updated to the proven + substitute through normal ART SSA maintenance. An optimized-away field + load can still have a logical DEX read event. The callback must not run + on a null receiver that throws before completing the field access. + +Source anchors (structural evidence, **not** confirmation of the exact +on-device ABI): +- [AOSP Android 13 optimizing source tree](https://android.googlesource.com/platform/art/+/refs/heads/android13-d4-s1-release/compiler/optimizing/) +- [AOSP nodes.cc insertion and user-list maintenance](https://android.googlesource.com/platform/art/+/refs/heads/android13-d4-s1-release/compiler/optimizing/nodes.cc) +- [AOSP nodes.h invoke metadata](https://android.googlesource.com/platform/art/+/refs/heads/android13-d4-s1-release/compiler/optimizing/nodes.h) +- [AOSP instruction builder](https://android.googlesource.com/platform/art/+/refs/heads/android13-d4-s1-release/compiler/optimizing/instruction_builder.cc) +- [AOSP graph checker](https://android.googlesource.com/platform/art/+/refs/heads/android13-d4-s1-release/compiler/optimizing/graph_checker.cc) + +## Smallest acceptable P3 mutation + +**Scope:** one *resolved*, nonvolatile `int` instance field belonging to +the controlled API 33 release fixture. Do not start with every Java class. +No object references, volatiles, static fields, unresolved accesses, other +architectures, or unverified ART builds. Keep the read-only P1 observers +unchanged and available as a rollback baseline. + +- **Identify a legal insertion point.** The current verified + `RunOptimizations(HGraph*, ...)` entry is a graph pointer boundary, but + alone does not prove final post-inlining pass order. Determine the actual + API 33 inlining/LSE order; prefer a point after relevant inlining and + before first field elimination. Baseline `CompilationKind=1` may not + visit this path and needs a separate verified insertion point. +- **Build a source-matched native C++ helper.** Compile against the + matching ART C++ structures, not only NDK/JNI headers or guessed offsets. + Load only after both mapped ART ELF build IDs match. Validate the graph, + allocator, field node, owner block and target invoke ABI before *any* + change. On mismatch, return an explicit failure reason; do not partially + rewrite the graph. Do not call Frida JavaScript or JNI from the JIT + compiler worker. +- **Use the preexisting canary helper method.** The APK fixture already + contains a correctly resolved static native invoke. Verify its method + reference, dispatch, signature, class-init state and environment from + an ART-generated invoke before constructing a new one. This is a + narrowly controlled way to close the call-lowering question; it is + not a general arbitrary-Dex solution. +- **Construct and insert through ART APIs.** Allocate in the graph arena; + set the event's site/kind constants and typed int SSA argument, attach a + correct environment, then use `InsertInstructionAfter`. Validate + argument use lists and dominance *immediately*. Do not retain live + `HInstruction*` or graph pointers after compilation. +- **Validate compiler output.** Run graph-checker-style invariants and + require successful code generation, not just a non-crashing app run. + Log an unambiguous `artwatch-injection` record with + `{attempted, inserted, rejectedReason, compilationKind, site}`. + Never confuse a compile-time IR observation with execution of the call. + +## Minimum acceptance and negative controls + +1. **Off by default:** existing passing P1/P2 CI remains unchanged; the + canary mutation is enabled only through an explicit workflow/agent flag. + Unknown ELF IDs, unsupported tier, missing helper metadata, or missing + graph invariants must return `inserted=false` and leave code untouched. +2. **Positive control:** remove *explicit* `recordInt` calls from a + distinct canary method while retaining the current explicit-call oracle. + Verify that this raw canary emits zero events with injection disabled, + then exactly one write and one read per successful invocation when P3 + injection is enabled. Keep the original `watchedOn` test intact. +3. **Exception control:** a null-receiver write must throw before + recording any event. Check that the method's return value is unchanged. +4. **Tier and optimization controls:** require evidence in both a + baseline-emitted get and an optimized compilation that can replace + get with `HPhi`. A side-effecting invoke may itself inhibit LSE; if + so record that fact instead of claiming optimized-get replacement. +5. **Sink behavior:** confirm exact value bits, order, count and drops + through the existing native snapshot. For later generalization, + test multiple threads, capacity exhaustion and reentrancy separately. +6. **Coverage claim:** future JIT compilations of selected DEX methods + only. Already compiled AOT/JIT, interpreted, inlined before attachment, + and D8-eliminated source operations remain outside this milestone. + +## Specific implementation blocker to resolve next + +Find a **real source/binary-compatible way to construct and lower a +`HInvokeStaticOrDirect` targeting the fixture sink**. The existing +Frida JavaScript observer and NDK passive shim do not contain the ART +C++ header/layout, environment construction, allocator plumbing, or +method-resolution contract required for this. Hook attachment and a +matching HGraph pointer are necessary but *not sufficient*. +Until those prerequisites are demonstrated, keep mutation disabled. + + +## 2026-11-21: same-graph clone proof implementation (source unit only) + +The device's API33 libart-compiler.so exported +`HBasicBlock::InsertInstructionAfter(HInstruction*,HInstruction*)` and +`HBasicBlock::InsertInstructionBefore(HInstruction*,HInstruction*)`, along +with `HInvokeStaticOrDirect::Accept`. CI run 44896426059 confirmed actual +invoke visitor callbacks on real compilations and an existing 256-event P2 +oracle. The newer invoke backend assertions remain a separate CI gate. + +Experimental C++ file: +[`native/p3-clone-injector-art.cc`](../../art-fieldwatch-phase1/native/p3-clone-injector-art.cc). + +This file contains **actual HGraph mutation code**, but is deliberately +**not built or loaded by the current NDK CI**. It uses source-level ART +interfaces, so it must be compiled in the matching ART source environment, +with the exact ELF Build IDs validated before integration. Its entrypoint +requires already validated same-graph `HInstanceFieldGet`, a real +`HInvokeStaticOrDirect` template, and its resolved sink `ArtMethod*`. + +The new `p3TemplateCarrierOn()` adds +`recordInt(0,0,observed)` in the same Java method as a real `iput` and +`iget`. The native sink excludes this reserved sentinel. The first +injected clone will use site 9002, kind 1, and the original field-get +SSA output; only the cloned call can emit a read event. + +**Important gates:** adjacency, type, source invoke signature, resolved +method identity, class-init dispatch, presence of a valid source environment, +and graph ownership must be checked before mutation. The helper refuses +nonadjacent nodes, volatiles, and cross-block calls. It clones the invoke, +replaces its first two SSA operands with constants, inserts immediately before +the existing call using ART APIs, then copies the original call environment. +It does not yet identify template and field pointers automatically, install a +compiler hook, or cover eliminated accesses. + +AOSP-compatible research reference for this clone design: +[Android 13 era AOSPA topaz nodes.h](https://github.com/AOSPA/android_art/blob/topaz/compiler/optimizing/nodes.h), +[nodes.cc](https://github.com/AOSPA/android_art/blob/topaz/compiler/optimizing/nodes.cc). +These mirror sources establish the algorithmic contract but **do not prove** +a binary ABI match with the emulator. Exact matching ART headers and a +build-tested injector are still required before enabling it. + +Before claiming P3 success require: fixture DEX retains the template; the +actual optimized graph retains its adjacent field get and sink invoke; the +mutator is built and loaded under the exact build-ID gate; the compiler +completes with valid SSA and environments; an injected invocation yields +128 events with the exact expected field-read values; zero-event controls +remain unchanged; and the P2 256-event oracle still passes. + +## P3 get/invoke adjacency check (2026-11-21) + +A build-ID-gated **read-only** native function now checks the Android 13 +`HInstruction` link layout for actual, vtable-validated +`HInstanceFieldGet` and `HInvokeStaticOrDirect` objects seen during the +same `HGraphVisitor::VisitBasicBlock` visit. It compares reciprocal +`previous_`/`next_` pointers and exact `HBasicBlock*` identity. Results +are reported as `adjacencyProbes`, `adjacencyMatches`, +`adjacencyRejected`, and bounded pointer samples per compilation. +No ART memory is modified. A passing API33 JIT must not have negative +identity checks; actual adjacency has to be observed before deploying the +`CloneUniqueIntReadInGraph` logic. A zero adjacency count is meaningful +and must not be relabeled as successful injection. + + +## 2026-11-22: baseline field-target scan and DEX PC identity + +The passed API 33 [CI run 44939983872](https://github.com/mnalmahmud/frida-scripts/actions/runs/44939983872) +demonstrated that the earlier **zero adjacency probes** were caused by the +`RunOptimizations()`-only visitor gate. After observing baseline compilation, +the debug/release logs showed respectively: + +| Signal | API 33 debug | API 33 release | +| --- | ---: | ---: | +| Invoke predecessor attempts | 64 | 301 | +| Field-target attempts | 28 | 279 | +| Immediate HInstanceFieldGet predecessor matches | 6 | 6 | +| Field gets within eight predecessors | 2 | 2 | +| Rejected or broken pointer identities | 0 | 0 | + +These represent observer *visits*, not deduplicated nodes or proof that the +candidate invoke is `FieldEventSink.recordInt()`. Repeated visits to the +same invoke can account for several matches. They establish only that +some live get/invoke pairs share a block and linked-list adjacency. + +The next strict **read-only** predicate has been committed: + +- Native `artwatch_shadow_instruction_dex_pc` reads `dex_pc_` at the + Android 13 x86_64 `HInstruction` source-layout offset, only after exact + runtime/compiler Build-ID verification and vtable validation. +- The JS invoke-predecessor walker compares the live field-get DEX PC to + `HInstructionBuilder::BuildInstanceFieldAccess` events from the same + `ArtMethod*` (including the DEX field index associated with the observed + get PC). +- CI requires a nonzero matched count and checks accounting of matched, + unmatched, and unavailable candidates. No graph memory is modified. + +**Still necessary before enabling `CloneUniqueIntReadInGraph`:** + +1. Verify a *unique* template in the same live graph, with exact sink + `MethodReference` (DEX-file pointer and method index) and expected + resolved `ArtMethod*`. Invoke adjacency and field-get DEX PC alone + do not establish this identity. +2. Prove all three actual invoke operands are int32 and carry + `(0,0,field_get)`; verify the `HEnvironment`, class-init state, + and dispatch metadata. Invoke::Accept does not expose this tuple. +3. Build the ART C++ mutator against the *exact* matching ART source + revision and test in the compiler context. The existing CI does not + compile `p3-clone-injector-art.cc` and cannot claim successful IR + insertion or new runtime read events. +4. Do not interpret repeated visitor observations as distinct field + accesses or instrumentation coverage. + +The new DEX-PC assertions are experimental; a green result is necessary, +not sufficient, for graph mutation.