From fba3f43884ecbd8e408f47551cc43627ee39b5b4 Mon Sep 17 00:00:00 2001 From: Muhtasham Nawr al-Mahmud <72372229+mnalmahmud@users.noreply.github.com> Date: Thu, 19 Nov 2026 17:41:55 +0600 Subject: [PATCH 001/129] ci: add ART fieldwatch JIT-boundary emulator smoke harness --- .github/workflows/art-fieldwatch-phase1.yml | 96 +++++++++++++++++++ art-fieldwatch-phase1/README.md | 22 +++++ .../ci/run-emulator-smoke.sh | 22 +++++ art-fieldwatch-phase1/ci/smoke_test.py | 64 +++++++++++++ art-fieldwatch-phase1/jit-boundary-probe.js | 96 +++++++++++++++++++ art-fieldwatch-phase1/test/app/build.gradle | 14 +++ .../test/app/src/main/AndroidManifest.xml | 10 ++ .../artfieldwatch/FieldWatchTarget.java | 25 +++++ .../example/artfieldwatch/MainActivity.java | 25 +++++ art-fieldwatch-phase1/test/build.gradle | 1 + art-fieldwatch-phase1/test/settings.gradle | 9 ++ 11 files changed, 384 insertions(+) create mode 100644 .github/workflows/art-fieldwatch-phase1.yml create mode 100644 art-fieldwatch-phase1/README.md create mode 100755 art-fieldwatch-phase1/ci/run-emulator-smoke.sh create mode 100644 art-fieldwatch-phase1/ci/smoke_test.py create mode 100644 art-fieldwatch-phase1/jit-boundary-probe.js create mode 100644 art-fieldwatch-phase1/test/app/build.gradle create mode 100644 art-fieldwatch-phase1/test/app/src/main/AndroidManifest.xml create mode 100644 art-fieldwatch-phase1/test/app/src/main/java/com/example/artfieldwatch/FieldWatchTarget.java create mode 100644 art-fieldwatch-phase1/test/app/src/main/java/com/example/artfieldwatch/MainActivity.java create mode 100644 art-fieldwatch-phase1/test/build.gradle create mode 100644 art-fieldwatch-phase1/test/settings.gradle diff --git a/.github/workflows/art-fieldwatch-phase1.yml b/.github/workflows/art-fieldwatch-phase1.yml new file mode 100644 index 0000000..a6d4b29 --- /dev/null +++ b/.github/workflows/art-fieldwatch-phase1.yml @@ -0,0 +1,96 @@ +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 +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: bash -n art-fieldwatch-phase1/ci/run-emulator-smoke.sh + android: + runs-on: ubuntu-latest + timeout-minutes: 35 + strategy: + fail-fast: false + matrix: + api: [33, 34] + env: + FRIDA_VERSION: '17.27.1' + ARTWATCH_LOG_DIR: /tmp/artwatch-logs + 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@v3 + - run: sdkmanager '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: ${{ matrix.api }} + target: default + arch: x86_64 + profile: pixel_2 + 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 + path: /tmp/artwatch-logs/ + if-no-files-found: ignore + android-arm64: + if: github.event_name == 'workflow_dispatch' && inputs.arm64 + runs-on: macos-15-arm64 + 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@v3 + - run: sdkmanager '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..8f36352 --- /dev/null +++ b/art-fieldwatch-phase1/README.md @@ -0,0 +1,22 @@ +# ART Fieldwatch Phase 1 CI + +This is a **read-only diagnostic** for JIT symbol and compilation-path discovery. +It is NOT yet a Java field-read/write interceptor. + +The workflow uses Android API 33 and 34 x86_64 emulators for spawn, +Frida attachment, ART module discovery and APK warmup. Both x86_64 tests +operate in passive inventory mode; they do not prove the ARM64 hook works. + +The optional workflow_dispatch arm64 job targets Android 14 API 34 +and **strictly** checks for a JIT hook and compilation. Failing here can +mean missing symbols, unexpected ART ABI, no compilations, or unavailable +emulator images. Preserve CI logs as research evidence, not as proof of field +monitoring coverage. + +The architecture goal is API 21-37. There is no compatibility guarantee +without running the field-watch suite on each profile. + +Frida runtime and server version: 17.27.1 (pinned). + +Run from GitHub Actions > ART Fieldwatch phase 1 > Run workflow, +optionally arm64=true. Check the log artifacts for diagnostics. diff --git a/art-fieldwatch-phase1/ci/run-emulator-smoke.sh b/art-fieldwatch-phase1/ci/run-emulator-smoke.sh new file mode 100755 index 0000000..12ae3cf --- /dev/null +++ b/art-fieldwatch-phase1/ci/run-emulator-smoke.sh @@ -0,0 +1,22 @@ +#!/usr/bin/env bash +set -euo pipefail +mkdir -p "${ARTWATCH_LOG_DIR:-/tmp/artwatch-logs}" +adb root +adb wait-for-device +adb install -r art-fieldwatch-phase1/test/app/build/outputs/apk/debug/app-debug.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 &)' +sleep 3 +python3 art-fieldwatch-phase1/ci/smoke_test.py diff --git a/art-fieldwatch-phase1/ci/smoke_test.py b/art-fieldwatch-phase1/ci/smoke_test.py new file mode 100644 index 0000000..37ee29d --- /dev/null +++ b/art-fieldwatch-phase1/ci/smoke_test.py @@ -0,0 +1,64 @@ +#!/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 + +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) + pid = device.spawn(['com.example.artfieldwatch']) + record('host','spawned-pid='+str(pid)) + session = device.attach(pid) + try: + script = session.create_script((BASE/'jit-boundary-probe.js').read_text()) + script.on('message',on_message) + script.load() + device.resume(pid) + time.sleep(20) + 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)) + if 'WARMUP_FAILED' in logs.stdout or 'WARMUP_DONE' not in logs.stdout: + raise AssertionError('APK fixture warmup failed or timed out') + if os.environ.get('ARTWATCH_REQUIRE_JIT') == '1': + if 'Attached compilation observer' not in text: + raise AssertionError('No native JIT hook installed') + if 'JIT success' not in text: + raise AssertionError('No JIT compile observed') + 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..7f3cfb9 --- /dev/null +++ b/art-fieldwatch-phase1/jit-boundary-probe.js @@ -0,0 +1,96 @@ +'use strict'; +/* Read-only JIT-boundary discovery. Does NOT intercept field reads/writes. */ +const LIMIT = 40; +const counts = {attempts: 0, successes: 0, failures: 0}; +const hooks = []; +const artNames = new Set(['libart.so','libartd.so','libart-compiler.so','libartd-compiler.so']); +const log = x => console.log('[art-fieldwatch/phase1] ' + x); +function sdkLevel() { + try { + const p = Process.getModuleByName('libc.so').findExportByName('__system_property_get'); + if (p === null) return '?'; + const fn = new NativeFunction(p,'int',['pointer','pointer']); + const out = Memory.alloc(128); + return fn(Memory.allocUtf8String('ro.build.version.sdk'),out) > 0 + ? out.readUtf8String() : '?'; + } catch (_) { return '?'; } +} +function kind(n) { + if (/\bJit::CompileMethodInternal\(/.test(n)) return 'jit_dispatch_internal'; + if (/\bJit::CompileMethod\(/.test(n)) return 'jit_dispatch'; + if (/\bOptimizingCompiler::JitCompile\(/.test(n)) return 'optimizing_jit'; + if (/\bOptimizingCompiler::TryCompile\(/.test(n)) return 'optimizing_preopt_candidate'; + if (/\bHGraphBuilder::BuildGraph\(/.test(n)) return 'graph_builder'; + if (/\bJitCodeCache::Commit\(/.test(n)) return 'code_publication'; + if (n === 'jit_load') return 'jit_load'; + return null; +} +function discover(m) { + const result = []; + const seen = new Set(); + const add = (name,address,source) => { + const type = kind(name); + if (type === null) return; + const key = type + ':' + address; + if (seen.has(key)) return; + seen.add(key); + result.push({type,name,address,source,module:m.name}); + }; + const exp = m.findExportByName('jit_load'); + if (exp !== null) add('jit_load',exp,'export'); + try { + for (const s of m.enumerateSymbols()) { + if (s.type === 'function' || s.type === undefined) + add(s.name,s.address,'symbol'); + } + } catch (e) { log('Cannot enumerate symbols in ' + m.name + ': ' + e.message); } + return result; +} +function attachDispatch(site) { + hooks.push(Interceptor.attach(site.address, { + onEnter(args) { + this.method = args[1]; + this.kind = args[3].toInt32(); + counts.attempts++; + this.print = counts.attempts <= LIMIT; + }, + onLeave(ret) { + const ok = ret.toInt32() !== 0; + counts[ok ? 'successes' : 'failures']++; + if (this.print) log('JIT ' + (ok?'success':'failed') + + ' method=' + this.method + ' kind=' + this.kind); + } + })); + log('Attached compilation observer at ' + site.address + ' (' + site.name + ')'); +} +function main() { + const api = Number(sdkLevel()); + log('pid='+Process.id+' arch='+Process.arch+' pointerSize='+Process.pointerSize+' api='+api); + const modules = Process.enumerateModules().filter(m => artNames.has(m.name)); + if (modules.length === 0) { log('No ART library found'); return; } + for (const m of modules) log('module='+m.name+' base='+m.base+' path='+m.path); + const sites = modules.flatMap(discover); + for (const s of sites) log('candidate='+s.type+' at='+s.address+ + ' module='+s.module+' source='+s.source+' symbol='+s.name); + if (Process.arch !== 'arm64' || (api !== 33 && api !== 34)) { + log('Inventory only: JIT callback requires API 33/34 arm64'); + return; + } + const pick = t => sites.find(s => s.type === t); + const chosen = api === 34 + ? (pick('jit_dispatch_internal') || pick('jit_dispatch')) + : (pick('jit_dispatch') || pick('jit_dispatch_internal')); + try { + if (chosen) attachDispatch(chosen); + else log('No ABI-checked C++ JIT dispatch symbol discovered'); + } catch(e) { log('Hook installation failed: '+e.stack); } + log('This probe does NOT capture field accesses or modify compiler IR'); + let before = 0; + setInterval(() => { + if (counts.attempts !== before) { + before = counts.attempts; + log('summary '+JSON.stringify(counts)); + } + }, 5000); +} +main(); diff --git a/art-fieldwatch-phase1/test/app/build.gradle b/art-fieldwatch-phase1/test/app/build.gradle new file mode 100644 index 0000000..e9e2183 --- /dev/null +++ b/art-fieldwatch-phase1/test/app/build.gradle @@ -0,0 +1,14 @@ +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' + } +} 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/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/MainActivity.java b/art-fieldwatch-phase1/test/app/src/main/java/com/example/artfieldwatch/MainActivity.java new file mode 100644 index 0000000..73b6c2d --- /dev/null +++ b/art-fieldwatch-phase1/test/app/src/main/java/com/example/artfieldwatch/MainActivity.java @@ -0,0 +1,25 @@ +package com.example.artfieldwatch; +import android.app.Activity; +import android.os.Bundle; +import android.util.Log; +import android.widget.TextView; + +public final class MainActivity extends Activity { + @Override + protected void onCreate(Bundle state) { + super.onCreate(state); + TextView label = new TextView(this); + label.setText("ART Fieldwatch: field access warmup"); + setContentView(label); + new Thread(() -> { + long accumulator = 0; + try { + for (int i = 0; i < 40; i++) + accumulator += FieldWatchTarget.exercise(100000); + 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/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' From bc1ff4183c1fcef8ab42fbd9d3682fc06f4ef20f Mon Sep 17 00:00:00 2001 From: Muhtasham Nawr al-Mahmud <72372229+mnalmahmud@users.noreply.github.com> Date: Thu, 19 Nov 2026 17:43:06 +0600 Subject: [PATCH 002/129] ci: avoid setup-android legacy tools package failure on hosted runners --- .github/workflows/art-fieldwatch-phase1.yml | 2 -- 1 file changed, 2 deletions(-) diff --git a/.github/workflows/art-fieldwatch-phase1.yml b/.github/workflows/art-fieldwatch-phase1.yml index a6d4b29..53b00ae 100644 --- a/.github/workflows/art-fieldwatch-phase1.yml +++ b/.github/workflows/art-fieldwatch-phase1.yml @@ -37,7 +37,6 @@ jobs: - uses: actions/setup-python@v5 with: python-version: '3.12' - - uses: android-actions/setup-android@v3 - run: sdkmanager 'platforms;android-35' 'build-tools;35.0.0' - uses: gradle/actions/setup-gradle@v4 with: @@ -74,7 +73,6 @@ jobs: - uses: actions/setup-python@v5 with: python-version: '3.12' - - uses: android-actions/setup-android@v3 - run: sdkmanager 'platforms;android-35' 'build-tools;35.0.0' - uses: gradle/actions/setup-gradle@v4 with: From 134a2706f205fa74996a7d56920798c0b4d33780 Mon Sep 17 00:00:00 2001 From: Muhtasham Nawr al-Mahmud <72372229+mnalmahmud@users.noreply.github.com> Date: Thu, 19 Nov 2026 17:43:57 +0600 Subject: [PATCH 003/129] ci: use setup-android v4 with valid SDK package identifiers --- .github/workflows/art-fieldwatch-phase1.yml | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/.github/workflows/art-fieldwatch-phase1.yml b/.github/workflows/art-fieldwatch-phase1.yml index 53b00ae..c39de8d 100644 --- a/.github/workflows/art-fieldwatch-phase1.yml +++ b/.github/workflows/art-fieldwatch-phase1.yml @@ -37,7 +37,9 @@ jobs: - uses: actions/setup-python@v5 with: python-version: '3.12' - - run: sdkmanager 'platforms;android-35' 'build-tools;35.0.0' + - 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' @@ -73,7 +75,9 @@ jobs: - uses: actions/setup-python@v5 with: python-version: '3.12' - - run: sdkmanager 'platforms;android-35' 'build-tools;35.0.0' + - 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' From 8238ae65b074607a653b7cab747e920d3162f6ba Mon Sep 17 00:00:00 2001 From: Muhtasham Nawr al-Mahmud <72372229+mnalmahmud@users.noreply.github.com> Date: Thu, 19 Nov 2026 17:48:39 +0600 Subject: [PATCH 004/129] ci: exercise arm64 ART JIT hook in PR test run --- .github/workflows/art-fieldwatch-phase1.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/art-fieldwatch-phase1.yml b/.github/workflows/art-fieldwatch-phase1.yml index c39de8d..8a431b8 100644 --- a/.github/workflows/art-fieldwatch-phase1.yml +++ b/.github/workflows/art-fieldwatch-phase1.yml @@ -59,7 +59,7 @@ jobs: path: /tmp/artwatch-logs/ if-no-files-found: ignore android-arm64: - if: github.event_name == 'workflow_dispatch' && inputs.arm64 + if: github.event_name == 'pull_request' || (github.event_name == 'workflow_dispatch' && inputs.arm64) runs-on: macos-15-arm64 timeout-minutes: 45 env: From 3e1033904860a9f9098e62d3663287f2853affb7 Mon Sep 17 00:00:00 2001 From: Muhtasham Nawr al-Mahmud <72372229+mnalmahmud@users.noreply.github.com> Date: Thu, 19 Nov 2026 18:01:07 +0600 Subject: [PATCH 005/129] ci: isolate risky deep ART symbol discovery from x86 smoke tests --- art-fieldwatch-phase1/jit-boundary-probe.js | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/art-fieldwatch-phase1/jit-boundary-probe.js b/art-fieldwatch-phase1/jit-boundary-probe.js index 7f3cfb9..b8e359a 100644 --- a/art-fieldwatch-phase1/jit-boundary-probe.js +++ b/art-fieldwatch-phase1/jit-boundary-probe.js @@ -69,6 +69,16 @@ function main() { const modules = Process.enumerateModules().filter(m => artNames.has(m.name)); if (modules.length === 0) { log('No ART library found'); return; } for (const m of modules) log('module='+m.name+' base='+m.base+' path='+m.path); + // x86_64 CI is an ART/Frida smoke test, not a native JIT symbol test. + // Avoid enumerateSymbols() here: on API 34 the previous probe disconnected + // immediately after printing the ART module list. The exact cause is + // unconfirmed; this keeps potentially unsafe symbol enumeration isolated. + if (Process.arch !== 'arm64' || (api !== 33 && api !== 34)) { + log('Inventory complete; skipping deep symbol scan on this platform'); + log('This probe does NOT capture field accesses or modify compiler IR'); + return; + } + log('ARM64 experimental symbol discovery starting'); const sites = modules.flatMap(discover); for (const s of sites) log('candidate='+s.type+' at='+s.address+ ' module='+s.module+' source='+s.source+' symbol='+s.name); From d1a193d54b59b350ecc072bdcff56cc511b915cc Mon Sep 17 00:00:00 2001 From: Muhtasham Nawr al-Mahmud <72372229+mnalmahmud@users.noreply.github.com> Date: Thu, 19 Nov 2026 18:01:18 +0600 Subject: [PATCH 006/129] ci: fix ARM64 runner label and gate experimental emulator job --- .github/workflows/art-fieldwatch-phase1.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/art-fieldwatch-phase1.yml b/.github/workflows/art-fieldwatch-phase1.yml index 8a431b8..cc7caa5 100644 --- a/.github/workflows/art-fieldwatch-phase1.yml +++ b/.github/workflows/art-fieldwatch-phase1.yml @@ -59,8 +59,8 @@ jobs: path: /tmp/artwatch-logs/ if-no-files-found: ignore android-arm64: - if: github.event_name == 'pull_request' || (github.event_name == 'workflow_dispatch' && inputs.arm64) - runs-on: macos-15-arm64 + if: github.event_name == 'workflow_dispatch' && inputs.arm64 + runs-on: macos-15 timeout-minutes: 45 env: FRIDA_VERSION: '17.27.1' From 56929c3ecda9da0d5c0ac713e57c10433c409e33 Mon Sep 17 00:00:00 2001 From: Muhtasham Nawr al-Mahmud <72372229+mnalmahmud@users.noreply.github.com> Date: Thu, 19 Nov 2026 18:18:10 +0600 Subject: [PATCH 007/129] ci: capture Frida console logs in smoke test assertions --- art-fieldwatch-phase1/ci/smoke_test.py | 1 + 1 file changed, 1 insertion(+) diff --git a/art-fieldwatch-phase1/ci/smoke_test.py b/art-fieldwatch-phase1/ci/smoke_test.py index 37ee29d..aa29554 100644 --- a/art-fieldwatch-phase1/ci/smoke_test.py +++ b/art-fieldwatch-phase1/ci/smoke_test.py @@ -33,6 +33,7 @@ def main(): try: script = session.create_script((BASE/'jit-boundary-probe.js').read_text()) script.on('message',on_message) + script.set_log_handler(lambda level, line: record('console-'+level, line)) script.load() device.resume(pid) time.sleep(20) From cf6bdb3b0ed7615c49fe4b347e425e37c1db5d29 Mon Sep 17 00:00:00 2001 From: Muhtasham Nawr al-Mahmud <72372229+mnalmahmud@users.noreply.github.com> Date: Thu, 19 Nov 2026 18:47:20 +0600 Subject: [PATCH 008/129] research: inspect ART JIT exports safely on both x86_64 emulator profiles --- art-fieldwatch-phase1/jit-boundary-probe.js | 14 +++++++++++++- 1 file changed, 13 insertions(+), 1 deletion(-) diff --git a/art-fieldwatch-phase1/jit-boundary-probe.js b/art-fieldwatch-phase1/jit-boundary-probe.js index b8e359a..191e755 100644 --- a/art-fieldwatch-phase1/jit-boundary-probe.js +++ b/art-fieldwatch-phase1/jit-boundary-probe.js @@ -68,7 +68,19 @@ function main() { log('pid='+Process.id+' arch='+Process.arch+' pointerSize='+Process.pointerSize+' api='+api); const modules = Process.enumerateModules().filter(m => artNames.has(m.name)); if (modules.length === 0) { log('No ART library found'); return; } - for (const m of modules) log('module='+m.name+' base='+m.base+' path='+m.path); + for (const m of modules) { + log('module='+m.name+' base='+m.base+' path='+m.path); + // Dynamic exports only. Unlike enumerateSymbols(), this avoids scanning + // the full ELF symbol table on production ART. + try { + const candidates = m.enumerateExports().filter(e => + /jit_load|jit_compile_method|jit_compiler_|CompileMethod/.test(e.name)); + log('exports=' + m.name + ' matches=' + candidates.length); + for (const e of candidates.slice(0, 30)) + log('export=' + m.name + ' name=' + e.name + ' address=' + e.address); + if (candidates.length > 30) log('export-list-truncated=' + m.name); + } catch (e) { log('export-enumeration-error=' + m.name + ': ' + e.message); } + } // x86_64 CI is an ART/Frida smoke test, not a native JIT symbol test. // Avoid enumerateSymbols() here: on API 34 the previous probe disconnected // immediately after printing the ART module list. The exact cause is From 13ebe09296f3f1bcd3574c76ac0f6c201dac3dda Mon Sep 17 00:00:00 2001 From: Muhtasham Nawr al-Mahmud <72372229+mnalmahmud@users.noreply.github.com> Date: Thu, 19 Nov 2026 23:54:28 +0600 Subject: [PATCH 009/129] research: trace exported ART JIT compilation boundaries on x86_64 and arm64 --- .../ci/run-emulator-smoke.sh | 18 ++++- art-fieldwatch-phase1/ci/smoke_test.py | 9 +++ art-fieldwatch-phase1/jit-boundary-probe.js | 77 ++++++++++++------- 3 files changed, 73 insertions(+), 31 deletions(-) diff --git a/art-fieldwatch-phase1/ci/run-emulator-smoke.sh b/art-fieldwatch-phase1/ci/run-emulator-smoke.sh index 12ae3cf..2e7167b 100755 --- a/art-fieldwatch-phase1/ci/run-emulator-smoke.sh +++ b/art-fieldwatch-phase1/ci/run-emulator-smoke.sh @@ -18,5 +18,19 @@ 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 &)' -sleep 3 -python3 art-fieldwatch-phase1/ci/smoke_test.py +# 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 ! 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 index aa29554..88c6d1e 100644 --- a/art-fieldwatch-phase1/ci/smoke_test.py +++ b/art-fieldwatch-phase1/ci/smoke_test.py @@ -27,6 +27,7 @@ def on_message(message,data): 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) @@ -55,6 +56,14 @@ def main(): raise AssertionError('No native JIT hook installed') if 'JIT success' not in text: raise AssertionError('No JIT compile observed') + hooked = [e for e in messages if e['kind']=='frida' and + '"artwatch-hook-attached"' in e['text']] + compiled = [e 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)}') + if os.environ.get('ARTWATCH_REQUIRE_JIT') == '1': + if not hooked: raise AssertionError('JIT compiler hook not installed') + if not compiled: raise AssertionError('No compilation events observed') record('host','PASS: Frida attach + ART discovery + fixture warmup') if __name__ == '__main__': diff --git a/art-fieldwatch-phase1/jit-boundary-probe.js b/art-fieldwatch-phase1/jit-boundary-probe.js index 191e755..1ddaa11 100644 --- a/art-fieldwatch-phase1/jit-boundary-probe.js +++ b/art-fieldwatch-phase1/jit-boundary-probe.js @@ -81,38 +81,57 @@ function main() { if (candidates.length > 30) log('export-list-truncated=' + m.name); } catch (e) { log('export-enumeration-error=' + m.name + ': ' + e.message); } } - // x86_64 CI is an ART/Frida smoke test, not a native JIT symbol test. - // Avoid enumerateSymbols() here: on API 34 the previous probe disconnected - // immediately after printing the ART module list. The exact cause is - // unconfirmed; this keeps potentially unsafe symbol enumeration isolated. - if (Process.arch !== 'arm64' || (api !== 33 && api !== 34)) { - log('Inventory complete; skipping deep symbol scan on this platform'); - log('This probe does NOT capture field accesses or modify compiler IR'); - return; + + // Observe exported C++ compilation functions, using mangled ELF names. + const candidates = []; + for (const m of modules) { + for (const e of m.enumerateExports()) { + if (e.type !== 'function') continue; + let layer = null; + if (e.name.startsWith('_ZN3art3jit3Jit13CompileMethodE')) + layer = 'runtime'; + else if (e.name.startsWith('_ZN3art3jit11JitCompiler13CompileMethodE')) + layer = 'compiler'; + if (layer !== null) { + candidates.push({layer,address:e.address,name:e.name,module:m.name}); + log('compilation-export=' + layer + ' name=' + e.name + ' at=' + e.address); + } + } } - log('ARM64 experimental symbol discovery starting'); - const sites = modules.flatMap(discover); - for (const s of sites) log('candidate='+s.type+' at='+s.address+ - ' module='+s.module+' source='+s.source+' symbol='+s.name); - if (Process.arch !== 'arm64' || (api !== 33 && api !== 34)) { - log('Inventory only: JIT callback requires API 33/34 arm64'); + if (!['x64','arm64'].includes(Process.arch) || ![33,34].includes(api)) { + log('Inventory only: compiler ABI not yet validated for this profile'); return; } - const pick = t => sites.find(s => s.type === t); - const chosen = api === 34 - ? (pick('jit_dispatch_internal') || pick('jit_dispatch')) - : (pick('jit_dispatch') || pick('jit_dispatch_internal')); - try { - if (chosen) attachDispatch(chosen); - else log('No ABI-checked C++ JIT dispatch symbol discovered'); - } catch(e) { log('Hook installation failed: '+e.stack); } - log('This probe does NOT capture field accesses or modify compiler IR'); - let before = 0; - setInterval(() => { - if (counts.attempts !== before) { - before = counts.attempts; - log('summary '+JSON.stringify(counts)); + const limits = {runtime:0,compiler:0}; + let hooked = 0; + for (const layer of ['runtime','compiler']) { + const site = candidates.find(c => c.layer === layer); + if (!site) continue; + try { + Interceptor.attach(site.address, { + onEnter(args) { + // Runtime: this, ArtMethod*, Thread*, CompilationKind, bool + // Compiler: this, Thread*, JitMemoryRegion*, ArtMethod*, CompilationKind + this.method = (layer === 'runtime' ? args[1] : args[3]).toString(); + this.compilationKind = (layer === 'runtime' ? args[3] : args[4]).toInt32(); + }, + onLeave(ret) { + limits[layer]++; + const event = {type:'artwatch-jit',layer,method:this.method, + kind:this.compilationKind,success:ret.toInt32() !== 0}; + send(event); + if (limits[layer] <= 25) log('JIT ' + JSON.stringify(event)); + } + }); + hooked++; + log('Attached compilation observer: ' + layer + ' at=' + site.address); + send({type:'artwatch-hook-attached',layer,name:site.name}); + } catch (e) { + log('JIT hook failed for ' + layer + ': ' + e.stack); } - }, 5000); + } + log('compile-hooks=' + hooked); + log('No field interception or compiler IR mutation implemented'); + } main(); From 42f4f8064c18be726fd7b6a96c11d1f45a3c4eb1 Mon Sep 17 00:00:00 2001 From: Muhtasham Nawr al-Mahmud <72372229+mnalmahmud@users.noreply.github.com> Date: Fri, 20 Nov 2026 00:16:29 +0600 Subject: [PATCH 010/129] fix: observe ordinary ART JIT worker boundary and resolve compiler via validated vtable --- art-fieldwatch-phase1/jit-boundary-probe.js | 225 ++++++++++---------- 1 file changed, 109 insertions(+), 116 deletions(-) diff --git a/art-fieldwatch-phase1/jit-boundary-probe.js b/art-fieldwatch-phase1/jit-boundary-probe.js index 1ddaa11..32dc903 100644 --- a/art-fieldwatch-phase1/jit-boundary-probe.js +++ b/art-fieldwatch-phase1/jit-boundary-probe.js @@ -1,137 +1,130 @@ 'use strict'; -/* Read-only JIT-boundary discovery. Does NOT intercept field reads/writes. */ -const LIMIT = 40; -const counts = {attempts: 0, successes: 0, failures: 0}; -const hooks = []; -const artNames = new Set(['libart.so','libartd.so','libart-compiler.so','libartd-compiler.so']); -const log = x => console.log('[art-fieldwatch/phase1] ' + x); +// 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}; function sdkLevel() { try { const p = Process.getModuleByName('libc.so').findExportByName('__system_property_get'); - if (p === null) return '?'; - const fn = new NativeFunction(p,'int',['pointer','pointer']); - const out = Memory.alloc(128); - return fn(Memory.allocUtf8String('ro.build.version.sdk'),out) > 0 - ? out.readUtf8String() : '?'; - } catch (_) { return '?'; } + 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; } } -function kind(n) { - if (/\bJit::CompileMethodInternal\(/.test(n)) return 'jit_dispatch_internal'; - if (/\bJit::CompileMethod\(/.test(n)) return 'jit_dispatch'; - if (/\bOptimizingCompiler::JitCompile\(/.test(n)) return 'optimizing_jit'; - if (/\bOptimizingCompiler::TryCompile\(/.test(n)) return 'optimizing_preopt_candidate'; - if (/\bHGraphBuilder::BuildGraph\(/.test(n)) return 'graph_builder'; - if (/\bJitCodeCache::Commit\(/.test(n)) return 'code_publication'; - if (n === 'jit_load') return 'jit_load'; - return null; +function getExport(module, prefix) { + return module.enumerateExports().find(e => e.type === 'function' && e.name.startsWith(prefix)); } -function discover(m) { - const result = []; - const seen = new Set(); - const add = (name,address,source) => { - const type = kind(name); - if (type === null) return; - const key = type + ':' + address; - if (seen.has(key)) return; - seen.add(key); - result.push({type,name,address,source,module:m.name}); - }; - const exp = m.findExportByName('jit_load'); - if (exp !== null) add('jit_load',exp,'export'); +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 = runtime.enumerateExports().find(e => + e.name === '_ZN3art3jit3Jit13jit_compiler_E'); + if (!symbol) { log('compiler-vtable=unavailable (jit_compiler_ not exported)'); return null; } try { - for (const s of m.enumerateSymbols()) { - if (s.type === 'function' || s.type === undefined) - add(s.name,s.address,'symbol'); + 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; } - } catch (e) { log('Cannot enumerate symbols in ' + m.name + ': ' + e.message); } - return result; -} -function attachDispatch(site) { - hooks.push(Interceptor.attach(site.address, { - onEnter(args) { - this.method = args[1]; - this.kind = args[3].toInt32(); - counts.attempts++; - this.print = counts.attempts <= LIMIT; - }, - onLeave(ret) { - const ok = ret.toInt32() !== 0; - counts[ok ? 'successes' : 'failures']++; - if (this.print) log('JIT ' + (ok?'success':'failed') + - ' method=' + this.method + ' kind=' + this.kind); + 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('Attached compilation observer at ' + site.address + ' (' + site.name + ')'); + 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 (this.ordinal <= SAMPLE_LIMIT) + log('JIT enter layer=' + layer + ' method=' + this.method + + ' kind=' + this.compilationKind); + }, + onLeave(ret) { + 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; + } } function main() { - const api = Number(sdkLevel()); - log('pid='+Process.id+' arch='+Process.arch+' pointerSize='+Process.pointerSize+' api='+api); - const modules = Process.enumerateModules().filter(m => artNames.has(m.name)); - if (modules.length === 0) { log('No ART library found'); return; } - for (const m of modules) { - log('module='+m.name+' base='+m.base+' path='+m.path); - // Dynamic exports only. Unlike enumerateSymbols(), this avoids scanning - // the full ELF symbol table on production ART. + 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); try { - const candidates = m.enumerateExports().filter(e => - /jit_load|jit_compile_method|jit_compiler_|CompileMethod/.test(e.name)); - log('exports=' + m.name + ' matches=' + candidates.length); - for (const e of candidates.slice(0, 30)) - log('export=' + m.name + ' name=' + e.name + ' address=' + e.address); - if (candidates.length > 30) log('export-list-truncated=' + m.name); - } catch (e) { log('export-enumeration-error=' + m.name + ': ' + e.message); } + const matches = module.enumerateExports().filter(e => + /jit_load|jit_compiler_|CompileMethod/.test(e.name)); + log('exports=' + module.name + ' matches=' + matches.length); + matches.slice(0, 30).forEach(e => + log('export=' + module.name + ' name=' + e.name + ' address=' + e.address)); + } catch (e) { log('export-error=' + module.name + ': ' + e); } } - - // Observe exported C++ compilation functions, using mangled ELF names. - const candidates = []; - for (const m of modules) { - for (const e of m.enumerateExports()) { - if (e.type !== 'function') continue; - let layer = null; - if (e.name.startsWith('_ZN3art3jit3Jit13CompileMethodE')) - layer = 'runtime'; - else if (e.name.startsWith('_ZN3art3jit11JitCompiler13CompileMethodE')) - layer = 'compiler'; - if (layer !== null) { - candidates.push({layer,address:e.address,name:e.name,module:m.name}); - log('compilation-export=' + layer + ' name=' + e.name + ' at=' + e.address); - } - } + // 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; } - if (!['x64','arm64'].includes(Process.arch) || ![33,34].includes(api)) { - log('Inventory only: compiler ABI not yet validated for this profile'); - return; - } - const limits = {runtime:0,compiler:0}; + 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; - for (const layer of ['runtime','compiler']) { - const site = candidates.find(c => c.layer === layer); - if (!site) continue; - try { - Interceptor.attach(site.address, { - onEnter(args) { - // Runtime: this, ArtMethod*, Thread*, CompilationKind, bool - // Compiler: this, Thread*, JitMemoryRegion*, ArtMethod*, CompilationKind - this.method = (layer === 'runtime' ? args[1] : args[3]).toString(); - this.compilationKind = (layer === 'runtime' ? args[3] : args[4]).toInt32(); - }, - onLeave(ret) { - limits[layer]++; - const event = {type:'artwatch-jit',layer,method:this.method, - kind:this.compilationKind,success:ret.toInt32() !== 0}; - send(event); - if (limits[layer] <= 25) log('JIT ' + JSON.stringify(event)); - } - }); - hooked++; - log('Attached compilation observer: ' + layer + ' at=' + site.address); - send({type:'artwatch-hook-attached',layer,name:site.name}); - } catch (e) { - log('JIT hook failed for ' + layer + ': ' + e.stack); + if (runtime) { + const internal = getExport(runtime, '_ZN3art3jit3Jit21CompileMethodInternalE'); + 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, '_ZN3art3jit11JitCompiler13CompileMethodE'); + 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'); + } log('compile-hooks=' + hooked); log('No field interception or compiler IR mutation implemented'); - } main(); From 9c3bb6e3fc3db46ff07dc0c79bc6f8edbb65cfe7 Mon Sep 17 00:00:00 2001 From: Muhtasham Nawr al-Mahmud <72372229+mnalmahmud@users.noreply.github.com> Date: Fri, 20 Nov 2026 00:16:55 +0600 Subject: [PATCH 011/129] test: require observed ART JIT callbacks at internal and compiler boundaries --- art-fieldwatch-phase1/ci/smoke_test.py | 25 +++++++++++++++---------- 1 file changed, 15 insertions(+), 10 deletions(-) diff --git a/art-fieldwatch-phase1/ci/smoke_test.py b/art-fieldwatch-phase1/ci/smoke_test.py index 88c6d1e..525437e 100644 --- a/art-fieldwatch-phase1/ci/smoke_test.py +++ b/art-fieldwatch-phase1/ci/smoke_test.py @@ -51,19 +51,24 @@ def main(): if errors: raise AssertionError('Frida errors: '+'; '.join(errors)) if 'WARMUP_FAILED' in logs.stdout or 'WARMUP_DONE' not in logs.stdout: raise AssertionError('APK fixture warmup failed or timed out') - if os.environ.get('ARTWATCH_REQUIRE_JIT') == '1': - if 'Attached compilation observer' not in text: - raise AssertionError('No native JIT hook installed') - if 'JIT success' not in text: - raise AssertionError('No JIT compile observed') - hooked = [e for e in messages if e['kind']=='frida' and + hooked = [e['text'] for e in messages if e['kind']=='frida' and '"artwatch-hook-attached"' in e['text']] - compiled = [e for e in messages if e['kind']=='frida' and + 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)}') - if os.environ.get('ARTWATCH_REQUIRE_JIT') == '1': - if not hooked: raise AssertionError('JIT compiler hook not installed') - if not compiled: raise AssertionError('No compilation events observed') + 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. + if not any('"runtime_internal"' in h for h in hooked): + raise AssertionError('Jit::CompileMethodInternal interceptor not installed') + 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 internal or not compiler: + raise AssertionError('Missing JIT compilation callbacks from required layers') record('host','PASS: Frida attach + ART discovery + fixture warmup') if __name__ == '__main__': From 9ad8a14c5fdc7a909b860db839a78c730cd71c16 Mon Sep 17 00:00:00 2001 From: Muhtasham Nawr al-Mahmud <72372229+mnalmahmud@users.noreply.github.com> Date: Fri, 20 Nov 2026 00:17:03 +0600 Subject: [PATCH 012/129] ci: make x86_64 smoke verify executed ART JIT boundaries --- .github/workflows/art-fieldwatch-phase1.yml | 1 + 1 file changed, 1 insertion(+) diff --git a/.github/workflows/art-fieldwatch-phase1.yml b/.github/workflows/art-fieldwatch-phase1.yml index cc7caa5..b2bcbbe 100644 --- a/.github/workflows/art-fieldwatch-phase1.yml +++ b/.github/workflows/art-fieldwatch-phase1.yml @@ -28,6 +28,7 @@ jobs: 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 From ab91284190fabbaaa642bff7f96d04b59432d8f6 Mon Sep 17 00:00:00 2001 From: Muhtasham Nawr al-Mahmud <72372229+mnalmahmud@users.noreply.github.com> Date: Fri, 20 Nov 2026 00:40:49 +0600 Subject: [PATCH 013/129] research: capture on-device ART ELF symbol and build-id evidence in CI --- .../ci/art-binary-inventory.sh | 36 +++++++++++++++++++ 1 file changed, 36 insertions(+) create mode 100644 art-fieldwatch-phase1/ci/art-binary-inventory.sh 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..0cb65c7 --- /dev/null +++ b/art-fieldwatch-phase1/ci/art-binary-inventory.sh @@ -0,0 +1,36 @@ +#!/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' | + head -n 80 || 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" From 358310fda0e277a5b506775906ad8f50c9f0d31f Mon Sep 17 00:00:00 2001 From: Muhtasham Nawr al-Mahmud <72372229+mnalmahmud@users.noreply.github.com> Date: Fri, 20 Nov 2026 00:41:16 +0600 Subject: [PATCH 014/129] ci: gather ART ELF symbol inventory before Frida compilation test --- art-fieldwatch-phase1/ci/run-emulator-smoke.sh | 3 +++ 1 file changed, 3 insertions(+) diff --git a/art-fieldwatch-phase1/ci/run-emulator-smoke.sh b/art-fieldwatch-phase1/ci/run-emulator-smoke.sh index 2e7167b..6fa7b63 100755 --- a/art-fieldwatch-phase1/ci/run-emulator-smoke.sh +++ b/art-fieldwatch-phase1/ci/run-emulator-smoke.sh @@ -29,6 +29,9 @@ if [ "$ready" -ne 1 ]; then adb shell cat /data/local/tmp/artwatch-frida-server.log || true 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 From 17eca7e295d97eb043b20f237b2f7094f8342c6b Mon Sep 17 00:00:00 2001 From: Muhtasham Nawr al-Mahmud <72372229+mnalmahmud@users.noreply.github.com> Date: Fri, 20 Nov 2026 00:41:45 +0600 Subject: [PATCH 015/129] fix: avoid in-process export enumeration and use exact ART symbols --- art-fieldwatch-phase1/jit-boundary-probe.js | 35 +++++++++++++-------- 1 file changed, 22 insertions(+), 13 deletions(-) diff --git a/art-fieldwatch-phase1/jit-boundary-probe.js b/art-fieldwatch-phase1/jit-boundary-probe.js index 32dc903..71cce7a 100644 --- a/art-fieldwatch-phase1/jit-boundary-probe.js +++ b/art-fieldwatch-phase1/jit-boundary-probe.js @@ -15,16 +15,22 @@ function sdkLevel() { return rc > 0 ? Number(buf.readUtf8String()) : NaN; } catch (e) { log('sdk-error=' + e); return NaN; } } -function getExport(module, prefix) { - return module.enumerateExports().find(e => e.type === 'function' && e.name.startsWith(prefix)); +const NAMES = { + internal: '_ZN3art3jit3Jit21CompileMethodInternalEPNS_9ArtMethodEPNS_6ThreadENS_15CompilationKindEb', + publicCompile: '_ZN3art3jit3Jit13CompileMethodEPNS_9ArtMethodEPNS_6ThreadENS_15CompilationKindEb', + compiler: '_ZN3art3jit11JitCompiler13CompileMethodEPNS_6ThreadEPNS0_15JitMemoryRegionEPNS_9ArtMethodENS_15CompilationKindE', + instance: '_ZN3art3jit3Jit13jit_compiler_E' +}; +function getExport(module, exactName) { + const address = module.findExportByName(exactName); + return address === null ? null : {name: exactName, address}; } 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 = runtime.enumerateExports().find(e => - e.name === '_ZN3art3jit3Jit13jit_compiler_E'); + 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(). @@ -86,13 +92,16 @@ function main() { 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); - try { - const matches = module.enumerateExports().filter(e => - /jit_load|jit_compiler_|CompileMethod/.test(e.name)); - log('exports=' + module.name + ' matches=' + matches.length); - matches.slice(0, 30).forEach(e => - log('export=' + module.name + ' name=' + e.name + ' address=' + e.address)); - } catch (e) { log('export-error=' + module.name + ': ' + e); } + // 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, '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) || @@ -104,7 +113,7 @@ function main() { m.name === 'libartd-compiler.so'); let hooked = 0; if (runtime) { - const internal = getExport(runtime, '_ZN3art3jit3Jit21CompileMethodInternalE'); + const internal = getExport(runtime, NAMES.internal); if (internal) { hooked += Number(attach('runtime_internal', {address: internal.address, name: internal.name, source: 'export'})); @@ -113,7 +122,7 @@ function main() { } } if (runtime && compiler) { - const exported = getExport(compiler, '_ZN3art3jit11JitCompiler13CompileMethodE'); + 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 + From b3ec3480eac678bc368ae44cb478b7b5c7a8da46 Mon Sep 17 00:00:00 2001 From: Muhtasham Nawr al-Mahmud <72372229+mnalmahmud@users.noreply.github.com> Date: Fri, 20 Nov 2026 00:41:57 +0600 Subject: [PATCH 016/129] test: require compiler callbacks on API 33 without missing internal export --- art-fieldwatch-phase1/ci/smoke_test.py | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/art-fieldwatch-phase1/ci/smoke_test.py b/art-fieldwatch-phase1/ci/smoke_test.py index 525437e..1c159b0 100644 --- a/art-fieldwatch-phase1/ci/smoke_test.py +++ b/art-fieldwatch-phase1/ci/smoke_test.py @@ -60,15 +60,18 @@ def main(): if required: # Assert the actual worker entry, not the exported Jit::CompileMethod() # path bypassed by ordinary JitCompileTask execution. - if not any('"runtime_internal"' in h for h in hooked): - raise AssertionError('Jit::CompileMethodInternal interceptor not installed') + # 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 internal or not compiler: - raise AssertionError('Missing JIT compilation callbacks from required layers') + 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') record('host','PASS: Frida attach + ART discovery + fixture warmup') if __name__ == '__main__': From 9f7e34b66f4ae418e67df2e92c3ec8f2610b8b3d Mon Sep 17 00:00:00 2001 From: Muhtasham Nawr al-Mahmud <72372229+mnalmahmud@users.noreply.github.com> Date: Fri, 20 Nov 2026 01:56:41 +0600 Subject: [PATCH 017/129] research: observe API 33 HGraphBuilder and pre-optimization boundaries --- art-fieldwatch-phase1/README.md | 56 +++++++++---- art-fieldwatch-phase1/ci/smoke_test.py | 28 +++++++ art-fieldwatch-phase1/jit-boundary-probe.js | 92 ++++++++++++++++++++- 3 files changed, 157 insertions(+), 19 deletions(-) diff --git a/art-fieldwatch-phase1/README.md b/art-fieldwatch-phase1/README.md index 8f36352..4987db2 100644 --- a/art-fieldwatch-phase1/README.md +++ b/art-fieldwatch-phase1/README.md @@ -1,22 +1,46 @@ -# ART Fieldwatch Phase 1 CI +# ART Fieldwatch Phase 1 — JIT and HGraph research -This is a **read-only diagnostic** for JIT symbol and compilation-path discovery. -It is NOT yet a Java field-read/write interceptor. +**Read-only diagnostic:** field interception, graph mutation, DEX rewriting, +deoptimization and native compiled-code patching are NOT implemented. -The workflow uses Android API 33 and 34 x86_64 emulators for spawn, -Frida attachment, ART module discovery and APK warmup. Both x86_64 tests -operate in passive inventory mode; they do not prove the ARM64 hook works. +## Verified compiler interface -The optional workflow_dispatch arm64 job targets Android 14 API 34 -and **strictly** checks for a JIT hook and compilation. Failing here can -mean missing symbols, unexpected ART ABI, no compilations, or unavailable -emulator images. Preserve CI logs as research evidence, not as proof of field -monitoring coverage. +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. -The architecture goal is API 21-37. There is no compatibility guarantee -without running the field-watch suite on each profile. +## New read-only graph boundary experiment (API 33 x86_64) -Frida runtime and server version: 17.27.1 (pinned). +The actual API 33 `libart-compiler.so` dynamic ELF symbol table includes: +- `art::HGraphBuilder::BuildGraph()` +- `art::OptimizingCompiler::RunOptimizations(HGraph*, CodeGenerator*, const DexCompilationUnit&, PassObserver*)` -Run from GitHub Actions > ART Fieldwatch phase 1 > Run workflow, -optionally arm64=true. Check the log artifacts for diagnostics. +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 diff --git a/art-fieldwatch-phase1/ci/smoke_test.py b/art-fieldwatch-phase1/ci/smoke_test.py index 1c159b0..93292e9 100644 --- a/art-fieldwatch-phase1/ci/smoke_test.py +++ b/art-fieldwatch-phase1/ci/smoke_test.py @@ -72,6 +72,34 @@ def main(): # 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. + 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 + 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') record('host','PASS: Frida attach + ART discovery + fixture warmup') if __name__ == '__main__': diff --git a/art-fieldwatch-phase1/jit-boundary-probe.js b/art-fieldwatch-phase1/jit-boundary-probe.js index 71cce7a..c56a839 100644 --- a/art-fieldwatch-phase1/jit-boundary-probe.js +++ b/art-fieldwatch-phase1/jit-boundary-probe.js @@ -4,7 +4,10 @@ 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}; +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(); function sdkLevel() { try { const p = Process.getModuleByName('libc.so').findExportByName('__system_property_get'); @@ -19,7 +22,9 @@ const NAMES = { internal: '_ZN3art3jit3Jit21CompileMethodInternalEPNS_9ArtMethodEPNS_6ThreadENS_15CompilationKindEb', publicCompile: '_ZN3art3jit3Jit13CompileMethodEPNS_9ArtMethodEPNS_6ThreadENS_15CompilationKindEb', compiler: '_ZN3art3jit11JitCompiler13CompileMethodEPNS_6ThreadEPNS0_15JitMemoryRegionEPNS_9ArtMethodENS_15CompilationKindE', - instance: '_ZN3art3jit3Jit13jit_compiler_E' + instance: '_ZN3art3jit3Jit13jit_compiler_E', + buildGraph: '_ZN3art13HGraphBuilder10BuildGraphEv', + runOptimizations: '_ZNK3art18OptimizingCompiler16RunOptimizationsEPNS_6HGraphEPNS_13CodeGeneratorERKNS_18DexCompilationUnitEPNS_12PassObserverE' }; function getExport(module, exactName) { const address = module.findExportByName(exactName); @@ -62,11 +67,22 @@ function attach(layer, site) { 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); + 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') { + 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}; @@ -85,6 +101,62 @@ function attach(layer, site) { 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; } + } else { + // const OptimizingCompiler* this, HGraph*, CodeGenerator*, ... + this.graph = args[1].toString(); + const previous = builtByThread.get(this.nativeThread); + const matches = previous && previous.graphCandidate !== null + ? previous.graphCandidate === this.graph : null; + 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 !== 'graph_builder') return; + 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; + } +} function main() { const api = sdkLevel(); log('pid=' + Process.id + ' arch=' + Process.arch + @@ -95,7 +167,8 @@ function main() { // 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, 'jit_load']) { + NAMES.compiler, NAMES.instance, NAMES.buildGraph, + NAMES.runOptimizations, 'jit_load']) { try { const site = getExport(module, name); if (site) log('export=' + module.name + ' name=' + name + @@ -133,6 +206,19 @@ function main() { 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); + } + } else { + log('graph-boundaries=disabled (unverified binary profile)'); + } log('compile-hooks=' + hooked); log('No field interception or compiler IR mutation implemented'); } From 1655726467789ea8544aaf1864b9da09ed143e11 Mon Sep 17 00:00:00 2001 From: Muhtasham Nawr al-Mahmud <72372229+mnalmahmud@users.noreply.github.com> Date: Fri, 20 Nov 2026 04:34:31 +0600 Subject: [PATCH 018/129] research: observe ART instance-field DEX builds against live HGraph on API 33 --- art-fieldwatch-phase1/README.md | 17 +++++ .../ci/art-binary-inventory.sh | 2 +- art-fieldwatch-phase1/ci/smoke_test.py | 21 ++++++ art-fieldwatch-phase1/jit-boundary-probe.js | 65 ++++++++++++++++++- .../example/artfieldwatch/FieldIRTarget.java | 23 +++++++ .../example/artfieldwatch/MainActivity.java | 1 + 6 files changed, 126 insertions(+), 3 deletions(-) create mode 100644 art-fieldwatch-phase1/test/app/src/main/java/com/example/artfieldwatch/FieldIRTarget.java diff --git a/art-fieldwatch-phase1/README.md b/art-fieldwatch-phase1/README.md index 4987db2..6155846 100644 --- a/art-fieldwatch-phase1/README.md +++ b/art-fieldwatch-phase1/README.md @@ -44,3 +44,20 @@ 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. diff --git a/art-fieldwatch-phase1/ci/art-binary-inventory.sh b/art-fieldwatch-phase1/ci/art-binary-inventory.sh index 0cb65c7..777edd7 100644 --- a/art-fieldwatch-phase1/ci/art-binary-inventory.sh +++ b/art-fieldwatch-phase1/ci/art-binary-inventory.sh @@ -23,7 +23,7 @@ abi="$(adb shell getprop ro.product.cpu.abi | tr -d '\r')" 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' | + 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 "-- summary --" if readelf -SW "$tmp/$library" | grep -q ' \.symtab '; then diff --git a/art-fieldwatch-phase1/ci/smoke_test.py b/art-fieldwatch-phase1/ci/smoke_test.py index 93292e9..5d29b3b 100644 --- a/art-fieldwatch-phase1/ci/smoke_test.py +++ b/art-fieldwatch-phase1/ci/smoke_test.py @@ -100,6 +100,27 @@ def main(): 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') record('host','PASS: Frida attach + ART discovery + fixture warmup') if __name__ == '__main__': diff --git a/art-fieldwatch-phase1/jit-boundary-probe.js b/art-fieldwatch-phase1/jit-boundary-probe.js index c56a839..91ed42e 100644 --- a/art-fieldwatch-phase1/jit-boundary-probe.js +++ b/art-fieldwatch-phase1/jit-boundary-probe.js @@ -8,6 +8,9 @@ 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}; function sdkLevel() { try { const p = Process.getModuleByName('libc.so').findExportByName('__system_property_get'); @@ -24,7 +27,11 @@ const NAMES = { compiler: '_ZN3art3jit11JitCompiler13CompileMethodEPNS_6ThreadEPNS0_15JitMemoryRegionEPNS_9ArtMethodENS_15CompilationKindE', instance: '_ZN3art3jit3Jit13jit_compiler_E', buildGraph: '_ZN3art13HGraphBuilder10BuildGraphEv', - runOptimizations: '_ZNK3art18OptimizingCompiler16RunOptimizationsEPNS_6HGraphEPNS_13CodeGeneratorERKNS_18DexCompilationUnitEPNS_12PassObserverE' + runOptimizations: '_ZNK3art18OptimizingCompiler16RunOptimizationsEPNS_6HGraphEPNS_13CodeGeneratorERKNS_18DexCompilationUnitEPNS_12PassObserverE', + // Candidate exported signatures from instruction_builder.cc. Only use if + // this exact ELF symbol exists on the running device. + fieldInstance: '_ZN3art19HInstructionBuilder24BuildInstanceFieldAccessERKNS_11InstructionEjbm', + fieldStatic: '_ZN3art19HInstructionBuilder22BuildStaticFieldAccessERKNS_11InstructionEjb' }; function getExport(module, exactName) { const address = module.findExportByName(exactName); @@ -118,6 +125,8 @@ function attachGraphBoundary(layer, site) { // 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); } else { // const OptimizingCompiler* this, HGraph*, CodeGenerator*, ... this.graph = args[1].toString(); @@ -137,6 +146,8 @@ function attachGraphBoundary(layer, site) { }, onLeave(_retval) { 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, @@ -157,6 +168,47 @@ function attachGraphBoundary(layer, site) { 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]; + if (ordinal > FIELD_SAMPLE_LIMIT) return; + 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}; + send(event); + log('FIELD_BUILD ' + JSON.stringify(event)); + } + }); + 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; + } +} function main() { const api = sdkLevel(); log('pid=' + Process.id + ' arch=' + Process.arch + @@ -168,7 +220,8 @@ function main() { // 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, 'jit_load']) { + NAMES.runOptimizations, NAMES.fieldInstance, + NAMES.fieldStatic, 'jit_load']) { try { const site = getExport(module, name); if (site) log('export=' + module.name + ' name=' + name + @@ -216,6 +269,14 @@ function main() { 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); + } } else { log('graph-boundaries=disabled (unverified binary profile)'); } 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..f36fff5 --- /dev/null +++ b/art-fieldwatch-phase1/test/app/src/main/java/com/example/artfieldwatch/FieldIRTarget.java @@ -0,0 +1,23 @@ +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; + } + + 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 read/write mismatch at " + i); + } + observed++; + } + return observed; + } +} diff --git a/art-fieldwatch-phase1/test/app/src/main/java/com/example/artfieldwatch/MainActivity.java b/art-fieldwatch-phase1/test/app/src/main/java/com/example/artfieldwatch/MainActivity.java index 73b6c2d..fd1a2c8 100644 --- a/art-fieldwatch-phase1/test/app/src/main/java/com/example/artfieldwatch/MainActivity.java +++ b/art-fieldwatch-phase1/test/app/src/main/java/com/example/artfieldwatch/MainActivity.java @@ -16,6 +16,7 @@ protected void onCreate(Bundle state) { try { for (int i = 0; i < 40; i++) accumulator += FieldWatchTarget.exercise(100000); + accumulator += FieldIRTarget.warmup(150000); Log.i("ARTWATCH_CI","WARMUP_DONE checksum=" + accumulator); } catch (Throwable t) { Log.e("ARTWATCH_CI","WARMUP_FAILED",t); From 869560bbafa8da1fc1c7e248ab6fb9b9e1ecab61 Mon Sep 17 00:00:00 2001 From: Muhtasham Nawr al-Mahmud <72372229+mnalmahmud@users.noreply.github.com> Date: Fri, 20 Nov 2026 05:25:22 +0600 Subject: [PATCH 019/129] ci: enable KVM and fail fast instead of looping on emulator 37.3 boot --- .github/workflows/art-fieldwatch-phase1.yml | 22 +++++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/.github/workflows/art-fieldwatch-phase1.yml b/.github/workflows/art-fieldwatch-phase1.yml index b2bcbbe..8c6778d 100644 --- a/.github/workflows/art-fieldwatch-phase1.yml +++ b/.github/workflows/art-fieldwatch-phase1.yml @@ -31,6 +31,26 @@ jobs: ARTWATCH_REQUIRE_JIT: '1' 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 @@ -52,6 +72,8 @@ jobs: 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() From d773bb86946892d903dc8b8d1f83f849da01219e Mon Sep 17 00:00:00 2001 From: Muhtasham Nawr al-Mahmud <72372229+mnalmahmud@users.noreply.github.com> Date: Fri, 20 Nov 2026 14:52:26 +0600 Subject: [PATCH 020/129] fix: use API33 confirmed BuildInstanceFieldAccess ELF signature --- art-fieldwatch-phase1/jit-boundary-probe.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/art-fieldwatch-phase1/jit-boundary-probe.js b/art-fieldwatch-phase1/jit-boundary-probe.js index 91ed42e..8d43e0b 100644 --- a/art-fieldwatch-phase1/jit-boundary-probe.js +++ b/art-fieldwatch-phase1/jit-boundary-probe.js @@ -30,7 +30,7 @@ const NAMES = { runOptimizations: '_ZNK3art18OptimizingCompiler16RunOptimizationsEPNS_6HGraphEPNS_13CodeGeneratorERKNS_18DexCompilationUnitEPNS_12PassObserverE', // Candidate exported signatures from instruction_builder.cc. Only use if // this exact ELF symbol exists on the running device. - fieldInstance: '_ZN3art19HInstructionBuilder24BuildInstanceFieldAccessERKNS_11InstructionEjbm', + fieldInstance: '_ZN3art19HInstructionBuilder24BuildInstanceFieldAccessERKNS_11InstructionEjb', fieldStatic: '_ZN3art19HInstructionBuilder22BuildStaticFieldAccessERKNS_11InstructionEjb' }; function getExport(module, exactName) { From 376f3f5b997316e984e9bb1ee9da1cd7be520b74 Mon Sep 17 00:00:00 2001 From: Muhtasham Nawr al-Mahmud <72372229+mnalmahmud@users.noreply.github.com> Date: Fri, 20 Nov 2026 15:08:15 +0600 Subject: [PATCH 021/129] research: inspect field HInstruction append pointers and candidate vtables on API33 --- art-fieldwatch-phase1/README.md | 21 ++++ .../ci/art-binary-inventory.sh | 4 + art-fieldwatch-phase1/ci/smoke_test.py | 18 +++ art-fieldwatch-phase1/jit-boundary-probe.js | 104 +++++++++++++++++- 4 files changed, 142 insertions(+), 5 deletions(-) diff --git a/art-fieldwatch-phase1/README.md b/art-fieldwatch-phase1/README.md index 6155846..61012c5 100644 --- a/art-fieldwatch-phase1/README.md +++ b/art-fieldwatch-phase1/README.md @@ -61,3 +61,24 @@ 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. diff --git a/art-fieldwatch-phase1/ci/art-binary-inventory.sh b/art-fieldwatch-phase1/ci/art-binary-inventory.sh index 777edd7..270600f 100644 --- a/art-fieldwatch-phase1/ci/art-binary-inventory.sh +++ b/art-fieldwatch-phase1/ci/art-binary-inventory.sh @@ -25,6 +25,10 @@ abi="$(adb shell getprop ro.product.cpu.abi | tr -d '\r')" 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 "-- summary --" if readelf -SW "$tmp/$library" | grep -q ' \.symtab '; then echo 'full-symbol-table=present' diff --git a/art-fieldwatch-phase1/ci/smoke_test.py b/art-fieldwatch-phase1/ci/smoke_test.py index 5d29b3b..7696a5f 100644 --- a/art-fieldwatch-phase1/ci/smoke_test.py +++ b/art-fieldwatch-phase1/ci/smoke_test.py @@ -121,6 +121,24 @@ def main(): 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}') + # Diagnostic discovery: whether the device exports/inlines the + # append boundary is not assumed. If hooked but silent, report failure. + if append_hooks and not nodes: + raise AssertionError('IR append hook installed but no field-context callbacks') + 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",[])}') record('host','PASS: Frida attach + ART discovery + fixture warmup') if __name__ == '__main__': diff --git a/art-fieldwatch-phase1/jit-boundary-probe.js b/art-fieldwatch-phase1/jit-boundary-probe.js index 8d43e0b..4d218c5 100644 --- a/art-fieldwatch-phase1/jit-boundary-probe.js +++ b/art-fieldwatch-phase1/jit-boundary-probe.js @@ -11,6 +11,20 @@ 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; +const knownFieldVtables = new Map(); +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'); @@ -31,7 +45,9 @@ const NAMES = { // 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' + fieldStatic: '_ZN3art19HInstructionBuilder22BuildStaticFieldAccessERKNS_11InstructionEjb', + appendInstruction: '_ZN3art19HInstructionBuilder17AppendInstructionEPNS_12HInstructionE', + addInstruction: '_ZN3art11HBasicBlock14AddInstructionEPNS_12HInstructionE' }; function getExport(module, exactName) { const address = module.findExportByName(exactName); @@ -179,7 +195,9 @@ function attachFieldBuilder(access, site) { const active = compiling.get(thread); if (!active) return; const ordinal = ++fieldCounts[access]; - if (ordinal > FIELD_SAMPLE_LIMIT) return; + this.fieldThread = thread; + this.previousFieldBuilder = activeFieldBuilder.get(thread); + this.hasFieldBuilder = true; const instruction = args[1]; let opcode = null; let fieldIndexRaw = null; @@ -196,8 +214,16 @@ function attachFieldBuilder(access, site) { graphCandidate: activeGraphBuild.get(thread) || null, dexPc: args[2].toUInt32(), isPut: args[3].toInt32() !== 0, opcode, fieldIndexRaw, ordinal}; - send(event); - log('FIELD_BUILD ' + JSON.stringify(event)); + activeFieldBuilder.set(thread, {...event, builder: args[0].toString()}); + 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); @@ -209,6 +235,61 @@ function attachFieldBuilder(access, site) { 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; + const field = activeFieldBuilder.get(thread); + if (!field || (source === 'append' && args[0].toString() !== field.builder)) return; + const ordinal = ++observedFieldNodeCandidates; + if (ordinal > FIELD_NODE_SAMPLE_LIMIT) return; + const node = args[1].toString(); + 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; + } +} function main() { const api = sdkLevel(); log('pid=' + Process.id + ' arch=' + Process.arch + @@ -221,7 +302,8 @@ function main() { for (const name of [NAMES.internal, NAMES.publicCompile, NAMES.compiler, NAMES.instance, NAMES.buildGraph, NAMES.runOptimizations, NAMES.fieldInstance, - NAMES.fieldStatic, 'jit_load']) { + NAMES.fieldStatic, NAMES.appendInstruction, + NAMES.addInstruction, 'jit_load']) { try { const site = getExport(module, name); if (site) log('export=' + module.name + ' name=' + name + @@ -277,6 +359,18 @@ function main() { if (site) attachFieldBuilder(access, site); else log('field-builder-not-exported=' + access); } + discoverFieldVtables(compiler); + // Prefer the builder's own out-of-line append; if absent use + // the HBasicBlock entry point. Both may be inlined on other builds. + const append = getExport(compiler, NAMES.appendInstruction); + const add = getExport(compiler, NAMES.addInstruction); + if (append && attachFieldNodeCandidate(append, 'append')) { + log('ir-append-mode=instruction-builder'); + } else if (add && attachFieldNodeCandidate(add, 'basic-block')) { + log('ir-append-mode=basic-block'); + } else { + log('ir-append-mode=not-exported-or-not-hookable'); + } } else { log('graph-boundaries=disabled (unverified binary profile)'); } From 1f9b9282afee3c2fee9d417ecbe9efacaae12385 Mon Sep 17 00:00:00 2001 From: Muhtasham Nawr al-Mahmud <72372229+mnalmahmud@users.noreply.github.com> Date: Fri, 20 Nov 2026 15:20:07 +0600 Subject: [PATCH 022/129] research: observe field IR through basic-block insertion and virtual Accept visitors --- art-fieldwatch-phase1/README.md | 18 +++++ art-fieldwatch-phase1/ci/smoke_test.py | 16 +++-- art-fieldwatch-phase1/jit-boundary-probe.js | 80 ++++++++++++++++++--- 3 files changed, 99 insertions(+), 15 deletions(-) diff --git a/art-fieldwatch-phase1/README.md b/art-fieldwatch-phase1/README.md index 61012c5..5bf6755 100644 --- a/art-fieldwatch-phase1/README.md +++ b/art-fieldwatch-phase1/README.md @@ -82,3 +82,21 @@ 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. diff --git a/art-fieldwatch-phase1/ci/smoke_test.py b/art-fieldwatch-phase1/ci/smoke_test.py index 7696a5f..daa5213 100644 --- a/art-fieldwatch-phase1/ci/smoke_test.py +++ b/art-fieldwatch-phase1/ci/smoke_test.py @@ -129,16 +129,24 @@ def main(): 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}') - # Diagnostic discovery: whether the device exports/inlines the - # append boundary is not assumed. If hooked but silent, report failure. - if append_hooks and not nodes: - raise AssertionError('IR append hook installed but no field-context callbacks') + 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') record('host','PASS: Frida attach + ART discovery + fixture warmup') if __name__ == '__main__': diff --git a/art-fieldwatch-phase1/jit-boundary-probe.js b/art-fieldwatch-phase1/jit-boundary-probe.js index 4d218c5..933d735 100644 --- a/art-fieldwatch-phase1/jit-boundary-probe.js +++ b/art-fieldwatch-phase1/jit-boundary-probe.js @@ -14,6 +14,9 @@ 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(); const knownFieldVtables = new Map(); const FIELD_VTABLE_SYMBOLS = [ ['HInstanceFieldGet', '_ZTVN3art17HInstanceFieldGetE'], @@ -145,6 +148,8 @@ function attachGraphBoundary(layer, site) { activeGraphBuild.set(this.nativeThread, this.graphCandidate); } else { // const OptimizingCompiler* this, HGraph*, CodeGenerator*, ... + this.previousOptimization = optimizationByThread.get(this.nativeThread); + optimizationByThread.set(this.nativeThread, args[1].toString()); this.graph = args[1].toString(); const previous = builtByThread.get(this.nativeThread); const matches = previous && previous.graphCandidate !== null @@ -161,6 +166,11 @@ function attachGraphBoundary(layer, site) { } }, onLeave(_retval) { + if (layer === 'pre_opt') { + 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); @@ -259,11 +269,17 @@ function attachFieldNodeCandidate(site, source) { Interceptor.attach(site.address, { onEnter(args) { const thread = this.threadId; + insertionCounts[source]++; const field = activeFieldBuilder.get(thread); - if (!field || (source === 'append' && args[0].toString() !== field.builder)) return; + 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; - const node = args[1].toString(); let vtable = null; let kind = null; try { @@ -290,6 +306,51 @@ function attachFieldNodeCandidate(site, source) { 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; + if (ordinal > FIELD_NODE_SAMPLE_LIMIT) return; + 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; + 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: optimizationByThread.has(thread) ? 'optimizing' : + (activeGraphBuild.has(thread) ? 'building' : 'other')}; + 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); +} function main() { const api = sdkLevel(); log('pid=' + Process.id + ' arch=' + Process.arch + @@ -360,17 +421,14 @@ function main() { else log('field-builder-not-exported=' + access); } discoverFieldVtables(compiler); - // Prefer the builder's own out-of-line append; if absent use - // the HBasicBlock entry point. Both may be inlined on other builds. + // 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); - if (append && attachFieldNodeCandidate(append, 'append')) { - log('ir-append-mode=instruction-builder'); - } else if (add && attachFieldNodeCandidate(add, 'basic-block')) { - log('ir-append-mode=basic-block'); - } else { - log('ir-append-mode=not-exported-or-not-hookable'); - } + 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); } else { log('graph-boundaries=disabled (unverified binary profile)'); } From bf8721a4875427347d3363b8ebdd32b4cee198da Mon Sep 17 00:00:00 2001 From: Muhtasham Nawr al-Mahmud <72372229+mnalmahmud@users.noreply.github.com> Date: Fri, 20 Nov 2026 15:35:11 +0600 Subject: [PATCH 023/129] research: track FieldIRTarget get/set IR nodes and candidate LSE removals --- art-fieldwatch-phase1/README.md | 29 ++++ .../ci/art-binary-inventory.sh | 4 + art-fieldwatch-phase1/ci/smoke_test.py | 22 +++ art-fieldwatch-phase1/jit-boundary-probe.js | 142 +++++++++++++++++- 4 files changed, 192 insertions(+), 5 deletions(-) diff --git a/art-fieldwatch-phase1/README.md b/art-fieldwatch-phase1/README.md index 5bf6755..31c991d 100644 --- a/art-fieldwatch-phase1/README.md +++ b/art-fieldwatch-phase1/README.md @@ -100,3 +100,32 @@ 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 diff --git a/art-fieldwatch-phase1/ci/art-binary-inventory.sh b/art-fieldwatch-phase1/ci/art-binary-inventory.sh index 270600f..71c810a 100644 --- a/art-fieldwatch-phase1/ci/art-binary-inventory.sh +++ b/art-fieldwatch-phase1/ci/art-binary-inventory.sh @@ -29,6 +29,10 @@ abi="$(adb shell getprop ro.product.cpu.abi | tr -d '\r')" 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 "-- 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 "-- summary --" if readelf -SW "$tmp/$library" | grep -q ' \.symtab '; then echo 'full-symbol-table=present' diff --git a/art-fieldwatch-phase1/ci/smoke_test.py b/art-fieldwatch-phase1/ci/smoke_test.py index daa5213..2bc44a9 100644 --- a/art-fieldwatch-phase1/ci/smoke_test.py +++ b/art-fieldwatch-phase1/ci/smoke_test.py @@ -147,6 +147,28 @@ def main(): 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 not targets: + raise AssertionError('FieldIRTarget.test DEX pattern not identified') + if not summaries: + raise AssertionError('No compiler summary for FieldIRTarget.test') + if not {'HInstanceFieldGet','HInstanceFieldSet'}.issubset(set(target_kinds)): + raise AssertionError('FieldIRTarget.test get/set IR nodes not both seen') + # Mutation/LSE hookability is a new hypothesis; missing exports are + # recorded, but do not invalidate the verified field-node capture. record('host','PASS: Frida attach + ART discovery + fixture warmup') if __name__ == '__main__': diff --git a/art-fieldwatch-phase1/jit-boundary-probe.js b/art-fieldwatch-phase1/jit-boundary-probe.js index 933d735..5346c8e 100644 --- a/art-fieldwatch-phase1/jit-boundary-probe.js +++ b/art-fieldwatch-phase1/jit-boundary-probe.js @@ -18,6 +18,21 @@ let observedFieldAccepts = 0; const insertionCounts = {append: 0, 'basic-block': 0}; const optimizationByThread = new Map(); const knownFieldVtables = new Map(); +const targetDexByMethod = new Map(); +const targetMethodPointers = new Set(); +const targetStates = new Map(); +const targetReportLimit = 36; +const lseByThread = new Map(); +const mutationHookCounts = {replace: 0, remove: 0, lse: 0}; +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'], @@ -50,7 +65,13 @@ const NAMES = { fieldInstance: '_ZN3art19HInstructionBuilder24BuildInstanceFieldAccessERKNS_11InstructionEjb', fieldStatic: '_ZN3art19HInstructionBuilder22BuildStaticFieldAccessERKNS_11InstructionEjb', appendInstruction: '_ZN3art19HInstructionBuilder17AppendInstructionEPNS_12HInstructionE', - addInstruction: '_ZN3art11HBasicBlock14AddInstructionEPNS_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_', + removeInstruction: '_ZN3art11HBasicBlock17RemoveInstructionEPNS_12HInstructionEb', + lseRun: '_ZN3art20LoadStoreElimination3RunEv', + lseRunBool: '_ZN3art20LoadStoreElimination3RunEb' }; function getExport(module, exactName) { const address = module.findExportByName(exactName); @@ -96,6 +117,12 @@ function attach(layer, site) { if (layer === 'compiler') { this.nativeThread = this.threadId; this.previousCompilation = compiling.get(this.nativeThread); + this.previousTargetState = targetStates.get(this.nativeThread); + targetStates.set(this.nativeThread, { + method: this.method, kind: this.compilationKind, + seenVisits: new Set(), seenKinds: new Set(), uniqueNodes: new Set(), + visitsByPhase: {}, mutations: [], reported: 0 + }); compiling.set(this.nativeThread, {method: this.method, kind: this.compilationKind}); builtByThread.delete(this.nativeThread); } @@ -105,6 +132,23 @@ function attach(layer, site) { }, onLeave(ret) { if (layer === 'compiler') { + const state = targetStates.get(this.nativeThread); + 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, + 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); + } + 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); @@ -225,6 +269,22 @@ function attachFieldBuilder(access, site) { dexPc: args[2].toUInt32(), isPut: args[3].toInt32() !== 0, opcode, fieldIndexRaw, ordinal}; activeFieldBuilder.set(thread, {...event, builder: args[0].toString()}); + // FieldIRTarget.test(int): DEX 22c iput at PC 0 and iget at PC 2, + // both referencing field_idx 0 in the dedicated Java fixture. + if (access === 'instance' && fieldIndexRaw === 0 && + ((opcode === 0x59 && event.dexPc === 0) || + (opcode === 0x52 && event.dexPc === 2))) { + const evidence = targetDexByMethod.get(active.method) || 0; + const bits = evidence | (opcode === 0x59 ? 1 : 2); + targetDexByMethod.set(active.method, bits); + if (bits === 3 && !targetMethodPointers.has(active.method)) { + targetMethodPointers.add(active.method); + const identified = {type: 'artwatch-target-dex', method: active.method, + dexPattern: 'iput@0,iget@2,field_idx=0'}; + send(identified); + log('TARGET_DEX ' + JSON.stringify(identified)); + } + } if (ordinal <= FIELD_SAMPLE_LIMIT) { send(event); log('FIELD_BUILD ' + JSON.stringify(event)); @@ -326,19 +386,36 @@ function attachFieldAccept(compiler) { const compilation = compiling.get(thread); if (!compilation) return; const ordinal = ++observedFieldAccepts; - if (ordinal > FIELD_NODE_SAMPLE_LIMIT) return; 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; + const phase = optimizationByThread.has(thread) ? 'optimizing' : + (activeGraphBuild.has(thread) ? 'building' : 'other'); + 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: optimizationByThread.has(thread) ? 'optimizing' : - (activeGraphBuild.has(thread) ? 'building' : 'other')}; + phase}; send(event); log('IR_VISIT ' + JSON.stringify(event)); } @@ -351,6 +428,50 @@ function attachFieldAccept(compiler) { } 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 || !targetMethodPointers.has(compilation.method)) return; + mutationHookCounts[op]++; + if (op === 'lse') { + this.lseThread = thread; + this.lsePrevious = lseByThread.get(thread); + lseByThread.set(thread, true); + reportTargetEvent(state, {type:'artwatch-target-lse-enter', + method:compilation.method, compilationKind:compilation.kind, + thread}); + return; + } + const instruction = op === 'replace' ? args[0] : args[1]; + const kind = fieldKind(instruction); + if (!kind) return; + const record = {op, kind, node: instruction.toString(), + substitute: op === 'replace' ? args[1].toString() : null, + duringLse: lseByThread.has(thread), + duringOptimizations: optimizationByThread.has(thread)}; + 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.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; } +} function main() { const api = sdkLevel(); log('pid=' + Process.id + ' arch=' + Process.arch + @@ -364,7 +485,9 @@ function main() { NAMES.compiler, NAMES.instance, NAMES.buildGraph, NAMES.runOptimizations, NAMES.fieldInstance, NAMES.fieldStatic, NAMES.appendInstruction, - NAMES.addInstruction, 'jit_load']) { + NAMES.addInstruction, NAMES.replaceWith, + NAMES.removeInstruction, NAMES.lseRun, + NAMES.lseRunBool, 'jit_load']) { try { const site = getExport(module, name); if (site) log('export=' + module.name + ' name=' + name + @@ -429,6 +552,15 @@ function main() { const addHook = add ? attachFieldNodeCandidate(add, 'basic-block') : false; log('ir-insertion-hooks=' + JSON.stringify({append: appendHook, add: addHook})); attachFieldAccept(compiler); + for (const [op, names] of [ + ['replace', [NAMES.replaceWith]], + ['remove', [NAMES.removeInstruction]], + ['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)'); } From ff1465fba290458c65bb63e4f84324e55dc90ab9 Mon Sep 17 00:00:00 2001 From: Muhtasham Nawr al-Mahmud <72372229+mnalmahmud@users.noreply.github.com> Date: Fri, 20 Nov 2026 15:47:09 +0600 Subject: [PATCH 024/129] research: verify load-store elimination in non-debuggable optimized ART JIT --- .github/workflows/art-fieldwatch-phase1.yml | 21 +++++++-- art-fieldwatch-phase1/README.md | 30 +++++++++++++ .../ci/run-emulator-smoke.sh | 9 +++- art-fieldwatch-phase1/ci/smoke_test.py | 16 +++++++ art-fieldwatch-phase1/jit-boundary-probe.js | 44 ++++++++++++++++--- art-fieldwatch-phase1/test/app/build.gradle | 9 ++++ .../example/artfieldwatch/MainActivity.java | 6 +++ 7 files changed, 125 insertions(+), 10 deletions(-) mode change 100755 => 100644 art-fieldwatch-phase1/ci/run-emulator-smoke.sh diff --git a/.github/workflows/art-fieldwatch-phase1.yml b/.github/workflows/art-fieldwatch-phase1.yml index 8c6778d..8feead1 100644 --- a/.github/workflows/art-fieldwatch-phase1.yml +++ b/.github/workflows/art-fieldwatch-phase1.yml @@ -24,9 +24,16 @@ jobs: strategy: fail-fast: false matrix: - api: [33, 34] + 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' steps: @@ -64,7 +71,15 @@ jobs: - uses: gradle/actions/setup-gradle@v4 with: gradle-version: '8.10.2' - - run: gradle -p art-fieldwatch-phase1/test :app:assembleDebug --no-daemon + - name: Build selected APK variant + shell: bash + run: | + case "$ARTWATCH_BUILD_VARIANT" in + debug) task=assembleDebug ;; + release) task=assembleRelease ;; + *) exit 1 ;; + esac + gradle -p art-fieldwatch-phase1/test ":app:$task" --no-daemon - run: python3 -m pip install 'frida==17.27.1' - uses: reactivecircus/android-emulator-runner@v2 with: @@ -78,7 +93,7 @@ jobs: - uses: actions/upload-artifact@v4 if: always() with: - name: artwatch-api${{ matrix.api }}-x86_64 + name: artwatch-api${{ matrix.api }}-x86_64-${{ matrix.variant }} path: /tmp/artwatch-logs/ if-no-files-found: ignore android-arm64: diff --git a/art-fieldwatch-phase1/README.md b/art-fieldwatch-phase1/README.md index 31c991d..f548506 100644 --- a/art-fieldwatch-phase1/README.md +++ b/art-fieldwatch-phase1/README.md @@ -129,3 +129,33 @@ 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 diff --git a/art-fieldwatch-phase1/ci/run-emulator-smoke.sh b/art-fieldwatch-phase1/ci/run-emulator-smoke.sh old mode 100755 new mode 100644 index 6fa7b63..17a63ec --- a/art-fieldwatch-phase1/ci/run-emulator-smoke.sh +++ b/art-fieldwatch-phase1/ci/run-emulator-smoke.sh @@ -3,7 +3,14 @@ set -euo pipefail mkdir -p "${ARTWATCH_LOG_DIR:-/tmp/artwatch-logs}" adb root adb wait-for-device -adb install -r art-fieldwatch-phase1/test/app/build/outputs/apk/debug/app-debug.apk +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 diff --git a/art-fieldwatch-phase1/ci/smoke_test.py b/art-fieldwatch-phase1/ci/smoke_test.py index 2bc44a9..a38da84 100644 --- a/art-fieldwatch-phase1/ci/smoke_test.py +++ b/art-fieldwatch-phase1/ci/smoke_test.py @@ -49,6 +49,10 @@ def main(): 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 'WARMUP_FAILED' in logs.stdout or 'WARMUP_DONE' not in logs.stdout: raise AssertionError('APK fixture warmup failed or timed out') hooked = [e['text'] for e in messages if e['kind']=='frida' and @@ -169,6 +173,18 @@ def main(): raise AssertionError('FieldIRTarget.test get/set IR nodes not both seen') # 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') record('host','PASS: Frida attach + ART discovery + fixture warmup') if __name__ == '__main__': diff --git a/art-fieldwatch-phase1/jit-boundary-probe.js b/art-fieldwatch-phase1/jit-boundary-probe.js index 5346c8e..6ba7e3f 100644 --- a/art-fieldwatch-phase1/jit-boundary-probe.js +++ b/art-fieldwatch-phase1/jit-boundary-probe.js @@ -24,6 +24,8 @@ const targetStates = new Map(); const targetReportLimit = 36; const lseByThread = new Map(); const mutationHookCounts = {replace: 0, remove: 0, lse: 0}; +let lseTraceEmitted = 0; +const LSE_TRACE_LIMIT = 80; function fieldKind(ptr) { try { return knownFieldVtables.get(ptr.readPointer().toString()) || null; } catch (_) { return null; } @@ -121,7 +123,8 @@ function attach(layer, site) { targetStates.set(this.nativeThread, { method: this.method, kind: this.compilationKind, seenVisits: new Set(), seenKinds: new Set(), uniqueNodes: new Set(), - visitsByPhase: {}, mutations: [], reported: 0 + visitsByPhase: {}, mutations: [], reported: 0, + optimizationEntries: 0, lseInvocations: 0 }); compiling.set(this.nativeThread, {method: this.method, kind: this.compilationKind}); builtByThread.delete(this.nativeThread); @@ -147,6 +150,14 @@ function attach(layer, site) { ' kinds=' + [...state.seenKinds].join(',') + ' mutations=' + state.mutations.length); } + if (state && this.ordinal <= SAMPLE_LIMIT) { + 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 (this.previousTargetState) targetStates.set(this.nativeThread, this.previousTargetState); else targetStates.delete(this.nativeThread); if (this.previousCompilation) compiling.set(this.nativeThread, this.previousCompilation); @@ -194,6 +205,8 @@ function attachGraphBoundary(layer, site) { // 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 @@ -437,17 +450,30 @@ function attachMutationObserver(site, op) { const thread = this.threadId; const compilation = compiling.get(thread); const state = targetStates.get(thread); - if (!compilation || !state || !targetMethodPointers.has(compilation.method)) return; + if (!compilation || !state) return; mutationHookCounts[op]++; if (op === 'lse') { this.lseThread = thread; this.lsePrevious = lseByThread.get(thread); lseByThread.set(thread, true); - reportTargetEvent(state, {type:'artwatch-target-lse-enter', - method:compilation.method, compilationKind:compilation.kind, - thread}); + 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; } + if (!targetMethodPointers.has(compilation.method)) return; const instruction = op === 'replace' ? args[0] : args[1]; const kind = fieldKind(instruction); if (!kind) return; @@ -460,8 +486,14 @@ function attachMutationObserver(site, op) { method:compilation.method, compilationKind:compilation.kind, thread, ...record}); }, - onLeave(_retval) { + onLeave(retval) { if (op !== 'lse' || this.lseThread === undefined) return; + if (this.lseReport) { + const event = {type:'artwatch-lse', phase:'exit', + 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); } diff --git a/art-fieldwatch-phase1/test/app/build.gradle b/art-fieldwatch-phase1/test/app/build.gradle index e9e2183..881dc71 100644 --- a/art-fieldwatch-phase1/test/app/build.gradle +++ b/art-fieldwatch-phase1/test/app/build.gradle @@ -11,4 +11,13 @@ android { versionCode 1 versionName '0.1' } + 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/java/com/example/artfieldwatch/MainActivity.java b/art-fieldwatch-phase1/test/app/src/main/java/com/example/artfieldwatch/MainActivity.java index fd1a2c8..646d98a 100644 --- a/art-fieldwatch-phase1/test/app/src/main/java/com/example/artfieldwatch/MainActivity.java +++ b/art-fieldwatch-phase1/test/app/src/main/java/com/example/artfieldwatch/MainActivity.java @@ -11,12 +11,18 @@ protected void onCreate(Bundle state) { TextView label = new TextView(this); label.setText("ART Fieldwatch: field access warmup"); setContentView(label); + final boolean appDebuggable = + (getApplicationInfo().flags & android.content.pm.ApplicationInfo.FLAG_DEBUGGABLE) != 0; + Log.i("ARTWATCH_CI","APP_DEBUGGABLE=" + appDebuggable); new Thread(() -> { 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) accumulator += FieldIRTarget.warmup(1200000); Log.i("ARTWATCH_CI","WARMUP_DONE checksum=" + accumulator); } catch (Throwable t) { Log.e("ARTWATCH_CI","WARMUP_FAILED",t); From da99d143faffc249dfe565b3c04bb07695e0387f Mon Sep 17 00:00:00 2001 From: Muhtasham Nawr al-Mahmud <72372229+mnalmahmud@users.noreply.github.com> Date: Fri, 20 Nov 2026 16:06:04 +0600 Subject: [PATCH 025/129] ci: fix release target-SDK lint and make field DEX fingerprint index-independent --- art-fieldwatch-phase1/README.md | 16 +++++++++++++++ art-fieldwatch-phase1/jit-boundary-probe.js | 22 +++++++++++++-------- art-fieldwatch-phase1/test/app/build.gradle | 6 ++++++ 3 files changed, 36 insertions(+), 8 deletions(-) diff --git a/art-fieldwatch-phase1/README.md b/art-fieldwatch-phase1/README.md index f548506..40d37a6 100644 --- a/art-fieldwatch-phase1/README.md +++ b/art-fieldwatch-phase1/README.md @@ -159,3 +159,19 @@ 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. diff --git a/art-fieldwatch-phase1/jit-boundary-probe.js b/art-fieldwatch-phase1/jit-boundary-probe.js index 6ba7e3f..3a2ef1a 100644 --- a/art-fieldwatch-phase1/jit-boundary-probe.js +++ b/art-fieldwatch-phase1/jit-boundary-probe.js @@ -282,18 +282,24 @@ function attachFieldBuilder(access, site) { dexPc: args[2].toUInt32(), isPut: args[3].toInt32() !== 0, opcode, fieldIndexRaw, ordinal}; activeFieldBuilder.set(thread, {...event, builder: args[0].toString()}); - // FieldIRTarget.test(int): DEX 22c iput at PC 0 and iget at PC 2, - // both referencing field_idx 0 in the dedicated Java fixture. - if (access === 'instance' && fieldIndexRaw === 0 && + // Match the same field index in iput@0 and iget@2 without assuming + // that DEX field indices are stable when other app code is modified. + if (access === 'instance' && fieldIndexRaw !== null && ((opcode === 0x59 && event.dexPc === 0) || (opcode === 0x52 && event.dexPc === 2))) { - const evidence = targetDexByMethod.get(active.method) || 0; - const bits = evidence | (opcode === 0x59 ? 1 : 2); - targetDexByMethod.set(active.method, bits); + let byField = targetDexByMethod.get(active.method); + if (!byField) { + byField = new Map(); + targetDexByMethod.set(active.method, byField); + } + const bits = (byField.get(fieldIndexRaw) || 0) | + (opcode === 0x59 ? 1 : 2); + byField.set(fieldIndexRaw, bits); if (bits === 3 && !targetMethodPointers.has(active.method)) { targetMethodPointers.add(active.method); - const identified = {type: 'artwatch-target-dex', method: active.method, - dexPattern: 'iput@0,iget@2,field_idx=0'}; + const identified = {type: 'artwatch-target-dex', + method: active.method, fieldIndexRaw, + dexPattern: 'iput@0,iget@2,same-field-index'}; send(identified); log('TARGET_DEX ' + JSON.stringify(identified)); } diff --git a/art-fieldwatch-phase1/test/app/build.gradle b/art-fieldwatch-phase1/test/app/build.gradle index 881dc71..e5e7c69 100644 --- a/art-fieldwatch-phase1/test/app/build.gradle +++ b/art-fieldwatch-phase1/test/app/build.gradle @@ -11,6 +11,12 @@ android { 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' + } buildTypes { release { // Keep the build non-debuggable while signing it for emulator installation. From 2d37ccbc7d04b97bec1333613073b4ce713c409f Mon Sep 17 00:00:00 2001 From: Muhtasham Nawr al-Mahmud <72372229+mnalmahmud@users.noreply.github.com> Date: Fri, 20 Nov 2026 16:24:05 +0600 Subject: [PATCH 026/129] research: compare shipped DEX and observe field mutation boundaries across release JIT --- .github/workflows/art-fieldwatch-phase1.yml | 3 ++ art-fieldwatch-phase1/README.md | 36 +++++++++++++++++ art-fieldwatch-phase1/ci/dex-inventory.sh | 30 ++++++++++++++ art-fieldwatch-phase1/ci/smoke_test.py | 30 +++++++++++--- art-fieldwatch-phase1/jit-boundary-probe.js | 45 +++++++++++++++++---- 5 files changed, 130 insertions(+), 14 deletions(-) create mode 100644 art-fieldwatch-phase1/ci/dex-inventory.sh diff --git a/.github/workflows/art-fieldwatch-phase1.yml b/.github/workflows/art-fieldwatch-phase1.yml index 8feead1..6735339 100644 --- a/.github/workflows/art-fieldwatch-phase1.yml +++ b/.github/workflows/art-fieldwatch-phase1.yml @@ -18,6 +18,7 @@ jobs: - run: node --check art-fieldwatch-phase1/jit-boundary-probe.js - run: python3 -m py_compile art-fieldwatch-phase1/ci/smoke_test.py - run: bash -n art-fieldwatch-phase1/ci/run-emulator-smoke.sh + - run: bash -n art-fieldwatch-phase1/ci/dex-inventory.sh android: runs-on: ubuntu-latest timeout-minutes: 35 @@ -80,6 +81,8 @@ jobs: *) exit 1 ;; esac gradle -p art-fieldwatch-phase1/test ":app:$task" --no-daemon + - 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: diff --git a/art-fieldwatch-phase1/README.md b/art-fieldwatch-phase1/README.md index 40d37a6..3307b29 100644 --- a/art-fieldwatch-phase1/README.md +++ b/art-fieldwatch-phase1/README.md @@ -175,3 +175,39 @@ 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 diff --git a/art-fieldwatch-phase1/ci/dex-inventory.sh b/art-fieldwatch-phase1/ci/dex-inventory.sh new file mode 100644 index 0000000..18f42d5 --- /dev/null +++ b/art-fieldwatch-phase1/ci/dex-inventory.sh @@ -0,0 +1,30 @@ +#!/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" +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 --" +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/smoke_test.py b/art-fieldwatch-phase1/ci/smoke_test.py index a38da84..a098f3a 100644 --- a/art-fieldwatch-phase1/ci/smoke_test.py +++ b/art-fieldwatch-phase1/ci/smoke_test.py @@ -165,12 +165,16 @@ def main(): f'target IR={len(target_ir)} kinds={target_kinds} ' f'target summaries={len(summaries)} ' f'mutation hooks={mutation_hooks} mutation events={len(mutations)}') - if not targets: - raise AssertionError('FieldIRTarget.test DEX pattern not identified') - if not summaries: - raise AssertionError('No compiler summary for FieldIRTarget.test') - if not {'HInstanceFieldGet','HInstanceFieldSet'}.issubset(set(target_kinds)): - raise AssertionError('FieldIRTarget.test get/set IR nodes not both seen') + 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 @@ -185,6 +189,20 @@ def main(): 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') + 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') record('host','PASS: Frida attach + ART discovery + fixture warmup') if __name__ == '__main__': diff --git a/art-fieldwatch-phase1/jit-boundary-probe.js b/art-fieldwatch-phase1/jit-boundary-probe.js index 3a2ef1a..8cf0a98 100644 --- a/art-fieldwatch-phase1/jit-boundary-probe.js +++ b/art-fieldwatch-phase1/jit-boundary-probe.js @@ -23,9 +23,11 @@ const targetMethodPointers = new Set(); const targetStates = new Map(); const targetReportLimit = 36; const lseByThread = new Map(); -const mutationHookCounts = {replace: 0, remove: 0, lse: 0}; +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; } @@ -71,7 +73,9 @@ const NAMES = { // 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', lseRun: '_ZN3art20LoadStoreElimination3RunEv', lseRunBool: '_ZN3art20LoadStoreElimination3RunEb' }; @@ -120,6 +124,7 @@ function attach(layer, site) { 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, seenVisits: new Set(), seenKinds: new Set(), uniqueNodes: new Set(), @@ -151,6 +156,12 @@ function attach(layer, site) { ' mutations=' + state.mutations.length); } 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), @@ -460,6 +471,8 @@ function attachMutationObserver(site, op) { 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++; @@ -479,23 +492,36 @@ function attachMutationObserver(site, op) { } return; } - if (!targetMethodPointers.has(compilation.method)) 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 record = {op, kind, node: instruction.toString(), - substitute: op === 'replace' ? args[1].toString() : null, + substitute: op === 'replace' ? args[1].toString() : + (op === 'replace_remove' ? args[2].toString() : null), duringLse: lseByThread.has(thread), duringOptimizations: optimizationByThread.has(thread)}; - state.mutations.push(record); - reportTargetEvent(state, {type:'artwatch-ir-mutation', - method:compilation.method, compilationKind:compilation.kind, - thread, ...record}); + 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)); @@ -524,7 +550,8 @@ function main() { NAMES.runOptimizations, NAMES.fieldInstance, NAMES.fieldStatic, NAMES.appendInstruction, NAMES.addInstruction, NAMES.replaceWith, - NAMES.removeInstruction, NAMES.lseRun, + NAMES.replaceAndRemove, NAMES.removeInstruction, + NAMES.removeInstructionOrPhi, NAMES.lseRun, NAMES.lseRunBool, 'jit_load']) { try { const site = getExport(module, name); @@ -592,7 +619,9 @@ function main() { attachFieldAccept(compiler); 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); From d055b6b4b0eaafaf4249a09f512ee6d5342ee843 Mon Sep 17 00:00:00 2001 From: Muhtasham Nawr al-Mahmud <72372229+mnalmahmud@users.noreply.github.com> Date: Fri, 20 Nov 2026 16:47:14 +0600 Subject: [PATCH 027/129] research: retain release DEX iget through identity helper and inspect backend field lowering --- art-fieldwatch-phase1/README.md | 28 ++++++ art-fieldwatch-phase1/ci/dex-inventory.sh | 14 +++ art-fieldwatch-phase1/ci/smoke_test.py | 16 ++++ art-fieldwatch-phase1/jit-boundary-probe.js | 93 +++++++++++++++++-- .../example/artfieldwatch/FieldIRTarget.java | 16 +++- 5 files changed, 156 insertions(+), 11 deletions(-) diff --git a/art-fieldwatch-phase1/README.md b/art-fieldwatch-phase1/README.md index 3307b29..8a0401c 100644 --- a/art-fieldwatch-phase1/README.md +++ b/art-fieldwatch-phase1/README.md @@ -211,3 +211,31 @@ 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 diff --git a/art-fieldwatch-phase1/ci/dex-inventory.sh b/art-fieldwatch-phase1/ci/dex-inventory.sh index 18f42d5..eb3945c 100644 --- a/art-fieldwatch-phase1/ci/dex-inventory.sh +++ b/art-fieldwatch-phase1/ci/dex-inventory.sh @@ -23,6 +23,20 @@ if "$analyzer" dex code --class com.example.artfieldwatch.FieldIRTarget "$apk" > 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." + fi else echo "apkanalyzer failed; preserving stderr as diagnostic" cat "$out/fieldir-$variant.stderr" diff --git a/art-fieldwatch-phase1/ci/smoke_test.py b/art-fieldwatch-phase1/ci/smoke_test.py index a098f3a..3707c62 100644 --- a/art-fieldwatch-phase1/ci/smoke_test.py +++ b/art-fieldwatch-phase1/ci/smoke_test.py @@ -189,6 +189,22 @@ def main(): 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' diff --git a/art-fieldwatch-phase1/jit-boundary-probe.js b/art-fieldwatch-phase1/jit-boundary-probe.js index 8cf0a98..a50e4c7 100644 --- a/art-fieldwatch-phase1/jit-boundary-probe.js +++ b/art-fieldwatch-phase1/jit-boundary-probe.js @@ -19,6 +19,9 @@ const insertionCounts = {append: 0, 'basic-block': 0}; const optimizationByThread = new Map(); const knownFieldVtables = new Map(); 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; @@ -76,6 +79,10 @@ const NAMES = { 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' }; @@ -129,7 +136,8 @@ function attach(layer, site) { method: this.method, kind: this.compilationKind, seenVisits: new Set(), seenKinds: new Set(), uniqueNodes: new Set(), visitsByPhase: {}, mutations: [], reported: 0, - optimizationEntries: 0, lseInvocations: 0 + optimizationEntries: 0, lseInvocations: 0, + backendLocations: new Set(), backendEmitted: new Set() }); compiling.set(this.nativeThread, {method: this.method, kind: this.compilationKind}); builtByThread.delete(this.nativeThread); @@ -148,6 +156,8 @@ function attach(layer, site) { 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=' + @@ -293,24 +303,29 @@ function attachFieldBuilder(access, site) { dexPc: args[2].toUInt32(), isPut: args[3].toInt32() !== 0, opcode, fieldIndexRaw, ordinal}; activeFieldBuilder.set(thread, {...event, builder: args[0].toString()}); - // Match the same field index in iput@0 and iget@2 without assuming - // that DEX field indices are stable when other app code is modified. + // 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 && event.dexPc === 0) || - (opcode === 0x52 && event.dexPc === 2))) { + (opcode === 0x59 || opcode === 0x52)) { let byField = targetDexByMethod.get(active.method); if (!byField) { byField = new Map(); targetDexByMethod.set(active.method, byField); } - const bits = (byField.get(fieldIndexRaw) || 0) | - (opcode === 0x59 ? 1 : 2); - byField.set(fieldIndexRaw, bits); - if (bits === 3 && !targetMethodPointers.has(active.method)) { + 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@0,iget@2,same-field-index'}; + dexPattern: 'iput+iget,same-field-index', + putPc: updated.putPc, getPc: updated.getPc}; send(identified); log('TARGET_DEX ' + JSON.stringify(identified)); } @@ -536,6 +551,56 @@ function attachMutationObserver(site, op) { 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; + } +} function main() { const api = sdkLevel(); log('pid=' + Process.id + ' arch=' + Process.arch + @@ -552,6 +617,8 @@ function main() { 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); @@ -617,6 +684,12 @@ function main() { 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]], 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 index f36fff5..58e2394 100644 --- 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 @@ -9,12 +9,26 @@ public int test(int 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; + } + 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 read/write mismatch at " + 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++; } From c0ff3e894cd0d6a0454eba5465b2fd66347964e9 Mon Sep 17 00:00:00 2001 From: Muhtasham Nawr al-Mahmud <72372229+mnalmahmud@users.noreply.github.com> Date: Fri, 20 Nov 2026 17:11:22 +0600 Subject: [PATCH 028/129] research: assert exact LSE-eliminated HInstanceFieldGet never reaches code emission --- art-fieldwatch-phase1/README.md | 40 +++++++++++++++++++++ art-fieldwatch-phase1/ci/smoke_test.py | 29 +++++++++++++++ art-fieldwatch-phase1/jit-boundary-probe.js | 37 ++++++++++++++++++- 3 files changed, 105 insertions(+), 1 deletion(-) diff --git a/art-fieldwatch-phase1/README.md b/art-fieldwatch-phase1/README.md index 8a0401c..f46a8c0 100644 --- a/art-fieldwatch-phase1/README.md +++ b/art-fieldwatch-phase1/README.md @@ -239,3 +239,43 @@ 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. diff --git a/art-fieldwatch-phase1/ci/smoke_test.py b/art-fieldwatch-phase1/ci/smoke_test.py index 3707c62..0cf68c9 100644 --- a/art-fieldwatch-phase1/ci/smoke_test.py +++ b/art-fieldwatch-phase1/ci/smoke_test.py @@ -219,6 +219,35 @@ def main(): 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] + 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'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') record('host','PASS: Frida attach + ART discovery + fixture warmup') if __name__ == '__main__': diff --git a/art-fieldwatch-phase1/jit-boundary-probe.js b/art-fieldwatch-phase1/jit-boundary-probe.js index a50e4c7..388da1e 100644 --- a/art-fieldwatch-phase1/jit-boundary-probe.js +++ b/art-fieldwatch-phase1/jit-boundary-probe.js @@ -165,6 +165,39 @@ function attach(layer, site) { ' 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; + } + const entries = Array.from(lifecycleByNode.values()).map(entry => { + const identity = entry.kind + '@' + entry.node; + return {...entry, 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)) { @@ -516,7 +549,9 @@ function attachMutationObserver(site, op) { substitute: op === 'replace' ? args[1].toString() : (op === 'replace_remove' ? args[2].toString() : null), duringLse: lseByThread.has(thread), - duringOptimizations: optimizationByThread.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, From d639173965f60ffcf55ec0bc22852104bc2df464 Mon Sep 17 00:00:00 2001 From: Muhtasham Nawr al-Mahmud <72372229+mnalmahmud@users.noreply.github.com> Date: Fri, 20 Nov 2026 17:23:16 +0600 Subject: [PATCH 029/129] docs: design side-effecting compiler IR field events and safety gates --- docs/art-fieldwatch/ir-event-probe-design.md | 182 +++++++++++++++++++ 1 file changed, 182 insertions(+) create mode 100644 docs/art-fieldwatch/ir-event-probe-design.md 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. From f97296e0d8d7a1ef1030f672f00991a3687d2e86 Mon Sep 17 00:00:00 2001 From: Muhtasham Nawr al-Mahmud <72372229+mnalmahmud@users.noreply.github.com> Date: Fri, 20 Nov 2026 17:40:03 +0600 Subject: [PATCH 030/129] research: add passive build-ID-gated native ART shadow observer source --- .../ci/build-passive-shim.sh | 19 +++ art-fieldwatch-phase1/native/passive-shadow.c | 136 ++++++++++++++++++ 2 files changed, 155 insertions(+) create mode 100644 art-fieldwatch-phase1/ci/build-passive-shim.sh create mode 100644 art-fieldwatch-phase1/native/passive-shadow.c 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..dbdcac8 --- /dev/null +++ b/art-fieldwatch-phase1/ci/build-passive-shim.sh @@ -0,0 +1,19 @@ +#!/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 + yes | sdkmanager --install "ndk;$version" >/dev/null +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)' | tee "$out/exports.txt" diff --git a/art-fieldwatch-phase1/native/passive-shadow.c b/art-fieldwatch-phase1/native/passive-shadow.c new file mode 100644 index 0000000..39efb22 --- /dev/null +++ b/art-fieldwatch-phase1/native/passive-shadow.c @@ -0,0 +1,136 @@ +// 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 +#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; +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; + if (nh.n_type != NT_GNU_BUILD_ID || + nh.n_namesz < 4 || memcmp(name, "GNU", 4) != 0 || + nh.n_descsz != 20) continue; + static const char digits[] = "0123456789abcdef"; + for (size_t k = 0; k < 20; ++k) { + out[2*k] = digits[desc[k] >> 4]; + out[2*k+1] = digits[desc[k] & 15]; + } + out[40] = '\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. +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; +} +// 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); + return 1; +} +// 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," + "\"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(&rejected, __ATOMIC_RELAXED), + (unsigned long long)__atomic_load_n(&opaque_graph_word, __ATOMIC_RELAXED)); + return n > 0 && (uint32_t)n < length ? 1 : 0; +} From 506354e3fc00fe0eaecf24aec89ec2f0712b74ff Mon Sep 17 00:00:00 2001 From: Muhtasham Nawr al-Mahmud <72372229+mnalmahmud@users.noreply.github.com> Date: Fri, 20 Nov 2026 17:41:09 +0600 Subject: [PATCH 031/129] ci: wire passive native ART shadow observer into API33 JIT smoke --- .github/workflows/art-fieldwatch-phase1.yml | 5 ++ art-fieldwatch-phase1/README.md | 20 ++++++ .../ci/run-emulator-smoke.sh | 9 +++ art-fieldwatch-phase1/ci/smoke_test.py | 32 ++++++++- art-fieldwatch-phase1/jit-boundary-probe.js | 66 +++++++++++++++++++ 5 files changed, 131 insertions(+), 1 deletion(-) diff --git a/.github/workflows/art-fieldwatch-phase1.yml b/.github/workflows/art-fieldwatch-phase1.yml index 6735339..9e16b4c 100644 --- a/.github/workflows/art-fieldwatch-phase1.yml +++ b/.github/workflows/art-fieldwatch-phase1.yml @@ -19,6 +19,7 @@ jobs: - run: python3 -m py_compile art-fieldwatch-phase1/ci/smoke_test.py - 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 @@ -37,6 +38,7 @@ jobs: ARTWATCH_BUILD_VARIANT: ${{ matrix.variant }} ARTWATCH_LOG_DIR: /tmp/artwatch-logs ARTWATCH_REQUIRE_JIT: '1' + ARTWATCH_SHADOW_SHIM: ${{ matrix.api == 33 && '1' || '0' }} steps: - uses: actions/checkout@v4 # Emulator 37.3+ refuses -accel off without an explicit TCG override. @@ -72,6 +74,9 @@ jobs: - 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: | diff --git a/art-fieldwatch-phase1/README.md b/art-fieldwatch-phase1/README.md index f46a8c0..b9543f3 100644 --- a/art-fieldwatch-phase1/README.md +++ b/art-fieldwatch-phase1/README.md @@ -279,3 +279,23 @@ 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. diff --git a/art-fieldwatch-phase1/ci/run-emulator-smoke.sh b/art-fieldwatch-phase1/ci/run-emulator-smoke.sh index 17a63ec..5e259ef 100644 --- a/art-fieldwatch-phase1/ci/run-emulator-smoke.sh +++ b/art-fieldwatch-phase1/ci/run-emulator-smoke.sh @@ -36,6 +36,15 @@ if [ "$ready" -ne 1 ]; then adb shell cat /data/local/tmp/artwatch-frida-server.log || true exit 1 fi +if [[ "${ARTWATCH_SHADOW_SHIM:-0}" == 1 ]]; then + if [[ "$ABI" != x86_64 ]]; then + echo "Native shadow shim supports only x86_64" >&2; exit 1 + fi + native="art-fieldwatch-phase1/native/out/libartwatch_shadow.so" + test -s "$native" || { echo "Missing native shim: $native" >&2; exit 1; } + adb push "$native" /data/local/tmp/libartwatch_shadow.so + adb shell chmod 755 /data/local/tmp/libartwatch_shadow.so +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 diff --git a/art-fieldwatch-phase1/ci/smoke_test.py b/art-fieldwatch-phase1/ci/smoke_test.py index 0cf68c9..57c8acb 100644 --- a/art-fieldwatch-phase1/ci/smoke_test.py +++ b/art-fieldwatch-phase1/ci/smoke_test.py @@ -32,7 +32,12 @@ def main(): record('host','spawned-pid='+str(pid)) session = device.attach(pid) try: - script = session.create_script((BASE/'jit-boundary-probe.js').read_text()) + source = (BASE/'jit-boundary-probe.js').read_text() + if os.environ.get('ARTWATCH_SHADOW_SHIM') == '1': + source = ('globalThis.__artwatchShadowPath = ' + + json.dumps('/data/local/tmp/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() @@ -78,6 +83,7 @@ def main(): 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': @@ -248,6 +254,30 @@ def main(): '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 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') record('host','PASS: Frida attach + ART discovery + fixture warmup') if __name__ == '__main__': diff --git a/art-fieldwatch-phase1/jit-boundary-probe.js b/art-fieldwatch-phase1/jit-boundary-probe.js index 388da1e..a00491d 100644 --- a/art-fieldwatch-phase1/jit-boundary-probe.js +++ b/art-fieldwatch-phase1/jit-boundary-probe.js @@ -18,6 +18,9 @@ let observedFieldAccepts = 0; const insertionCounts = {append: 0, 'basic-block': 0}; const optimizationByThread = new Map(); const knownFieldVtables = new Map(); +let shadowShim = null; +let shadowGraphLogged = 0; +let shadowNodeLogged = 0; const targetDexByMethod = new Map(); let backendVisitOrdinal = 0; const BACKEND_VISIT_LIMIT = 160; @@ -90,6 +93,44 @@ 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 { + const module = Module.load(globalThis.__artwatchShadowPath); + 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']) + }; + 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() @@ -212,6 +253,7 @@ function attach(layer, site) { 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); @@ -265,6 +307,17 @@ function attachGraphBoundary(layer, site) { const previous = builtByThread.get(this.nativeThread); const matches = previous && previous.graphCandidate !== null ? previous.graphCandidate === this.graph : null; + 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 && + 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, @@ -470,6 +523,18 @@ function attachFieldAccept(compiler) { 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 && 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'); if (targetMethodPointers.has(compilation.method)) { @@ -711,6 +776,7 @@ function main() { else log('field-builder-not-exported=' + access); } discoverFieldVtables(compiler); + 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); From a2ab1e28cc03d36d76db68dc7ad649ea154b74ca Mon Sep 17 00:00:00 2001 From: Muhtasham Nawr al-Mahmud <72372229+mnalmahmud@users.noreply.github.com> Date: Fri, 20 Nov 2026 17:42:39 +0600 Subject: [PATCH 032/129] ci: ignore expected sdkmanager license-input SIGPIPE after NDK installed --- art-fieldwatch-phase1/ci/build-passive-shim.sh | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/art-fieldwatch-phase1/ci/build-passive-shim.sh b/art-fieldwatch-phase1/ci/build-passive-shim.sh index dbdcac8..d73a40b 100644 --- a/art-fieldwatch-phase1/ci/build-passive-shim.sh +++ b/art-fieldwatch-phase1/ci/build-passive-shim.sh @@ -6,7 +6,9 @@ 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 - yes | sdkmanager --install "ndk;$version" >/dev/null + # 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" From ce3cbec7ad3563f5b62ab71b2a0821cc5a0210e9 Mon Sep 17 00:00:00 2001 From: Muhtasham Nawr al-Mahmud <72372229+mnalmahmud@users.noreply.github.com> Date: Fri, 20 Nov 2026 17:56:47 +0600 Subject: [PATCH 033/129] ci: package native P1 shim in APK and resolve app-loaded library --- .github/workflows/art-fieldwatch-phase1.yml | 5 +++++ art-fieldwatch-phase1/README.md | 20 +++++++++++++++++++ .../ci/build-passive-shim.sh | 7 +++++++ .../ci/run-emulator-smoke.sh | 11 ++++------ art-fieldwatch-phase1/ci/smoke_test.py | 5 ++++- art-fieldwatch-phase1/jit-boundary-probe.js | 12 ++++++++++- art-fieldwatch-phase1/test/app/build.gradle | 7 +++++++ .../example/artfieldwatch/MainActivity.java | 11 ++++++++++ 8 files changed, 69 insertions(+), 9 deletions(-) diff --git a/.github/workflows/art-fieldwatch-phase1.yml b/.github/workflows/art-fieldwatch-phase1.yml index 9e16b4c..5a0580e 100644 --- a/.github/workflows/art-fieldwatch-phase1.yml +++ b/.github/workflows/art-fieldwatch-phase1.yml @@ -86,6 +86,11 @@ jobs: *) exit 1 ;; esac gradle -p art-fieldwatch-phase1/test ":app:$task" --no-daemon + - 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' - 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' diff --git a/art-fieldwatch-phase1/README.md b/art-fieldwatch-phase1/README.md index b9543f3..7124a3e 100644 --- a/art-fieldwatch-phase1/README.md +++ b/art-fieldwatch-phase1/README.md @@ -299,3 +299,23 @@ 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. diff --git a/art-fieldwatch-phase1/ci/build-passive-shim.sh b/art-fieldwatch-phase1/ci/build-passive-shim.sh index d73a40b..3a27659 100644 --- a/art-fieldwatch-phase1/ci/build-passive-shim.sh +++ b/art-fieldwatch-phase1/ci/build-passive-shim.sh @@ -19,3 +19,10 @@ mkdir -p "$out" -o "$out/libartwatch_shadow.so" file "$out/libartwatch_shadow.so" readelf -Ws "$out/libartwatch_shadow.so" | grep -E 'artwatch_shadow_(init|graph|node|report)' | 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" diff --git a/art-fieldwatch-phase1/ci/run-emulator-smoke.sh b/art-fieldwatch-phase1/ci/run-emulator-smoke.sh index 5e259ef..54245ed 100644 --- a/art-fieldwatch-phase1/ci/run-emulator-smoke.sh +++ b/art-fieldwatch-phase1/ci/run-emulator-smoke.sh @@ -37,13 +37,10 @@ if [ "$ready" -ne 1 ]; then exit 1 fi if [[ "${ARTWATCH_SHADOW_SHIM:-0}" == 1 ]]; then - if [[ "$ABI" != x86_64 ]]; then - echo "Native shadow shim supports only x86_64" >&2; exit 1 - fi - native="art-fieldwatch-phase1/native/out/libartwatch_shadow.so" - test -s "$native" || { echo "Missing native shim: $native" >&2; exit 1; } - adb push "$native" /data/local/tmp/libartwatch_shadow.so - adb shell chmod 755 /data/local/tmp/libartwatch_shadow.so + # 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. diff --git a/art-fieldwatch-phase1/ci/smoke_test.py b/art-fieldwatch-phase1/ci/smoke_test.py index 57c8acb..1fe0d75 100644 --- a/art-fieldwatch-phase1/ci/smoke_test.py +++ b/art-fieldwatch-phase1/ci/smoke_test.py @@ -35,7 +35,7 @@ def main(): source = (BASE/'jit-boundary-probe.js').read_text() if os.environ.get('ARTWATCH_SHADOW_SHIM') == '1': source = ('globalThis.__artwatchShadowPath = ' + - json.dumps('/data/local/tmp/libartwatch_shadow.so') + + json.dumps('libartwatch_shadow.so') + ';\n' + source) script = session.create_script(source) script.on('message',on_message) @@ -58,6 +58,9 @@ def main(): 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: + raise AssertionError('App failed to load packaged native shadow library') if 'WARMUP_FAILED' in logs.stdout or 'WARMUP_DONE' not in logs.stdout: raise AssertionError('APK fixture warmup failed or timed out') hooked = [e['text'] for e in messages if e['kind']=='frida' and diff --git a/art-fieldwatch-phase1/jit-boundary-probe.js b/art-fieldwatch-phase1/jit-boundary-probe.js index a00491d..28878be 100644 --- a/art-fieldwatch-phase1/jit-boundary-probe.js +++ b/art-fieldwatch-phase1/jit-boundary-probe.js @@ -19,6 +19,7 @@ const insertionCounts = {append: 0, 'basic-block': 0}; const optimizationByThread = new Map(); const knownFieldVtables = new Map(); let shadowShim = null; +let shadowModuleAttempted = false; let shadowGraphLogged = 0; let shadowNodeLogged = 0; const targetDexByMethod = new Map(); @@ -99,7 +100,12 @@ function loadPassiveShadow() { if (typeof globalThis.__artwatchShadowPath !== 'string' || Process.arch !== 'x64') return; try { - const module = Module.load(globalThis.__artwatchShadowPath); + // 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); @@ -298,6 +304,7 @@ function attachGraphBoundary(layer, site) { this.previousGraphBuild = activeGraphBuild.get(this.nativeThread); activeGraphBuild.set(this.nativeThread, this.graphCandidate); } else { + if (!shadowShim) loadPassiveShadow(); // const OptimizingCompiler* this, HGraph*, CodeGenerator*, ... this.previousOptimization = optimizationByThread.get(this.nativeThread); optimizationByThread.set(this.nativeThread, args[1].toString()); @@ -523,6 +530,7 @@ function attachFieldAccept(compiler) { 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 { @@ -776,6 +784,8 @@ function main() { else log('field-builder-not-exported=' + access); } discoverFieldVtables(compiler); + // 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. diff --git a/art-fieldwatch-phase1/test/app/build.gradle b/art-fieldwatch-phase1/test/app/build.gradle index e5e7c69..eecc2b4 100644 --- a/art-fieldwatch-phase1/test/app/build.gradle +++ b/art-fieldwatch-phase1/test/app/build.gradle @@ -17,6 +17,13 @@ android { 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. diff --git a/art-fieldwatch-phase1/test/app/src/main/java/com/example/artfieldwatch/MainActivity.java b/art-fieldwatch-phase1/test/app/src/main/java/com/example/artfieldwatch/MainActivity.java index 646d98a..f8ae385 100644 --- a/art-fieldwatch-phase1/test/app/src/main/java/com/example/artfieldwatch/MainActivity.java +++ b/art-fieldwatch-phase1/test/app/src/main/java/com/example/artfieldwatch/MainActivity.java @@ -14,6 +14,17 @@ protected void onCreate(Bundle state) { final boolean appDebuggable = (getApplicationInfo().flags & android.content.pm.ApplicationInfo.FLAG_DEBUGGABLE) != 0; Log.i("ARTWATCH_CI","APP_DEBUGGABLE=" + appDebuggable); + // Load the native P1 companion from the APK on the API33 emulator. + // The Frida agent only looks up the already-loaded module and never + // tries to mmap a shared library from /data/local/tmp. + if (android.os.Build.VERSION.SDK_INT == 33) { + try { + System.loadLibrary("artwatch_shadow"); + Log.i("ARTWATCH_CI","SHADOW_LIB_LOADED=true"); + } catch (UnsatisfiedLinkError e) { + Log.e("ARTWATCH_CI","SHADOW_LIB_LOAD_FAILED",e); + } + } new Thread(() -> { long accumulator = 0; try { From d8a47afddf9d1bf032b1c3e68e85ff226e18334a Mon Sep 17 00:00:00 2001 From: Muhtasham Nawr al-Mahmud <72372229+mnalmahmud@users.noreply.github.com> Date: Fri, 20 Nov 2026 18:20:23 +0600 Subject: [PATCH 034/129] fix: accept Android ART 16-byte GNU build IDs in native shadow gate --- art-fieldwatch-phase1/native/passive-shadow.c | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/art-fieldwatch-phase1/native/passive-shadow.c b/art-fieldwatch-phase1/native/passive-shadow.c index 39efb22..daee386 100644 --- a/art-fieldwatch-phase1/native/passive-shadow.c +++ b/art-fieldwatch-phase1/native/passive-shadow.c @@ -42,15 +42,18 @@ static int note_build_id(const struct dl_phdr_info *info, char out[41]) { 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 != 20) continue; + (nh.n_descsz != 16 && nh.n_descsz != 20)) continue; static const char digits[] = "0123456789abcdef"; - for (size_t k = 0; k < 20; ++k) { + 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[40] = '\0'; + out[2u * nh.n_descsz] = '\0'; return 1; } } From 241f42970267bd47cb0c6cfebe5072408d341386 Mon Sep 17 00:00:00 2001 From: Muhtasham Nawr al-Mahmud <72372229+mnalmahmud@users.noreply.github.com> Date: Fri, 20 Nov 2026 18:51:05 +0600 Subject: [PATCH 035/129] test: diversify and stage release JIT field-load elimination workloads --- art-fieldwatch-phase1/README.md | 23 +++++++++++ art-fieldwatch-phase1/ci/dex-inventory.sh | 16 ++++++++ art-fieldwatch-phase1/ci/smoke_test.py | 10 ++++- .../example/artfieldwatch/FieldIRTarget.java | 39 +++++++++++++++++++ .../example/artfieldwatch/MainActivity.java | 13 ++++++- 5 files changed, 99 insertions(+), 2 deletions(-) diff --git a/art-fieldwatch-phase1/README.md b/art-fieldwatch-phase1/README.md index 7124a3e..41f5b5b 100644 --- a/art-fieldwatch-phase1/README.md +++ b/art-fieldwatch-phase1/README.md @@ -319,3 +319,26 @@ 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. diff --git a/art-fieldwatch-phase1/ci/dex-inventory.sh b/art-fieldwatch-phase1/ci/dex-inventory.sh index eb3945c..78c6ffc 100644 --- a/art-fieldwatch-phase1/ci/dex-inventory.sh +++ b/art-fieldwatch-phase1/ci/dex-inventory.sh @@ -36,6 +36,22 @@ if "$analyzer" dex code --class com.example.artfieldwatch.FieldIRTarget "$apk" > exit 1 fi echo "Verified release testViaIdentity DEX retains both iput and iget." + # 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" diff --git a/art-fieldwatch-phase1/ci/smoke_test.py b/art-fieldwatch-phase1/ci/smoke_test.py index 1fe0d75..7cd8b4a 100644 --- a/art-fieldwatch-phase1/ci/smoke_test.py +++ b/art-fieldwatch-phase1/ci/smoke_test.py @@ -42,7 +42,9 @@ def main(): script.set_log_handler(lambda level, line: record('console-'+level, line)) script.load() device.resume(pid) - time.sleep(20) + # 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) finally: try: session.detach() except frida.InvalidOperationError: pass @@ -63,6 +65,12 @@ def main(): raise AssertionError('App failed to load packaged native shadow library') 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 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 index 58e2394..7424e44 100644 --- 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 @@ -20,6 +20,45 @@ public int testViaIdentity(int 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; + } + public static int warmup(int iterations) { FieldIRTarget target = new FieldIRTarget(); int observed = 0; diff --git a/art-fieldwatch-phase1/test/app/src/main/java/com/example/artfieldwatch/MainActivity.java b/art-fieldwatch-phase1/test/app/src/main/java/com/example/artfieldwatch/MainActivity.java index f8ae385..5c26874 100644 --- a/art-fieldwatch-phase1/test/app/src/main/java/com/example/artfieldwatch/MainActivity.java +++ b/art-fieldwatch-phase1/test/app/src/main/java/com/example/artfieldwatch/MainActivity.java @@ -33,7 +33,18 @@ protected void onCreate(Bundle state) { 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) accumulator += FieldIRTarget.warmup(1200000); + 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); + } + } Log.i("ARTWATCH_CI","WARMUP_DONE checksum=" + accumulator); } catch (Throwable t) { Log.e("ARTWATCH_CI","WARMUP_FAILED",t); From 5edf25d5bf4f80060a8885c213727edeef8faba7 Mon Sep 17 00:00:00 2001 From: Muhtasham Nawr al-Mahmud <72372229+mnalmahmud@users.noreply.github.com> Date: Fri, 20 Nov 2026 19:23:07 +0600 Subject: [PATCH 036/129] research: add native per-compilation field IR visitor inventory without HGraph layout assumptions --- art-fieldwatch-phase1/README.md | 21 ++++++++ .../ci/build-passive-shim.sh | 2 +- art-fieldwatch-phase1/ci/smoke_test.py | 16 ++++++ art-fieldwatch-phase1/jit-boundary-probe.js | 32 ++++++++++-- art-fieldwatch-phase1/native/passive-shadow.c | 52 +++++++++++++++++++ 5 files changed, 117 insertions(+), 6 deletions(-) diff --git a/art-fieldwatch-phase1/README.md b/art-fieldwatch-phase1/README.md index 41f5b5b..08a7c77 100644 --- a/art-fieldwatch-phase1/README.md +++ b/art-fieldwatch-phase1/README.md @@ -342,3 +342,24 @@ 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 diff --git a/art-fieldwatch-phase1/ci/build-passive-shim.sh b/art-fieldwatch-phase1/ci/build-passive-shim.sh index 3a27659..5a0f434 100644 --- a/art-fieldwatch-phase1/ci/build-passive-shim.sh +++ b/art-fieldwatch-phase1/ci/build-passive-shim.sh @@ -18,7 +18,7 @@ mkdir -p "$out" 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)' | tee "$out/exports.txt" +readelf -Ws "$out/libartwatch_shadow.so" | grep -E 'artwatch_shadow_(init|graph|node|report|scope_begin|scope_end)' | 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. diff --git a/art-fieldwatch-phase1/ci/smoke_test.py b/art-fieldwatch-phase1/ci/smoke_test.py index 7cd8b4a..031df80 100644 --- a/art-fieldwatch-phase1/ci/smoke_test.py +++ b/art-fieldwatch-phase1/ci/smoke_test.py @@ -289,6 +289,22 @@ def main(): 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') record('host','PASS: Frida attach + ART discovery + fixture warmup') if __name__ == '__main__': diff --git a/art-fieldwatch-phase1/jit-boundary-probe.js b/art-fieldwatch-phase1/jit-boundary-probe.js index 28878be..47d5988 100644 --- a/art-fieldwatch-phase1/jit-boundary-probe.js +++ b/art-fieldwatch-phase1/jit-boundary-probe.js @@ -119,7 +119,9 @@ function loadPassiveShadow() { 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']) + 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']) }; send({type:'artwatch-shadow-init',ready:true,source:'native', buildIdVerified:true,mutable:false}); @@ -314,14 +316,18 @@ function attachGraphBoundary(layer, site) { const previous = builtByThread.get(this.nativeThread); const matches = previous && previous.graphCandidate !== null ? previous.graphCandidate === this.graph : null; + 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 && - shadowGraphLogged++ < 14) { - send({type:'artwatch-shadow-graph',method:this.method, - graph:this.graph,matched:true}); + 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); } } @@ -338,6 +344,22 @@ function attachGraphBoundary(layer, site) { }, onLeave(_retval) { if (layer === 'pre_opt') { + 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; diff --git a/art-fieldwatch-phase1/native/passive-shadow.c b/art-fieldwatch-phase1/native/passive-shadow.c index daee386..9537bee 100644 --- a/art-fieldwatch-phase1/native/passive-shadow.c +++ b/art-fieldwatch-phase1/native/passive-shadow.c @@ -87,6 +87,36 @@ EXPORT int artwatch_shadow_init(void) { } // 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); @@ -121,6 +151,28 @@ EXPORT int artwatch_shadow_node(const void *node, const void *vt_symbol, int kin } 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; } // Writes only into the caller's scratch buffer, never to ART memory. From 277dadc40f4f0f9f4a54374408208815facc69ce Mon Sep 17 00:00:00 2001 From: Muhtasham Nawr al-Mahmud <72372229+mnalmahmud@users.noreply.github.com> Date: Fri, 20 Nov 2026 21:24:56 +0600 Subject: [PATCH 037/129] research: probe source-backed HGraph AddBlock and GraphChecker block boundaries --- art-fieldwatch-phase1/README.md | 25 ++++++ .../ci/art-binary-inventory.sh | 4 + .../ci/build-passive-shim.sh | 2 +- art-fieldwatch-phase1/ci/smoke_test.py | 19 ++++ art-fieldwatch-phase1/jit-boundary-probe.js | 86 ++++++++++++++++++- art-fieldwatch-phase1/native/passive-shadow.c | 18 +++- 6 files changed, 148 insertions(+), 6 deletions(-) diff --git a/art-fieldwatch-phase1/README.md b/art-fieldwatch-phase1/README.md index 08a7c77..8332fd7 100644 --- a/art-fieldwatch-phase1/README.md +++ b/art-fieldwatch-phase1/README.md @@ -363,3 +363,28 @@ the NDK alone requires layout verification against the exact Android 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 diff --git a/art-fieldwatch-phase1/ci/art-binary-inventory.sh b/art-fieldwatch-phase1/ci/art-binary-inventory.sh index 71c810a..334a9ee 100644 --- a/art-fieldwatch-phase1/ci/art-binary-inventory.sh +++ b/art-fieldwatch-phase1/ci/art-binary-inventory.sh @@ -33,6 +33,10 @@ abi="$(adb shell getprop ro.product.cpu.abi | tr -d '\r')" readelf -Ws "$tmp/$library" 2>&1 | grep -E '(LoadStoreElimination|LSEVisitor|HInstruction.*ReplaceWith|HBasicBlock.*RemoveInstruction|ReplaceAndRemoveInstruction)' | head -n 100 || 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' diff --git a/art-fieldwatch-phase1/ci/build-passive-shim.sh b/art-fieldwatch-phase1/ci/build-passive-shim.sh index 5a0f434..581af5f 100644 --- a/art-fieldwatch-phase1/ci/build-passive-shim.sh +++ b/art-fieldwatch-phase1/ci/build-passive-shim.sh @@ -18,7 +18,7 @@ mkdir -p "$out" 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)' | tee "$out/exports.txt" +readelf -Ws "$out/libartwatch_shadow.so" | grep -E 'artwatch_shadow_(init|graph|node|report|scope_begin|scope_end|block)' | 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. diff --git a/art-fieldwatch-phase1/ci/smoke_test.py b/art-fieldwatch-phase1/ci/smoke_test.py index 031df80..0f230b6 100644 --- a/art-fieldwatch-phase1/ci/smoke_test.py +++ b/art-fieldwatch-phase1/ci/smoke_test.py @@ -305,6 +305,25 @@ def main(): 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') + # Out-of-line graph functions may be absent or silent after inlining. record('host','PASS: Frida attach + ART discovery + fixture warmup') if __name__ == '__main__': diff --git a/art-fieldwatch-phase1/jit-boundary-probe.js b/art-fieldwatch-phase1/jit-boundary-probe.js index 47d5988..4d28c7e 100644 --- a/art-fieldwatch-phase1/jit-boundary-probe.js +++ b/art-fieldwatch-phase1/jit-boundary-probe.js @@ -71,6 +71,8 @@ const NAMES = { instance: '_ZN3art3jit3Jit13jit_compiler_E', buildGraph: '_ZN3art13HGraphBuilder10BuildGraphEv', runOptimizations: '_ZNK3art18OptimizingCompiler16RunOptimizationsEPNS_6HGraphEPNS_13CodeGeneratorERKNS_18DexCompilationUnitEPNS_12PassObserverE', + graphAddBlock: '_ZN3art6HGraph8AddBlockEPNS_11HBasicBlockE', + graphCheckerBlock: '_ZN3art12GraphChecker15VisitBasicBlockEPNS_11HBasicBlockE', // Candidate exported signatures from instruction_builder.cc. Only use if // this exact ELF symbol exists on the running device. fieldInstance: '_ZN3art19HInstructionBuilder24BuildInstanceFieldAccessERKNS_11InstructionEjb', @@ -121,7 +123,8 @@ function loadPassiveShadow() { 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']) + scopeEnd: exported('artwatch_shadow_scope_end','int',['pointer','uint']), + block: exported('artwatch_shadow_block','int',['pointer','pointer','pointer']) }; send({type:'artwatch-shadow-init',ready:true,source:'native', buildIdVerified:true,mutable:false}); @@ -186,7 +189,9 @@ function attach(layer, site) { seenVisits: new Set(), seenKinds: new Set(), uniqueNodes: new Set(), visitsByPhase: {}, mutations: [], reported: 0, optimizationEntries: 0, lseInvocations: 0, - backendLocations: new Set(), backendEmitted: new Set() + backendLocations: new Set(), backendEmitted: new Set(), + constructionGraph: null, constructedBlocks: new Set(), + checkerBlocks: new Set(), unmatchedBlockCalls: 0 }); compiling.set(this.nativeThread, {method: this.method, kind: this.compilationKind}); builtByThread.delete(this.nativeThread); @@ -305,6 +310,8 @@ function attachGraphBoundary(layer, site) { 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*, ... @@ -316,6 +323,17 @@ function attachGraphBoundary(layer, site) { 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)); + } this.shadowScopeStarted = false; if (shadowShim && matches === true) { try { @@ -344,6 +362,16 @@ function attachGraphBoundary(layer, site) { }, onLeave(_retval) { if (layer === 'pre_opt') { + const state = targetStates.get(this.nativeThread); + 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); @@ -387,6 +415,49 @@ function attachGraphBoundary(layer, site) { 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 { + if (!optimizationByThread.has(thread)) return; + const block = args[1]; + if (block.isNull() || !Process.findRangeByAddress(block)) return; + if (state.checkerBlocks.size < 4096) + state.checkerBlocks.add(block.toString()); + } + } + }); + 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. @@ -742,7 +813,8 @@ function main() { // 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.fieldInstance, + NAMES.runOptimizations, NAMES.graphAddBlock, + NAMES.graphCheckerBlock, NAMES.fieldInstance, NAMES.fieldStatic, NAMES.appendInstruction, NAMES.addInstruction, NAMES.replaceWith, NAMES.replaceAndRemove, NAMES.removeInstruction, @@ -805,6 +877,14 @@ function main() { 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] + ]) { + const site = getExport(compiler, name); + if (site) attachBlockBoundary(layer, site); + else log('block-boundary-not-exported=' + layer); + } discoverFieldVtables(compiler); // The app's onCreate() has not run at agent load time. Resolve the // already-loaded shim lazily from compiler callbacks instead. diff --git a/art-fieldwatch-phase1/native/passive-shadow.c b/art-fieldwatch-phase1/native/passive-shadow.c index 9537bee..8f3a5a7 100644 --- a/art-fieldwatch-phase1/native/passive-shadow.c +++ b/art-fieldwatch-phase1/native/passive-shadow.c @@ -14,7 +14,7 @@ #define RUNTIME_ID "c8b6a2df9893030c07b3b96dc24a7d30" static int ready = 0; -static uint64_t graphs = 0, gets = 0, sets = 0, rejected = 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; @@ -128,6 +128,19 @@ EXPORT int artwatch_shadow_graph(const void *graph, const void *builder_graph) { __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) { @@ -180,11 +193,12 @@ 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," - "\"rejected\":%llu,\"opaqueGraphWord\":\"0x%llx\"}", + "\"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; From 582c54809ac787a858def00c4063f47ba138070d Mon Sep 17 00:00:00 2001 From: Muhtasham Nawr al-Mahmud <72372229+mnalmahmud@users.noreply.github.com> Date: Fri, 20 Nov 2026 23:50:12 +0600 Subject: [PATCH 038/129] research: correlate HGraph block identities with field instruction insertion and traversal --- art-fieldwatch-phase1/README.md | 35 ++++++++ .../ci/art-binary-inventory.sh | 4 + art-fieldwatch-phase1/ci/smoke_test.py | 28 +++++- art-fieldwatch-phase1/jit-boundary-probe.js | 88 +++++++++++++++++-- 4 files changed, 149 insertions(+), 6 deletions(-) diff --git a/art-fieldwatch-phase1/README.md b/art-fieldwatch-phase1/README.md index 8332fd7..233b1ff 100644 --- a/art-fieldwatch-phase1/README.md +++ b/art-fieldwatch-phase1/README.md @@ -388,3 +388,38 @@ 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 diff --git a/art-fieldwatch-phase1/ci/art-binary-inventory.sh b/art-fieldwatch-phase1/ci/art-binary-inventory.sh index 334a9ee..8b72935 100644 --- a/art-fieldwatch-phase1/ci/art-binary-inventory.sh +++ b/art-fieldwatch-phase1/ci/art-binary-inventory.sh @@ -33,6 +33,10 @@ abi="$(adb shell getprop ro.product.cpu.abi | tr -d '\r')" 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)' | diff --git a/art-fieldwatch-phase1/ci/smoke_test.py b/art-fieldwatch-phase1/ci/smoke_test.py index 0f230b6..5895a0c 100644 --- a/art-fieldwatch-phase1/ci/smoke_test.py +++ b/art-fieldwatch-phase1/ci/smoke_test.py @@ -323,7 +323,33 @@ def main(): 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') - # Out-of-line graph functions may be absent or silent after inlining. + 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') + # Visitor and AddInstruction call sites can be fully inlined. + # Never manufacture node membership from an exported symbol. record('host','PASS: Frida attach + ART discovery + fixture warmup') if __name__ == '__main__': diff --git a/art-fieldwatch-phase1/jit-boundary-probe.js b/art-fieldwatch-phase1/jit-boundary-probe.js index 4d28c7e..21e8829 100644 --- a/art-fieldwatch-phase1/jit-boundary-probe.js +++ b/art-fieldwatch-phase1/jit-boundary-probe.js @@ -73,6 +73,11 @@ const NAMES = { 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', @@ -191,7 +196,11 @@ function attach(layer, site) { optimizationEntries: 0, lseInvocations: 0, backendLocations: new Set(), backendEmitted: new Set(), constructionGraph: null, constructedBlocks: new Set(), - checkerBlocks: new Set(), unmatchedBlockCalls: 0 + checkerBlocks: new Set(), visitorBlocks: new Set(), + visitorBlocksUnknown: new Set(), + 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); @@ -334,6 +343,18 @@ function attachGraphBoundary(layer, site) { 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 { @@ -363,6 +384,17 @@ function attachGraphBoundary(layer, site) { onLeave(_retval) { if (layer === 'pre_opt') { const state = targetStates.get(this.nativeThread); + if (state && state.visitorBlocks.size > 0) { + 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, @@ -444,8 +476,18 @@ function attachBlockBoundary(layer, site) { if (!optimizationByThread.has(thread)) return; const block = args[1]; if (block.isNull() || !Process.findRangeByAddress(block)) return; - if (state.checkerBlocks.size < 4096) - state.checkerBlocks.add(block.toString()); + if (layer === 'graph_checker_block') { + if (state.checkerBlocks.size < 4096) + state.checkerBlocks.add(block.toString()); + } else { + 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()); + } } } }); @@ -561,6 +603,22 @@ function attachFieldNodeCandidate(site, source) { 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; @@ -638,6 +696,13 @@ function attachFieldAccept(compiler) { } 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++; + } if (targetMethodPointers.has(compilation.method)) { const state = targetStates.get(thread); if (state) { @@ -814,7 +879,9 @@ function main() { for (const name of [NAMES.internal, NAMES.publicCompile, NAMES.compiler, NAMES.instance, NAMES.buildGraph, NAMES.runOptimizations, NAMES.graphAddBlock, - NAMES.graphCheckerBlock, NAMES.fieldInstance, + NAMES.graphCheckerBlock, NAMES.graphVisitorBlock, + NAMES.graphVisitorInsertion, NAMES.graphVisitorRpo, + NAMES.fieldInstance, NAMES.fieldStatic, NAMES.appendInstruction, NAMES.addInstruction, NAMES.replaceWith, NAMES.replaceAndRemove, NAMES.removeInstruction, @@ -879,12 +946,23 @@ function main() { } for (const [layer, name] of [ ['graph_add_block', NAMES.graphAddBlock], - ['graph_checker_block', NAMES.graphCheckerBlock] + ['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); // The app's onCreate() has not run at agent load time. Resolve the // already-loaded shim lazily from compiler callbacks instead. From e989e8bac8724823ae0ed3b13d3490f875a1ac2b Mon Sep 17 00:00:00 2001 From: Muhtasham Nawr al-Mahmud <72372229+mnalmahmud@users.noreply.github.com> Date: Sat, 21 Nov 2026 01:18:57 +0600 Subject: [PATCH 039/129] research: prove field IR instruction-to-basic-block ownership through matching ART visitors --- art-fieldwatch-phase1/README.md | 32 ++++++++++ art-fieldwatch-phase1/ci/smoke_test.py | 30 ++++++++- art-fieldwatch-phase1/jit-boundary-probe.js | 69 +++++++++++++++++++++ 3 files changed, 129 insertions(+), 2 deletions(-) diff --git a/art-fieldwatch-phase1/README.md b/art-fieldwatch-phase1/README.md index 233b1ff..8bbcc82 100644 --- a/art-fieldwatch-phase1/README.md +++ b/art-fieldwatch-phase1/README.md @@ -423,3 +423,35 @@ 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 diff --git a/art-fieldwatch-phase1/ci/smoke_test.py b/art-fieldwatch-phase1/ci/smoke_test.py index 5895a0c..c58b489 100644 --- a/art-fieldwatch-phase1/ci/smoke_test.py +++ b/art-fieldwatch-phase1/ci/smoke_test.py @@ -348,8 +348,34 @@ def main(): if any(v.get('newlySeenBlocks',0) > v.get('uniqueBlocks',0) for v in visitor_evidence): raise AssertionError('Impossible visitor block membership counts') - # Visitor and AddInstruction call sites can be fully inlined. - # Never manufacture node membership from an exported symbol. + 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__': diff --git a/art-fieldwatch-phase1/jit-boundary-probe.js b/art-fieldwatch-phase1/jit-boundary-probe.js index 21e8829..6d17327 100644 --- a/art-fieldwatch-phase1/jit-boundary-probe.js +++ b/art-fieldwatch-phase1/jit-boundary-probe.js @@ -17,6 +17,8 @@ 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(); let shadowShim = null; let shadowModuleAttempted = false; @@ -198,6 +200,9 @@ function attach(layer, site) { 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, blockInstructionMap: new Map(), fieldNodeInserts: 0, graphAddInstructionCalls: 0, fieldVisitBlockMatches: 0, unmatchedBlockCalls: 0 @@ -385,6 +390,20 @@ function attachGraphBoundary(layer, site) { if (layer === 'pre_opt') { const state = targetStates.get(this.nativeThread); if (state && state.visitorBlocks.size > 0) { + 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, @@ -480,6 +499,15 @@ function attachBlockBoundary(layer, site) { 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; + activeVisitorBlockByThread.set(thread, { + visitor: args[0].toString(), block: block.toString() + }); if (state.visitorBlocks.size < 4096) state.visitorBlocks.add(block.toString()); // Inlining or loop transformations can add blocks after the @@ -489,6 +517,14 @@ function attachBlockBoundary(layer, site) { state.visitorBlocksUnknown.add(block.toString()); } } + }, + onLeave() { + if (this.visitorBlockActive !== true) return; + if (this.previousVisitorBlock === undefined) + activeVisitorBlockByThread.delete(this.visitorBlockThread); + else + activeVisitorBlockByThread.set(this.visitorBlockThread, + this.previousVisitorBlock); } }); send({type:'artwatch-hook-attached',layer,source:'export', @@ -703,6 +739,39 @@ function attachFieldAccept(compiler) { 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) { + 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) { From be270a605915f6a48a045f934f27c918752345f6 Mon Sep 17 00:00:00 2001 From: Muhtasham Nawr al-Mahmud <72372229+mnalmahmud@users.noreply.github.com> Date: Sat, 21 Nov 2026 01:19:54 +0600 Subject: [PATCH 040/129] ci: fix Python ownership assertion syntax before emulator verification --- art-fieldwatch-phase1/ci/smoke_test.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/art-fieldwatch-phase1/ci/smoke_test.py b/art-fieldwatch-phase1/ci/smoke_test.py index c58b489..8bf90d0 100644 --- a/art-fieldwatch-phase1/ci/smoke_test.py +++ b/art-fieldwatch-phase1/ci/smoke_test.py @@ -367,7 +367,7 @@ def main(): raise AssertionError('Field Accept visitor did not match active ' 'HGraphVisitor::VisitBasicBlock') for item in ownership: - if (item.get('uniqueFieldBlockPairs',0) > item.get('correlatedVisits',0): + 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') From e2fedd431953e889b864681c56cb92c4749a8aa0 Mon Sep 17 00:00:00 2001 From: Muhtasham Nawr al-Mahmud <72372229+mnalmahmud@users.noreply.github.com> Date: Sat, 21 Nov 2026 01:26:01 +0600 Subject: [PATCH 041/129] research: assert every LSE-eliminated field get has observed ART basic-block ownership --- art-fieldwatch-phase1/README.md | 27 +++++++++++++++++++++ art-fieldwatch-phase1/ci/smoke_test.py | 12 +++++++++ art-fieldwatch-phase1/jit-boundary-probe.js | 16 +++++++++++- 3 files changed, 54 insertions(+), 1 deletion(-) diff --git a/art-fieldwatch-phase1/README.md b/art-fieldwatch-phase1/README.md index 8bbcc82..29cb68e 100644 --- a/art-fieldwatch-phase1/README.md +++ b/art-fieldwatch-phase1/README.md @@ -455,3 +455,30 @@ 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. diff --git a/art-fieldwatch-phase1/ci/smoke_test.py b/art-fieldwatch-phase1/ci/smoke_test.py index 8bf90d0..cec4a26 100644 --- a/art-fieldwatch-phase1/ci/smoke_test.py +++ b/art-fieldwatch-phase1/ci/smoke_test.py @@ -252,6 +252,10 @@ def main(): 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 @@ -259,12 +263,20 @@ def main(): 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') 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 diff --git a/art-fieldwatch-phase1/jit-boundary-probe.js b/art-fieldwatch-phase1/jit-boundary-probe.js index 6d17327..bbf164b 100644 --- a/art-fieldwatch-phase1/jit-boundary-probe.js +++ b/art-fieldwatch-phase1/jit-boundary-probe.js @@ -254,7 +254,21 @@ function attach(layer, site) { } const entries = Array.from(lifecycleByNode.values()).map(entry => { const identity = entry.kind + '@' + entry.node; - return {...entry, lowered: state.backendLocations.has(identity), + // 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) { From 4f3f628d36d868115d401e88aa1fc795a845db0c Mon Sep 17 00:00:00 2001 From: Muhtasham Nawr al-Mahmud <72372229+mnalmahmud@users.noreply.github.com> Date: Sat, 21 Nov 2026 06:14:38 +0600 Subject: [PATCH 042/129] research: capture per-block field visitation order and LSE replacement SSA kinds --- art-fieldwatch-phase1/README.md | 35 ++++++++ art-fieldwatch-phase1/ci/smoke_test.py | 31 +++++++ art-fieldwatch-phase1/jit-boundary-probe.js | 90 +++++++++++++++++++-- 3 files changed, 150 insertions(+), 6 deletions(-) diff --git a/art-fieldwatch-phase1/README.md b/art-fieldwatch-phase1/README.md index 29cb68e..cafd872 100644 --- a/art-fieldwatch-phase1/README.md +++ b/art-fieldwatch-phase1/README.md @@ -482,3 +482,38 @@ Important caveat: an instruction can move between blocks, so 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 diff --git a/art-fieldwatch-phase1/ci/smoke_test.py b/art-fieldwatch-phase1/ci/smoke_test.py index cec4a26..5efae29 100644 --- a/art-fieldwatch-phase1/ci/smoke_test.py +++ b/art-fieldwatch-phase1/ci/smoke_test.py @@ -277,6 +277,37 @@ def main(): 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 diff --git a/art-fieldwatch-phase1/jit-boundary-probe.js b/art-fieldwatch-phase1/jit-boundary-probe.js index bbf164b..a86b536 100644 --- a/art-fieldwatch-phase1/jit-boundary-probe.js +++ b/art-fieldwatch-phase1/jit-boundary-probe.js @@ -20,6 +20,39 @@ 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; @@ -203,6 +236,8 @@ function attach(layer, site) { 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 @@ -250,7 +285,10 @@ function attach(layer, site) { } entry.operations.push(mutation.op); entry.visitedBeforeMutation ||= mutation.visitedBeforeMutation === true; - if (mutation.op === 'replace') entry.replacement = mutation.substitute; + 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; @@ -404,6 +442,18 @@ function attachGraphBoundary(layer, site) { 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, @@ -519,9 +569,12 @@ function attachBlockBoundary(layer, site) { this.visitorBlockThread = thread; this.previousVisitorBlock = activeVisitorBlockByThread.get(thread); this.visitorBlockActive = true; - activeVisitorBlockByThread.set(thread, { - visitor: args[0].toString(), block: block.toString() - }); + 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 @@ -534,6 +587,19 @@ function attachBlockBoundary(layer, site) { }, 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 @@ -765,6 +831,15 @@ function attachFieldAccept(compiler) { 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++; @@ -859,9 +934,11 @@ function attachMutationObserver(site, op) { 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: op === 'replace' ? args[1].toString() : - (op === 'replace_remove' ? args[2].toString() : null), + 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) @@ -1047,6 +1124,7 @@ function main() { (site ? site.address : 'not-exported')); } discoverFieldVtables(compiler); + discoverValueVtables(compiler); // The app's onCreate() has not run at agent load time. Resolve the // already-loaded shim lazily from compiler callbacks instead. loadPassiveShadow(); From 2fe8fca967e890c1177de7fd5a53503539c44120 Mon Sep 17 00:00:00 2001 From: Muhtasham Nawr al-Mahmud <72372229+mnalmahmud@users.noreply.github.com> Date: Sat, 21 Nov 2026 06:19:20 +0600 Subject: [PATCH 043/129] feat: deliver real int-field runtime events through bounded JNI sink and Frida RPC --- .github/workflows/art-fieldwatch-phase1.yml | 1 + art-fieldwatch-phase1/README.md | 36 ++++++++ .../ci/build-passive-shim.sh | 12 +++ art-fieldwatch-phase1/ci/smoke_test.py | 31 ++++++- art-fieldwatch-phase1/jit-boundary-probe.js | 15 ++++ art-fieldwatch-phase1/native/runtime-events.c | 83 +++++++++++++++++++ .../example/artfieldwatch/FieldEventSink.java | 18 ++++ .../example/artfieldwatch/FieldIRTarget.java | 42 ++++++++++ .../example/artfieldwatch/MainActivity.java | 10 +++ 9 files changed, 246 insertions(+), 2 deletions(-) create mode 100644 art-fieldwatch-phase1/native/runtime-events.c create mode 100644 art-fieldwatch-phase1/test/app/src/main/java/com/example/artfieldwatch/FieldEventSink.java diff --git a/.github/workflows/art-fieldwatch-phase1.yml b/.github/workflows/art-fieldwatch-phase1.yml index 5a0580e..c9e7f31 100644 --- a/.github/workflows/art-fieldwatch-phase1.yml +++ b/.github/workflows/art-fieldwatch-phase1.yml @@ -91,6 +91,7 @@ jobs: 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' - 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' diff --git a/art-fieldwatch-phase1/README.md b/art-fieldwatch-phase1/README.md index cafd872..298d476 100644 --- a/art-fieldwatch-phase1/README.md +++ b/art-fieldwatch-phase1/README.md @@ -517,3 +517,39 @@ 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/build-passive-shim.sh b/art-fieldwatch-phase1/ci/build-passive-shim.sh index 581af5f..a15a0e7 100644 --- a/art-fieldwatch-phase1/ci/build-passive-shim.sh +++ b/art-fieldwatch-phase1/ci/build-passive-shim.sh @@ -26,3 +26,15 @@ 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|Java_com_example_artfieldwatch_FieldEventSink_(recordInt|reset))' | + 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" diff --git a/art-fieldwatch-phase1/ci/smoke_test.py b/art-fieldwatch-phase1/ci/smoke_test.py index 5efae29..9191385 100644 --- a/art-fieldwatch-phase1/ci/smoke_test.py +++ b/art-fieldwatch-phase1/ci/smoke_test.py @@ -31,6 +31,7 @@ def main(): pid = device.spawn(['com.example.artfieldwatch']) record('host','spawned-pid='+str(pid)) session = device.attach(pid) + runtime_snapshot = None try: source = (BASE/'jit-boundary-probe.js').read_text() if os.environ.get('ARTWATCH_SHADOW_SHIM') == '1': @@ -45,6 +46,13 @@ def main(): # 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() + (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 @@ -61,8 +69,27 @@ def main(): 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: - raise AssertionError('App failed to load packaged native shadow library') + 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') + 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': diff --git a/art-fieldwatch-phase1/jit-boundary-probe.js b/art-fieldwatch-phase1/jit-boundary-probe.js index a86b536..7cd0838 100644 --- a/art-fieldwatch-phase1/jit-boundary-probe.js +++ b/art-fieldwatch-phase1/jit-boundary-probe.js @@ -1159,4 +1159,19 @@ function main() { 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 = { + 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/runtime-events.c b/art-fieldwatch-phase1/native/runtime-events.c new file mode 100644 index 0000000..1aa60c2 --- /dev/null +++ b/art-fieldwatch-phase1/native/runtime-events.c @@ -0,0 +1,83 @@ +// 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 + +#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; + +// 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); + 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; + 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); +} +// 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. +EVENT_EXPORT int artwatch_events_snapshot(char *out, uint32_t length) { + if (out == NULL || length < 512) return 0; + 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 stored = total < EVENT_CAPACITY ? total : EVENT_CAPACITY; + 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 < stored; ++i) { + if (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, + events[i].site, events[i].kind, 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; +} 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..87a35e5 --- /dev/null +++ b/art-fieldwatch-phase1/test/app/src/main/java/com/example/artfieldwatch/FieldEventSink.java @@ -0,0 +1,18 @@ +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 reset(); +} 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 index 7424e44..c3ebc45 100644 --- 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 @@ -59,6 +59,48 @@ public static int exerciseAlternating(int iterations) { 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; + } + + 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; diff --git a/art-fieldwatch-phase1/test/app/src/main/java/com/example/artfieldwatch/MainActivity.java b/art-fieldwatch-phase1/test/app/src/main/java/com/example/artfieldwatch/MainActivity.java index 5c26874..d9af7b2 100644 --- a/art-fieldwatch-phase1/test/app/src/main/java/com/example/artfieldwatch/MainActivity.java +++ b/art-fieldwatch-phase1/test/app/src/main/java/com/example/artfieldwatch/MainActivity.java @@ -20,7 +20,9 @@ protected void onCreate(Bundle state) { if (android.os.Build.VERSION.SDK_INT == 33) { try { System.loadLibrary("artwatch_shadow"); + System.loadLibrary("artwatch_events"); Log.i("ARTWATCH_CI","SHADOW_LIB_LOADED=true"); + Log.i("ARTWATCH_CI","EVENT_LIB_LOADED=true"); } catch (UnsatisfiedLinkError e) { Log.e("ARTWATCH_CI","SHADOW_LIB_LOAD_FAILED",e); } @@ -45,6 +47,14 @@ protected void onCreate(Bundle state) { 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 runtimeChecksum = FieldIRTarget.exerciseRuntimeEvents(); + Log.i("ARTWATCH_CI","RUNTIME_EVENTS_DONE count=256 checksum=" + + runtimeChecksum + " nullCheck=true"); + accumulator += runtimeChecksum; + } Log.i("ARTWATCH_CI","WARMUP_DONE checksum=" + accumulator); } catch (Throwable t) { Log.e("ARTWATCH_CI","WARMUP_FAILED",t); From 63b3c28577ef34fd9062324c87978f0604b0a2b3 Mon Sep 17 00:00:00 2001 From: Muhtasham Nawr al-Mahmud <72372229+mnalmahmud@users.noreply.github.com> Date: Sat, 21 Nov 2026 08:34:51 +0600 Subject: [PATCH 044/129] research: establish API33 P3 invoke insertion and correctness gates --- docs/art-fieldwatch/p3-injection-abi-gates.md | 143 ++++++++++++++++++ 1 file changed, 143 insertions(+) create mode 100644 docs/art-fieldwatch/p3-injection-abi-gates.md 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..5ef2af1 --- /dev/null +++ b/docs/art-fieldwatch/p3-injection-abi-gates.md @@ -0,0 +1,143 @@ +# 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/+/391e155a6936a05bd39b171031ec21d2dee62133/compiler/optimizing/nodes.cc) +- [AOSP nodes.h invoke metadata](https://android.googlesource.com/platform/art/+/b28c8749a52f4f3252fbfe8bfb5f9d7c7f980adf/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. From 888c3b1da6e73351fdfe99d4a1cc3b43d65a2c9b Mon Sep 17 00:00:00 2001 From: Muhtasham Nawr al-Mahmud <72372229+mnalmahmud@users.noreply.github.com> Date: Sat, 21 Nov 2026 08:35:07 +0600 Subject: [PATCH 045/129] docs: align P3 source references to Android 13 ART branch --- docs/art-fieldwatch/p3-injection-abi-gates.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/art-fieldwatch/p3-injection-abi-gates.md b/docs/art-fieldwatch/p3-injection-abi-gates.md index 5ef2af1..32b73eb 100644 --- a/docs/art-fieldwatch/p3-injection-abi-gates.md +++ b/docs/art-fieldwatch/p3-injection-abi-gates.md @@ -65,8 +65,8 @@ The first mutation remains **off by default**, exact-ELF-gated, and APK-fixture- 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/+/391e155a6936a05bd39b171031ec21d2dee62133/compiler/optimizing/nodes.cc) -- [AOSP nodes.h invoke metadata](https://android.googlesource.com/platform/art/+/b28c8749a52f4f3252fbfe8bfb5f9d7c7f980adf/compiler/optimizing/nodes.h) +- [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) From 083c3ec977e08f26abe2494ebc7c4a7b8fb801d1 Mon Sep 17 00:00:00 2001 From: Muhtasham Nawr al-Mahmud <72372229+mnalmahmud@users.noreply.github.com> Date: Sat, 21 Nov 2026 09:16:16 +0600 Subject: [PATCH 046/129] test: add uninstrumented P3 field canary --- art-fieldwatch-phase1/native/runtime-events.c | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/art-fieldwatch-phase1/native/runtime-events.c b/art-fieldwatch-phase1/native/runtime-events.c index 1aa60c2..2327851 100644 --- a/art-fieldwatch-phase1/native/runtime-events.c +++ b/art-fieldwatch-phase1/native/runtime-events.c @@ -51,6 +51,13 @@ Java_com_example_artfieldwatch_FieldEventSink_recordInt( 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. From 8f407e78299262e0165c4bf0caa999bd3383a36a Mon Sep 17 00:00:00 2001 From: Muhtasham Nawr al-Mahmud <72372229+mnalmahmud@users.noreply.github.com> Date: Sat, 21 Nov 2026 09:16:18 +0600 Subject: [PATCH 047/129] test: add uninstrumented P3 field canary --- .../src/main/java/com/example/artfieldwatch/FieldEventSink.java | 1 + 1 file changed, 1 insertion(+) 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 index 87a35e5..3c8031c 100644 --- 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 @@ -15,4 +15,5 @@ private FieldEventSink() {} public static native void recordInt(int site, int kind, int value); public static native void reset(); + public static native int eventCount(); } From 1d07077660d34ae10492d8969f27063c3f08603c Mon Sep 17 00:00:00 2001 From: Muhtasham Nawr al-Mahmud <72372229+mnalmahmud@users.noreply.github.com> Date: Sat, 21 Nov 2026 09:16:20 +0600 Subject: [PATCH 048/129] test: add uninstrumented P3 field canary --- .../example/artfieldwatch/FieldIRTarget.java | 33 +++++++++++++++++++ 1 file changed, 33 insertions(+) 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 index c3ebc45..678bead 100644 --- 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 @@ -72,6 +72,39 @@ public static int watchedOn(FieldIRTarget receiver, int x) { return observed; } + // 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 From f747ddd160398af6a94a81b18cd79be65d5a7e3f Mon Sep 17 00:00:00 2001 From: Muhtasham Nawr al-Mahmud <72372229+mnalmahmud@users.noreply.github.com> Date: Sat, 21 Nov 2026 09:16:27 +0600 Subject: [PATCH 049/129] test: validate silent field access before explicit event oracle --- .../src/main/java/com/example/artfieldwatch/MainActivity.java | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/art-fieldwatch-phase1/test/app/src/main/java/com/example/artfieldwatch/MainActivity.java b/art-fieldwatch-phase1/test/app/src/main/java/com/example/artfieldwatch/MainActivity.java index d9af7b2..da02e53 100644 --- a/art-fieldwatch-phase1/test/app/src/main/java/com/example/artfieldwatch/MainActivity.java +++ b/art-fieldwatch-phase1/test/app/src/main/java/com/example/artfieldwatch/MainActivity.java @@ -50,6 +50,10 @@ protected void onCreate(Bundle state) { // 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 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"); From a402b57088e23942aae9eaa5e15f4df63dbc674c Mon Sep 17 00:00:00 2001 From: Muhtasham Nawr al-Mahmud <72372229+mnalmahmud@users.noreply.github.com> Date: Sat, 21 Nov 2026 09:16:30 +0600 Subject: [PATCH 050/129] test: validate silent field access before explicit event oracle --- art-fieldwatch-phase1/ci/smoke_test.py | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/art-fieldwatch-phase1/ci/smoke_test.py b/art-fieldwatch-phase1/ci/smoke_test.py index 9191385..b5994d2 100644 --- a/art-fieldwatch-phase1/ci/smoke_test.py +++ b/art-fieldwatch-phase1/ci/smoke_test.py @@ -72,6 +72,11 @@ def main(): 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') + 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 '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') From 57f27913ed8eabc467dbc811c8f86baf6568b3ef Mon Sep 17 00:00:00 2001 From: Muhtasham Nawr al-Mahmud <72372229+mnalmahmud@users.noreply.github.com> Date: Sat, 21 Nov 2026 09:16:33 +0600 Subject: [PATCH 051/129] test: validate silent field access before explicit event oracle --- art-fieldwatch-phase1/ci/build-passive-shim.sh | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/art-fieldwatch-phase1/ci/build-passive-shim.sh b/art-fieldwatch-phase1/ci/build-passive-shim.sh index a15a0e7..31fbeed 100644 --- a/art-fieldwatch-phase1/ci/build-passive-shim.sh +++ b/art-fieldwatch-phase1/ci/build-passive-shim.sh @@ -34,7 +34,7 @@ echo "Native shadow library staged for APK packaging: $jni_dir" art-fieldwatch-phase1/native/runtime-events.c \ -o "$out/libartwatch_events.so" readelf -Ws "$out/libartwatch_events.so" | - grep -E '(artwatch_events_snapshot|Java_com_example_artfieldwatch_FieldEventSink_(recordInt|reset))' | + grep -E '(artwatch_events_snapshot|Java_com_example_artfieldwatch_FieldEventSink_(recordInt|reset|eventCount))' | 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" From a5d69302272b439f77f75a338625d751aa04c603 Mon Sep 17 00:00:00 2001 From: Muhtasham Nawr al-Mahmud <72372229+mnalmahmud@users.noreply.github.com> Date: Sat, 21 Nov 2026 09:16:41 +0600 Subject: [PATCH 052/129] research: capture P3 canary DEX and native IR invoke ABI symbols --- art-fieldwatch-phase1/ci/dex-inventory.sh | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/art-fieldwatch-phase1/ci/dex-inventory.sh b/art-fieldwatch-phase1/ci/dex-inventory.sh index 78c6ffc..4959f44 100644 --- a/art-fieldwatch-phase1/ci/dex-inventory.sh +++ b/art-fieldwatch-phase1/ci/dex-inventory.sh @@ -36,6 +36,20 @@ if "$analyzer" dex code --class com.example.artfieldwatch.FieldIRTarget "$apk" > 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." # 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 From e8fb07206fa7255ef6731fa179b1f0f7b49c6ba4 Mon Sep 17 00:00:00 2001 From: Muhtasham Nawr al-Mahmud <72372229+mnalmahmud@users.noreply.github.com> Date: Sat, 21 Nov 2026 09:16:44 +0600 Subject: [PATCH 053/129] research: capture P3 canary DEX and native IR invoke ABI symbols --- art-fieldwatch-phase1/ci/art-binary-inventory.sh | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/art-fieldwatch-phase1/ci/art-binary-inventory.sh b/art-fieldwatch-phase1/ci/art-binary-inventory.sh index 8b72935..4dc45e6 100644 --- a/art-fieldwatch-phase1/ci/art-binary-inventory.sh +++ b/art-fieldwatch-phase1/ci/art-binary-inventory.sh @@ -29,6 +29,10 @@ abi="$(adb shell getprop ro.product.cpu.abi | tr -d '\r')" 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)' | From a0c88215e92236c21c1afcc0194acd9d3f76a6c1 Mon Sep 17 00:00:00 2001 From: Muhtasham Nawr al-Mahmud <72372229+mnalmahmud@users.noreply.github.com> Date: Sat, 21 Nov 2026 09:16:53 +0600 Subject: [PATCH 054/129] research: observe compiler-created HInvokeStaticOrDirect without mutation --- art-fieldwatch-phase1/jit-boundary-probe.js | 40 +++++++++++++++++++++ 1 file changed, 40 insertions(+) diff --git a/art-fieldwatch-phase1/jit-boundary-probe.js b/art-fieldwatch-phase1/jit-boundary-probe.js index 7cd0838..547b528 100644 --- a/art-fieldwatch-phase1/jit-boundary-probe.js +++ b/art-fieldwatch-phase1/jit-boundary-probe.js @@ -57,6 +57,11 @@ 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 MAX_EXISTING_INVOKES = 80; +let existingInvokeCount = 0; const targetDexByMethod = new Map(); let backendVisitOrdinal = 0; const BACKEND_VISIT_LIMIT = 160; @@ -1027,6 +1032,40 @@ function attachBackendFieldVisitor(compiler, symbol, stage, expectedKind) { return false; } } +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); + 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 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:scope && scope.visitor === args[1].toString() + ? 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; + } +} function main() { const api = sdkLevel(); log('pid=' + Process.id + ' arch=' + Process.arch + @@ -1125,6 +1164,7 @@ function main() { } discoverFieldVtables(compiler); discoverValueVtables(compiler); + attachExistingInvokeObserver(compiler); // The app's onCreate() has not run at agent load time. Resolve the // already-loaded shim lazily from compiler callbacks instead. loadPassiveShadow(); From f09705ed5f9dcf8816e17420614eeb798b1a3f98 Mon Sep 17 00:00:00 2001 From: Muhtasham Nawr al-Mahmud <72372229+mnalmahmud@users.noreply.github.com> Date: Sat, 21 Nov 2026 09:17:08 +0600 Subject: [PATCH 055/129] fix: use literal awk DEX method regex for P3 canary --- art-fieldwatch-phase1/ci/dex-inventory.sh | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/art-fieldwatch-phase1/ci/dex-inventory.sh b/art-fieldwatch-phase1/ci/dex-inventory.sh index 4959f44..77adb58 100644 --- a/art-fieldwatch-phase1/ci/dex-inventory.sh +++ b/art-fieldwatch-phase1/ci/dex-inventory.sh @@ -36,8 +36,8 @@ if "$analyzer" dex code --class com.example.artfieldwatch.FieldIRTarget "$apk" > exit 1 fi echo "Verified release testViaIdentity DEX retains both iput and iget." - awk '/^\\.method.* p3CanaryOn\\(/ { inside=1; next } - inside && /^\\.end method/ { exit } + 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 From d476d94ed7501ab1cb1b3939d45fed8f86bfa70c Mon Sep 17 00:00:00 2001 From: Muhtasham Nawr al-Mahmud <72372229+mnalmahmud@users.noreply.github.com> Date: Sat, 21 Nov 2026 16:52:19 +0600 Subject: [PATCH 056/129] ci: retry transient adbd root reconnect after emulator boot --- .../ci/run-emulator-smoke.sh | 22 +++++++++++++++++-- 1 file changed, 20 insertions(+), 2 deletions(-) diff --git a/art-fieldwatch-phase1/ci/run-emulator-smoke.sh b/art-fieldwatch-phase1/ci/run-emulator-smoke.sh index 54245ed..fe36350 100644 --- a/art-fieldwatch-phase1/ci/run-emulator-smoke.sh +++ b/art-fieldwatch-phase1/ci/run-emulator-smoke.sh @@ -1,8 +1,26 @@ #!/usr/bin/env bash set -euo pipefail mkdir -p "${ARTWATCH_LOG_DIR:-/tmp/artwatch-logs}" -adb root -adb wait-for-device +# 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) ;; From 1f3f72dd1b026fb19067f3553082f686cd21c56c Mon Sep 17 00:00:00 2001 From: Muhtasham Nawr al-Mahmud <72372229+mnalmahmud@users.noreply.github.com> Date: Sat, 21 Nov 2026 16:52:29 +0600 Subject: [PATCH 057/129] ci: retry transient Gradle dependency-resolution failures --- .github/workflows/art-fieldwatch-phase1.yml | 15 ++++++++++++++- 1 file changed, 14 insertions(+), 1 deletion(-) diff --git a/.github/workflows/art-fieldwatch-phase1.yml b/.github/workflows/art-fieldwatch-phase1.yml index c9e7f31..6aa51e5 100644 --- a/.github/workflows/art-fieldwatch-phase1.yml +++ b/.github/workflows/art-fieldwatch-phase1.yml @@ -85,7 +85,20 @@ jobs: release) task=assembleRelease ;; *) exit 1 ;; esac - gradle -p art-fieldwatch-phase1/test ":app:$task" --no-daemon + # 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: | From bdb666e0282a27e7e7150c350fcc1da82d8af468 Mon Sep 17 00:00:00 2001 From: Muhtasham Nawr al-Mahmud <72372229+mnalmahmud@users.noreply.github.com> Date: Sat, 21 Nov 2026 16:52:44 +0600 Subject: [PATCH 058/129] research: count compiler invoke SSA nodes per JIT compilation --- art-fieldwatch-phase1/jit-boundary-probe.js | 21 +++++++++++++++++++-- 1 file changed, 19 insertions(+), 2 deletions(-) diff --git a/art-fieldwatch-phase1/jit-boundary-probe.js b/art-fieldwatch-phase1/jit-boundary-probe.js index 547b528..a4ce004 100644 --- a/art-fieldwatch-phase1/jit-boundary-probe.js +++ b/art-fieldwatch-phase1/jit-boundary-probe.js @@ -231,6 +231,8 @@ function attach(layer, site) { this.mutationCountsAtEnter = {...mutationHookCounts}; targetStates.set(this.nativeThread, { method: this.method, kind: this.compilationKind, + existingInvokeVisits: 0, existingInvokeNodes: new Set(), + existingInvokeBlockVisits: 0, seenVisits: new Set(), seenKinds: new Set(), uniqueNodes: new Set(), visitsByPhase: {}, mutations: [], reported: 0, optimizationEntries: 0, lseInvocations: 0, @@ -257,6 +259,14 @@ function attach(layer, site) { onLeave(ret) { if (layer === 'compiler') { const state = targetStates.get(this.nativeThread); + 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, + compilationSucceeded:ret.toInt32() !== 0}); + } if (state && targetMethodPointers.has(this.method)) { send({type: 'artwatch-target-summary', method: this.method, compilationKind: this.compilationKind, @@ -1049,13 +1059,20 @@ function attachExistingInvokeObserver(compiler) { 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); + 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:scope && scope.visitor === args[1].toString() - ? scope.block : null}); + block:matchesBlock ? scope.block : null}); } }); send({type:'artwatch-hook-attached',layer:'existing_invoke_accept', From ed8552a64334f47a279ab034a4e7f85a0727812b Mon Sep 17 00:00:00 2001 From: Muhtasham Nawr al-Mahmud <72372229+mnalmahmud@users.noreply.github.com> Date: Sat, 21 Nov 2026 16:52:54 +0600 Subject: [PATCH 059/129] test: require actual compiler-built invoke nodes on API33 --- art-fieldwatch-phase1/ci/smoke_test.py | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) diff --git a/art-fieldwatch-phase1/ci/smoke_test.py b/art-fieldwatch-phase1/ci/smoke_test.py index b5994d2..87ccc94 100644 --- a/art-fieldwatch-phase1/ci/smoke_test.py +++ b/art-fieldwatch-phase1/ci/smoke_test.py @@ -137,6 +137,31 @@ def main(): payloads.append(m['payload']) except (ValueError, TypeError): continue + # 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') + 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')} From 6287ad805771d1bdddcf62db9fbcad3c0b8e895d Mon Sep 17 00:00:00 2001 From: Muhtasham Nawr al-Mahmud <72372229+mnalmahmud@users.noreply.github.com> Date: Sat, 21 Nov 2026 17:11:23 +0600 Subject: [PATCH 060/129] ci: serialize emulator matrix and supersede old runs to avoid Maven 429 --- .github/workflows/art-fieldwatch-phase1.yml | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/.github/workflows/art-fieldwatch-phase1.yml b/.github/workflows/art-fieldwatch-phase1.yml index 6aa51e5..8b0cafc 100644 --- a/.github/workflows/art-fieldwatch-phase1.yml +++ b/.github/workflows/art-fieldwatch-phase1.yml @@ -10,6 +10,11 @@ on: 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 @@ -25,6 +30,9 @@ jobs: 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 From 2e48b960eae7725ab9163fe39cca76424ad47e24 Mon Sep 17 00:00:00 2001 From: Muhtasham Nawr al-Mahmud <72372229+mnalmahmud@users.noreply.github.com> Date: Sat, 21 Nov 2026 17:11:47 +0600 Subject: [PATCH 061/129] research: correlate compiler invoke nodes with x64 backend code emission --- art-fieldwatch-phase1/jit-boundary-probe.js | 45 +++++++++++++++++++++ 1 file changed, 45 insertions(+) diff --git a/art-fieldwatch-phase1/jit-boundary-probe.js b/art-fieldwatch-phase1/jit-boundary-probe.js index a4ce004..877a851 100644 --- a/art-fieldwatch-phase1/jit-boundary-probe.js +++ b/art-fieldwatch-phase1/jit-boundary-probe.js @@ -60,6 +60,10 @@ 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; const targetDexByMethod = new Map(); @@ -233,6 +237,8 @@ function attach(layer, site) { method: this.method, kind: this.compilationKind, existingInvokeVisits: 0, existingInvokeNodes: new Set(), existingInvokeBlockVisits: 0, + existingInvokeLocations: new Set(), + existingInvokeEmitted: new Set(), seenVisits: new Set(), seenKinds: new Set(), uniqueNodes: new Set(), visitsByPhase: {}, mutations: [], reported: 0, optimizationEntries: 0, lseInvocations: 0, @@ -265,6 +271,9 @@ function attach(layer, site) { visits:state.existingInvokeVisits, uniqueNodes:state.existingInvokeNodes.size, blockCorrelated:state.existingInvokeBlockVisits, + backendLocations:state.existingInvokeLocations.size, + backendEmitted:state.existingInvokeEmitted.size, + emittedInvokeNodes:[...state.existingInvokeEmitted].slice(0,12), compilationSucceeded:ret.toInt32() !== 0}); } if (state && targetMethodPointers.has(this.method)) { @@ -1083,6 +1092,40 @@ function attachExistingInvokeObserver(compiler) { 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; + } +} function main() { const api = sdkLevel(); log('pid=' + Process.id + ' arch=' + Process.arch + @@ -1182,6 +1225,8 @@ function main() { discoverFieldVtables(compiler); discoverValueVtables(compiler); attachExistingInvokeObserver(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(); From 29e4c49b8d57cb949f6585938eb36576cb22db04 Mon Sep 17 00:00:00 2001 From: Muhtasham Nawr al-Mahmud <72372229+mnalmahmud@users.noreply.github.com> Date: Sat, 21 Nov 2026 17:11:57 +0600 Subject: [PATCH 062/129] test: require compiler-created Java invokes to reach x64 code emission --- art-fieldwatch-phase1/ci/smoke_test.py | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/art-fieldwatch-phase1/ci/smoke_test.py b/art-fieldwatch-phase1/ci/smoke_test.py index 87ccc94..5f891aa 100644 --- a/art-fieldwatch-phase1/ci/smoke_test.py +++ b/art-fieldwatch-phase1/ci/smoke_test.py @@ -159,6 +159,23 @@ def main(): 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') + 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)}') From d3e4e12c42362cc923b7776fe0d9584a9cdbc2bd Mon Sep 17 00:00:00 2001 From: Muhtasham Nawr al-Mahmud <72372229+mnalmahmud@users.noreply.github.com> Date: Sat, 21 Nov 2026 17:19:30 +0600 Subject: [PATCH 063/129] test: add same-graph resolved JNI invoke template for P3 clone injection --- art-fieldwatch-phase1/native/runtime-events.c | 3 ++ .../example/artfieldwatch/FieldIRTarget.java | 34 +++++++++++++++++++ .../example/artfieldwatch/MainActivity.java | 4 +++ 3 files changed, 41 insertions(+) diff --git a/art-fieldwatch-phase1/native/runtime-events.c b/art-fieldwatch-phase1/native/runtime-events.c index 2327851..056311f 100644 --- a/art-fieldwatch-phase1/native/runtime-events.c +++ b/art-fieldwatch-phase1/native/runtime-events.c @@ -40,6 +40,9 @@ 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) return; uint32_t index = atomic_fetch_add_explicit(&next_index, 1u, memory_order_relaxed); if (index >= EVENT_CAPACITY) { 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 index 678bead..a027f2e 100644 --- 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 @@ -72,6 +72,40 @@ public static int watchedOn(FieldIRTarget receiver, int x) { 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; + int observed = identity(receiver).value; + FieldEventSink.recordInt(0, 0, observed); + return observed; + } + + public static int exerciseP3TemplateCarrier() { + FieldIRTarget target = new FieldIRTarget(); + for (int i = 0; i < 100000; i++) { + if (p3TemplateCarrierOn(target, i) != i) + throw new AssertionError("P3 template warmup mismatch: " + i); + } + 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 (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; diff --git a/art-fieldwatch-phase1/test/app/src/main/java/com/example/artfieldwatch/MainActivity.java b/art-fieldwatch-phase1/test/app/src/main/java/com/example/artfieldwatch/MainActivity.java index da02e53..ec21f02 100644 --- a/art-fieldwatch-phase1/test/app/src/main/java/com/example/artfieldwatch/MainActivity.java +++ b/art-fieldwatch-phase1/test/app/src/main/java/com/example/artfieldwatch/MainActivity.java @@ -50,6 +50,10 @@ protected void onCreate(Bundle state) { // 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(); + Log.i("ARTWATCH_CI","P3_TEMPLATE_DONE count=0 checksum=" + + carrierChecksum + " nullCheck=true"); + accumulator += carrierChecksum; int canaryChecksum = FieldIRTarget.exerciseP3UninstrumentedCanary(); Log.i("ARTWATCH_CI","P3_CANARY_DONE count=0 checksum=" + canaryChecksum + " nullCheck=true"); From fa1fd0b7f56bd0c22aaaf678afbe9179e72fdfd7 Mon Sep 17 00:00:00 2001 From: Muhtasham Nawr al-Mahmud <72372229+mnalmahmud@users.noreply.github.com> Date: Sat, 21 Nov 2026 17:19:39 +0600 Subject: [PATCH 064/129] test: assert P3 invoke template runs without native event records --- art-fieldwatch-phase1/ci/smoke_test.py | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/art-fieldwatch-phase1/ci/smoke_test.py b/art-fieldwatch-phase1/ci/smoke_test.py index 5f891aa..052ee7b 100644 --- a/art-fieldwatch-phase1/ci/smoke_test.py +++ b/art-fieldwatch-phase1/ci/smoke_test.py @@ -72,6 +72,11 @@ def main(): 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') + template_marker = 'P3_TEMPLATE_DONE count=0 checksum=25280 nullCheck=true' + if template_marker not in logs.stdout: + raise AssertionError('Resolved P3 invoke template did not run with zero events') + 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') From d6cac84ada82202f95ab39f85967f876f124d82f Mon Sep 17 00:00:00 2001 From: Muhtasham Nawr al-Mahmud <72372229+mnalmahmud@users.noreply.github.com> Date: Sat, 21 Nov 2026 17:19:51 +0600 Subject: [PATCH 065/129] test: verify P3 template invoke survives D8 in release DEX --- art-fieldwatch-phase1/ci/dex-inventory.sh | 15 ++++++++++++++- 1 file changed, 14 insertions(+), 1 deletion(-) diff --git a/art-fieldwatch-phase1/ci/dex-inventory.sh b/art-fieldwatch-phase1/ci/dex-inventory.sh index 77adb58..2680112 100644 --- a/art-fieldwatch-phase1/ci/dex-inventory.sh +++ b/art-fieldwatch-phase1/ci/dex-inventory.sh @@ -50,12 +50,25 @@ if "$analyzer" dex code --class com.example.artfieldwatch.FieldIRTarget "$apk" > 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 && /^\.end method/ { exit } inside { print } ' "$out/fieldir-$variant.smali" > "$out/fieldir-release-$method.smali" if ! grep -q 'iput' "$out/fieldir-release-$method.smali" || From 7674c88213c613cf2e0ddf574681c1cc35b32ada Mon Sep 17 00:00:00 2001 From: Muhtasham Nawr al-Mahmud <72372229+mnalmahmud@users.noreply.github.com> Date: Sat, 21 Nov 2026 17:20:48 +0600 Subject: [PATCH 066/129] feat(p3): implement source-matched guarded ART invoke cloning mutation --- .../native/p3-clone-injector-art.cc | 109 ++++++++++++++++++ 1 file changed, 109 insertions(+) create mode 100644 art-fieldwatch-phase1/native/p3-clone-injector-art.cc 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..d80584c --- /dev/null +++ b/art-fieldwatch-phase1/native/p3-clone-injector-art.cc @@ -0,0 +1,109 @@ +// 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; +} + +} // namespace artwatch_p3 +} // namespace art From 1d6a53ac2bf0646302e354baa81883eaf568bce1 Mon Sep 17 00:00:00 2001 From: Muhtasham Nawr al-Mahmud <72372229+mnalmahmud@users.noreply.github.com> Date: Sat, 21 Nov 2026 17:21:18 +0600 Subject: [PATCH 067/129] docs: record guarded HInvoke clone mutation source and deployment gates --- docs/art-fieldwatch/p3-injection-abi-gates.md | 49 +++++++++++++++++++ 1 file changed, 49 insertions(+) diff --git a/docs/art-fieldwatch/p3-injection-abi-gates.md b/docs/art-fieldwatch/p3-injection-abi-gates.md index 32b73eb..3d850a0 100644 --- a/docs/art-fieldwatch/p3-injection-abi-gates.md +++ b/docs/art-fieldwatch/p3-injection-abi-gates.md @@ -141,3 +141,52 @@ 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. From bb070e082e465dc0c0a13bc7e27e26d9e8629651 Mon Sep 17 00:00:00 2001 From: Muhtasham Nawr al-Mahmud <72372229+mnalmahmud@users.noreply.github.com> Date: Sat, 21 Nov 2026 17:26:58 +0600 Subject: [PATCH 068/129] feat(p3): select a unique same-DEX invoke template from live HGraph --- .../native/p3-clone-injector-art.cc | 50 +++++++++++++++++++ 1 file changed, 50 insertions(+) diff --git a/art-fieldwatch-phase1/native/p3-clone-injector-art.cc b/art-fieldwatch-phase1/native/p3-clone-injector-art.cc index d80584c..a53f5d8 100644 --- a/art-fieldwatch-phase1/native/p3-clone-injector-art.cc +++ b/art-fieldwatch-phase1/native/p3-clone-injector-art.cc @@ -105,5 +105,55 @@ CloneResult CloneIntReadFromResolvedTemplate( 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); +} + } // namespace artwatch_p3 } // namespace art From 1b2ed95ba0a7dacaff44f1c0ea388d9e9fd54b33 Mon Sep 17 00:00:00 2001 From: Muhtasham Nawr al-Mahmud <72372229+mnalmahmud@users.noreply.github.com> Date: Sat, 21 Nov 2026 22:55:12 +0600 Subject: [PATCH 069/129] research(p3): verify field-get/invoke adjacency with gated live ART links --- art-fieldwatch-phase1/ci/smoke_test.py | 7 +++ art-fieldwatch-phase1/jit-boundary-probe.js | 34 ++++++++++++++- art-fieldwatch-phase1/native/passive-shadow.c | 43 +++++++++++++++++++ docs/art-fieldwatch/p3-injection-abi-gates.md | 14 ++++++ 4 files changed, 96 insertions(+), 2 deletions(-) diff --git a/art-fieldwatch-phase1/ci/smoke_test.py b/art-fieldwatch-phase1/ci/smoke_test.py index 052ee7b..a5e9402 100644 --- a/art-fieldwatch-phase1/ci/smoke_test.py +++ b/art-fieldwatch-phase1/ci/smoke_test.py @@ -179,6 +179,13 @@ def main(): 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') + record('host','ART P3 linked get/invoke probes=' + + str(sum(v.get('adjacencyProbes',0) for v in invoke_summaries)) + + ' adjacent=' + + str(sum(v.get('adjacencyMatches',0) for v in invoke_summaries))) 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)} ' diff --git a/art-fieldwatch-phase1/jit-boundary-probe.js b/art-fieldwatch-phase1/jit-boundary-probe.js index 877a851..7b925b0 100644 --- a/art-fieldwatch-phase1/jit-boundary-probe.js +++ b/art-fieldwatch-phase1/jit-boundary-probe.js @@ -173,7 +173,9 @@ function loadPassiveShadow() { 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']) + block: exported('artwatch_shadow_block','int',['pointer','pointer','pointer']), + linkedGetInvoke: exported('artwatch_shadow_linked_get_invoke','int', + ['pointer','pointer','pointer','pointer']) }; send({type:'artwatch-shadow-init',ready:true,source:'native', buildIdVerified:true,mutable:false}); @@ -239,6 +241,8 @@ function attach(layer, site) { existingInvokeBlockVisits: 0, existingInvokeLocations: new Set(), existingInvokeEmitted: new Set(), + adjacencyProbes: 0, adjacencyMatches: 0, + adjacencyRejected: 0, adjacencySamples: [], seenVisits: new Set(), seenKinds: new Set(), uniqueNodes: new Set(), visitsByPhase: {}, mutations: [], reported: 0, optimizationEntries: 0, lseInvocations: 0, @@ -273,6 +277,10 @@ function attach(layer, site) { blockCorrelated:state.existingInvokeBlockVisits, backendLocations:state.existingInvokeLocations.size, backendEmitted:state.existingInvokeEmitted.size, + adjacencyProbes:state.adjacencyProbes, + adjacencyMatches:state.adjacencyMatches, + adjacencyRejected:state.adjacencyRejected, + adjacencySamples:state.adjacencySamples, emittedInvokeNodes:[...state.existingInvokeEmitted].slice(0,12), compilationSucceeded:ret.toInt32() !== 0}); } @@ -596,7 +604,7 @@ function attachBlockBoundary(layer, site) { this.visitorBlockRecord = { visitor: args[0].toString(), block: block.toString(), callOrdinal: ++state.blockVisitOrdinal, - fieldCount: 0, fields: [] + fieldCount: 0, fields: [], lastGet: null }; activeVisitorBlockByThread.set(thread,this.visitorBlockRecord); if (state.visitorBlocks.size < 4096) @@ -855,6 +863,8 @@ function attachFieldAccept(compiler) { const isGet = /FieldGet$/.test(kind); const isSet = /FieldSet$/.test(kind); if (isGet || isSet) { + if (kind === 'HInstanceFieldGet') + currentBlock.lastGet = args[0]; // Captures only relative order of *field* instructions // encountered by one real VisitBasicBlock traversal. // Other IR instructions and phi nodes are omitted. @@ -1058,6 +1068,7 @@ function attachExistingInvokeObserver(compiler) { 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) { @@ -1070,6 +1081,25 @@ function attachExistingInvokeObserver(compiler) { const scope = activeVisitorBlockByThread.get(thread); const matchesBlock = !!scope && scope.visitor === args[1].toString(); const state = targetStates.get(thread); + // Exact-ELF-gated, source-layout test. Do not retain HInstruction* + // past this live invocation. An Accept() callback alone cannot + // establish linked-list adjacency or matching HBasicBlock*. + if (state && matchesBlock && scope.lastGet && getVtable && + shadowShim && shadowShim.linkedGetInvoke && + state.adjacencyProbes < 256) { + state.adjacencyProbes++; + const rc = shadowShim.linkedGetInvoke( + scope.lastGet, args[0], getVtable.address, vt.address); + if (rc === 1) { + state.adjacencyMatches++; + if (state.adjacencySamples.length < 12) + state.adjacencySamples.push({ + get:scope.lastGet.toString(),invoke:args[0].toString(), + block:scope.block}); + } else if (rc < 0) { + state.adjacencyRejected++; + } + } if (state) { state.existingInvokeVisits++; if (state.existingInvokeNodes.size < 4096) diff --git a/art-fieldwatch-phase1/native/passive-shadow.c b/art-fieldwatch-phase1/native/passive-shadow.c index 8f3a5a7..cf18dd5 100644 --- a/art-fieldwatch-phase1/native/passive-shadow.c +++ b/art-fieldwatch-phase1/native/passive-shadow.c @@ -188,6 +188,49 @@ EXPORT int artwatch_shadow_node(const void *node, const void *vt_symbol, int kin } 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; +} // 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; diff --git a/docs/art-fieldwatch/p3-injection-abi-gates.md b/docs/art-fieldwatch/p3-injection-abi-gates.md index 3d850a0..dbae290 100644 --- a/docs/art-fieldwatch/p3-injection-abi-gates.md +++ b/docs/art-fieldwatch/p3-injection-abi-gates.md @@ -190,3 +190,17 @@ 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. From 42c5d0ee2c0ceed9cda9cb068683872577c333f8 Mon Sep 17 00:00:00 2001 From: Muhtasham Nawr al-Mahmud <72372229+mnalmahmud@users.noreply.github.com> Date: Sun, 22 Nov 2026 00:17:09 +0600 Subject: [PATCH 070/129] fix(p3): inspect live invoke predecessors instead of relying on stale field visitor state --- art-fieldwatch-phase1/jit-boundary-probe.js | 91 +++++++++++++++++---- 1 file changed, 73 insertions(+), 18 deletions(-) diff --git a/art-fieldwatch-phase1/jit-boundary-probe.js b/art-fieldwatch-phase1/jit-boundary-probe.js index 7b925b0..f276579 100644 --- a/art-fieldwatch-phase1/jit-boundary-probe.js +++ b/art-fieldwatch-phase1/jit-boundary-probe.js @@ -243,6 +243,9 @@ function attach(layer, site) { existingInvokeEmitted: new Set(), adjacencyProbes: 0, adjacencyMatches: 0, adjacencyRejected: 0, adjacencySamples: [], + adjacencyWithin8: 0, adjacencyBlockMismatch: 0, + adjacencyBrokenLinks: 0, adjacencyNoGetWithin8: 0, + adjacencyPreviousSamples: [], seenVisits: new Set(), seenKinds: new Set(), uniqueNodes: new Set(), visitsByPhase: {}, mutations: [], reported: 0, optimizationEntries: 0, lseInvocations: 0, @@ -281,6 +284,11 @@ function attach(layer, site) { adjacencyMatches:state.adjacencyMatches, adjacencyRejected:state.adjacencyRejected, adjacencySamples:state.adjacencySamples, + adjacencyWithin8:state.adjacencyWithin8, + adjacencyBlockMismatch:state.adjacencyBlockMismatch, + adjacencyBrokenLinks:state.adjacencyBrokenLinks, + adjacencyNoGetWithin8:state.adjacencyNoGetWithin8, + adjacencyPreviousSamples:state.adjacencyPreviousSamples, emittedInvokeNodes:[...state.existingInvokeEmitted].slice(0,12), compilationSucceeded:ret.toInt32() !== 0}); } @@ -604,7 +612,7 @@ function attachBlockBoundary(layer, site) { this.visitorBlockRecord = { visitor: args[0].toString(), block: block.toString(), callOrdinal: ++state.blockVisitOrdinal, - fieldCount: 0, fields: [], lastGet: null + fieldCount: 0, fields: [] }; activeVisitorBlockByThread.set(thread,this.visitorBlockRecord); if (state.visitorBlocks.size < 4096) @@ -863,8 +871,6 @@ function attachFieldAccept(compiler) { const isGet = /FieldGet$/.test(kind); const isSet = /FieldSet$/.test(kind); if (isGet || isSet) { - if (kind === 'HInstanceFieldGet') - currentBlock.lastGet = args[0]; // Captures only relative order of *field* instructions // encountered by one real VisitBasicBlock traversal. // Other IR instructions and phi nodes are omitted. @@ -1061,6 +1067,50 @@ function attachBackendFieldVisitor(compiler, symbol, stage, expectedKind) { 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 = ptr(scope.block); + const expectedGet = getVtable.address.add(2 * size); + let block; + try { + block = node.add(3 * size).readPointer(); + if (!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); @@ -1081,24 +1131,29 @@ function attachExistingInvokeObserver(compiler) { const scope = activeVisitorBlockByThread.get(thread); const matchesBlock = !!scope && scope.visitor === args[1].toString(); const state = targetStates.get(thread); - // Exact-ELF-gated, source-layout test. Do not retain HInstruction* - // past this live invocation. An Accept() callback alone cannot - // establish linked-list adjacency or matching HBasicBlock*. - if (state && matchesBlock && scope.lastGet && getVtable && - shadowShim && shadowShim.linkedGetInvoke && + // For this read-only layout walk, require the native shim's exact + // runtime/compiler ELF IDs; never probe unknown Android builds. + if (state && matchesBlock && getVtable && shadowShim && state.adjacencyProbes < 256) { + const seen = observeInvokePredecessors( + args[0],scope,getVtable,vt); state.adjacencyProbes++; - const rc = shadowShim.linkedGetInvoke( - scope.lastGet, args[0], getVtable.address, vt.address); - if (rc === 1) { - state.adjacencyMatches++; - if (state.adjacencySamples.length < 12) - state.adjacencySamples.push({ - get:scope.lastGet.toString(),invoke:args[0].toString(), - block:scope.block}); - } else if (rc < 0) { - state.adjacencyRejected++; + 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 && state.adjacencySamples.length < 12) + state.adjacencySamples.push({ + get:seen.get,invoke:args[0].toString(), + block:scope.block,depth:seen.depth}); + if (state.adjacencyPreviousSamples.length < 12) + state.adjacencyPreviousSamples.push({ + node:args[0].toString(),reason:seen.reason, + depth:seen.depth || null, block:scope.block}); } if (state) { state.existingInvokeVisits++; From 63f57baa2b68f4a7512d1de49589b7aab85574a2 Mon Sep 17 00:00:00 2001 From: Muhtasham Nawr al-Mahmud <72372229+mnalmahmud@users.noreply.github.com> Date: Sun, 22 Nov 2026 00:17:37 +0600 Subject: [PATCH 071/129] test(p3): require actual live invoke predecessor scans and classify outcomes --- art-fieldwatch-phase1/ci/smoke_test.py | 21 +++++++++++++++++---- 1 file changed, 17 insertions(+), 4 deletions(-) diff --git a/art-fieldwatch-phase1/ci/smoke_test.py b/art-fieldwatch-phase1/ci/smoke_test.py index a5e9402..0a83e81 100644 --- a/art-fieldwatch-phase1/ci/smoke_test.py +++ b/art-fieldwatch-phase1/ci/smoke_test.py @@ -182,10 +182,23 @@ def main(): 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') - record('host','ART P3 linked get/invoke probes=' + - str(sum(v.get('adjacencyProbes',0) for v in invoke_summaries)) + - ' adjacent=' + - str(sum(v.get('adjacencyMatches',0) for v in invoke_summaries))) + 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') 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)} ' From 43c36ef18006ecbeaf69fe1e69e1b7974221ac98 Mon Sep 17 00:00:00 2001 From: Muhtasham Nawr al-Mahmud <72372229+mnalmahmud@users.noreply.github.com> Date: Sun, 22 Nov 2026 01:15:09 +0600 Subject: [PATCH 072/129] fix(p3): observe baseline JIT invoke predecessor chains in target field methods --- art-fieldwatch-phase1/jit-boundary-probe.js | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/art-fieldwatch-phase1/jit-boundary-probe.js b/art-fieldwatch-phase1/jit-boundary-probe.js index f276579..1abcace 100644 --- a/art-fieldwatch-phase1/jit-boundary-probe.js +++ b/art-fieldwatch-phase1/jit-boundary-probe.js @@ -289,6 +289,7 @@ function attach(layer, site) { adjacencyBrokenLinks:state.adjacencyBrokenLinks, adjacencyNoGetWithin8:state.adjacencyNoGetWithin8, adjacencyPreviousSamples:state.adjacencyPreviousSamples, + fieldTarget:targetMethodPointers.has(this.method), emittedInvokeNodes:[...state.existingInvokeEmitted].slice(0,12), compilationSucceeded:ret.toInt32() !== 0}); } @@ -596,7 +597,11 @@ function attachBlockBoundary(layer, site) { if (state.constructedBlocks.size < 4096) state.constructedBlocks.add(block.toString()); } else { - if (!optimizationByThread.has(thread)) return; + // 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') { From 9bf233ade4535c920d5d90a2a319a33d548c5076 Mon Sep 17 00:00:00 2001 From: Muhtasham Nawr al-Mahmud <72372229+mnalmahmud@users.noreply.github.com> Date: Sun, 22 Nov 2026 01:15:36 +0600 Subject: [PATCH 073/129] research(p3): inspect invoke predecessor links directly for baseline field-target compilations --- art-fieldwatch-phase1/jit-boundary-probe.js | 25 +++++++++++++++------ 1 file changed, 18 insertions(+), 7 deletions(-) diff --git a/art-fieldwatch-phase1/jit-boundary-probe.js b/art-fieldwatch-phase1/jit-boundary-probe.js index 1abcace..4d01c87 100644 --- a/art-fieldwatch-phase1/jit-boundary-probe.js +++ b/art-fieldwatch-phase1/jit-boundary-probe.js @@ -245,7 +245,7 @@ function attach(layer, site) { adjacencyRejected: 0, adjacencySamples: [], adjacencyWithin8: 0, adjacencyBlockMismatch: 0, adjacencyBrokenLinks: 0, adjacencyNoGetWithin8: 0, - adjacencyPreviousSamples: [], + adjacencyPreviousSamples: [], targetAdjacencyProbes: 0, seenVisits: new Set(), seenKinds: new Set(), uniqueNodes: new Set(), visitsByPhase: {}, mutations: [], reported: 0, optimizationEntries: 0, lseInvocations: 0, @@ -290,6 +290,7 @@ function attach(layer, site) { adjacencyNoGetWithin8:state.adjacencyNoGetWithin8, adjacencyPreviousSamples:state.adjacencyPreviousSamples, fieldTarget:targetMethodPointers.has(this.method), + targetAdjacencyProbes:state.targetAdjacencyProbes, emittedInvokeNodes:[...state.existingInvokeEmitted].slice(0,12), compilationSucceeded:ret.toInt32() !== 0}); } @@ -1084,12 +1085,15 @@ function attachBackendFieldVisitor(compiler, symbol, stage, expectedKind) { // This is read-only and never retains HInstruction* past this callback. function observeInvokePredecessors(node, scope, getVtable, invokeVtable) { const size = Process.pointerSize; - const expectedBlock = ptr(scope.block); + 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.equals(expectedBlock)) return {reason:'block'}; + 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(); @@ -1138,11 +1142,16 @@ function attachExistingInvokeObserver(compiler) { 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. - if (state && matchesBlock && getVtable && shadowShim && + 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],scope,getVtable,vt); + 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; @@ -1154,11 +1163,13 @@ function attachExistingInvokeObserver(compiler) { if (seen.get && state.adjacencySamples.length < 12) state.adjacencySamples.push({ get:seen.get,invoke:args[0].toString(), - block:scope.block,depth:seen.depth}); + block:matchesBlock ? scope.block : null,depth:seen.depth, + fieldTarget}); if (state.adjacencyPreviousSamples.length < 12) state.adjacencyPreviousSamples.push({ node:args[0].toString(),reason:seen.reason, - depth:seen.depth || null, block:scope.block}); + depth:seen.depth || null, + block:matchesBlock ? scope.block : null,fieldTarget}); } if (state) { state.existingInvokeVisits++; From f30db50116944e4544e12c69fe389177dade79d6 Mon Sep 17 00:00:00 2001 From: Muhtasham Nawr al-Mahmud <72372229+mnalmahmud@users.noreply.github.com> Date: Sun, 22 Nov 2026 01:15:46 +0600 Subject: [PATCH 074/129] test(p3): fail if field-target compiler invokes evade predecessor sampling --- art-fieldwatch-phase1/ci/smoke_test.py | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/art-fieldwatch-phase1/ci/smoke_test.py b/art-fieldwatch-phase1/ci/smoke_test.py index 0a83e81..8066754 100644 --- a/art-fieldwatch-phase1/ci/smoke_test.py +++ b/art-fieldwatch-phase1/ci/smoke_test.py @@ -199,6 +199,14 @@ def main(): 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') 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)} ' From a9cb67e86de809854a5cb0d4f7dff991c7b0c134 Mon Sep 17 00:00:00 2001 From: Muhtasham Nawr al-Mahmud <72372229+mnalmahmud@users.noreply.github.com> Date: Sun, 22 Nov 2026 01:36:51 +0600 Subject: [PATCH 075/129] research(p3): read exact-build gated field and invoke DEX PCs --- art-fieldwatch-phase1/native/passive-shadow.c | 25 +++++++++++++++++++ 1 file changed, 25 insertions(+) diff --git a/art-fieldwatch-phase1/native/passive-shadow.c b/art-fieldwatch-phase1/native/passive-shadow.c index cf18dd5..781fc55 100644 --- a/art-fieldwatch-phase1/native/passive-shadow.c +++ b/art-fieldwatch-phase1/native/passive-shadow.c @@ -231,6 +231,31 @@ EXPORT int artwatch_shadow_linked_get_invoke( 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; +} // 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; From 8c3ef5ed6009e6323270d696a684dea80e516f12 Mon Sep 17 00:00:00 2001 From: Muhtasham Nawr al-Mahmud <72372229+mnalmahmud@users.noreply.github.com> Date: Sun, 22 Nov 2026 14:17:25 +0600 Subject: [PATCH 076/129] research(p3): join live get/invoke DEX PCs against field builder method identity --- art-fieldwatch-phase1/jit-boundary-probe.js | 51 ++++++++++++++++++--- 1 file changed, 45 insertions(+), 6 deletions(-) diff --git a/art-fieldwatch-phase1/jit-boundary-probe.js b/art-fieldwatch-phase1/jit-boundary-probe.js index 4d01c87..4d32d66 100644 --- a/art-fieldwatch-phase1/jit-boundary-probe.js +++ b/art-fieldwatch-phase1/jit-boundary-probe.js @@ -175,7 +175,9 @@ function loadPassiveShadow() { 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']) + ['pointer','pointer','pointer','pointer']), + instructionDexPc: exported('artwatch_shadow_instruction_dex_pc','int', + ['pointer','pointer','pointer']) }; send({type:'artwatch-shadow-init',ready:true,source:'native', buildIdVerified:true,mutable:false}); @@ -246,6 +248,8 @@ function attach(layer, site) { 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, @@ -291,6 +295,9 @@ function attach(layer, site) { 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}); } @@ -1160,11 +1167,43 @@ function attachExistingInvokeObserver(compiler) { case 'no-get': state.adjacencyNoGetWithin8++; break; default: state.adjacencyRejected++; break; } - if (seen.get && state.adjacencySamples.length < 12) - state.adjacencySamples.push({ - get:seen.get,invoke:args[0].toString(), - block:matchesBlock ? scope.block : null,depth:seen.depth, - fieldTarget}); + 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, From 03f9be29bf6c48fcf780c76c1f0a3b006a031e62 Mon Sep 17 00:00:00 2001 From: Muhtasham Nawr al-Mahmud <72372229+mnalmahmud@users.noreply.github.com> Date: Sun, 22 Nov 2026 14:17:41 +0600 Subject: [PATCH 077/129] test(p3): require field-get DEX PC identity for live invoke predecessor --- art-fieldwatch-phase1/ci/smoke_test.py | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/art-fieldwatch-phase1/ci/smoke_test.py b/art-fieldwatch-phase1/ci/smoke_test.py index 8066754..0de02b9 100644 --- a/art-fieldwatch-phase1/ci/smoke_test.py +++ b/art-fieldwatch-phase1/ci/smoke_test.py @@ -207,6 +207,22 @@ def main(): 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)} ' From ef25253c9c54737c08c9f69a4448ba4a40be110c Mon Sep 17 00:00:00 2001 From: Muhtasham Nawr al-Mahmud <72372229+mnalmahmud@users.noreply.github.com> Date: Sun, 22 Nov 2026 14:18:14 +0600 Subject: [PATCH 078/129] docs(p3): record baseline adjacency evidence and exact DEX-PC identity gate --- docs/art-fieldwatch/p3-injection-abi-gates.md | 52 +++++++++++++++++++ 1 file changed, 52 insertions(+) diff --git a/docs/art-fieldwatch/p3-injection-abi-gates.md b/docs/art-fieldwatch/p3-injection-abi-gates.md index dbae290..cc6100a 100644 --- a/docs/art-fieldwatch/p3-injection-abi-gates.md +++ b/docs/art-fieldwatch/p3-injection-abi-gates.md @@ -204,3 +204,55 @@ 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. From d949a61887d2e4e73e62874dfaa62a1e59a4acc9 Mon Sep 17 00:00:00 2001 From: Muhtasham Nawr al-Mahmud <72372229+mnalmahmud@users.noreply.github.com> Date: Sun, 22 Nov 2026 14:18:47 +0600 Subject: [PATCH 079/129] fix(ci): correct P3 DEX-PC counter assertion syntax --- art-fieldwatch-phase1/ci/smoke_test.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/art-fieldwatch-phase1/ci/smoke_test.py b/art-fieldwatch-phase1/ci/smoke_test.py index 0de02b9..3612f8b 100644 --- a/art-fieldwatch-phase1/ci/smoke_test.py +++ b/art-fieldwatch-phase1/ci/smoke_test.py @@ -219,7 +219,7 @@ def main(): 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: + 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') From f268c0c4300b922f283a44d74f115cac3c365708 Mon Sep 17 00:00:00 2001 From: Muhtasham Nawr al-Mahmud <72372229+mnalmahmud@users.noreply.github.com> Date: Sun, 22 Nov 2026 14:28:23 +0600 Subject: [PATCH 080/129] feat(p3): resolve fixture sink method index from packaged DEX --- art-fieldwatch-phase1/ci/dex_method_index.py | 170 +++++++++++++++++++ 1 file changed, 170 insertions(+) create mode 100644 art-fieldwatch-phase1/ci/dex_method_index.py 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..40f4ac3 --- /dev/null +++ b/art-fieldwatch-phase1/ci/dex_method_index.py @@ -0,0 +1,170 @@ +#!/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 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 name in 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 + matches.append({"dex": name, "methodIndex": idx, + "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") From 5135d02a090c8e5b3a0a8777cb5ea44f4a4c0d37 Mon Sep 17 00:00:00 2001 From: Muhtasham Nawr al-Mahmud <72372229+mnalmahmud@users.noreply.github.com> Date: Sun, 22 Nov 2026 14:28:40 +0600 Subject: [PATCH 081/129] fix(p3): correct DEX magic and string terminator byte literals --- art-fieldwatch-phase1/ci/dex_method_index.py | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/art-fieldwatch-phase1/ci/dex_method_index.py b/art-fieldwatch-phase1/ci/dex_method_index.py index 40f4ac3..107b364 100644 --- a/art-fieldwatch-phase1/ci/dex_method_index.py +++ b/art-fieldwatch-phase1/ci/dex_method_index.py @@ -42,7 +42,7 @@ def uleb128(data, pos): def sink_method_index(data): - if len(data) < 0x70 or data[:4] != b"dex\\n": + 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) @@ -62,7 +62,7 @@ def string(idx): if idx not in cache: off = u32(data, strings_off + 4 * idx) _, start = uleb128(data, off) - end = data.find(b"\\0", start) + end = data.find(b"\0", start) if end < 0: raise ValueError("unterminated DEX string") # Java descriptors and method names are ASCII even though @@ -130,7 +130,7 @@ def apk_sink_method(apk): def self_test(): strings = [SINK_CLASS, SINK_NAME, "I", "V"] data = bytearray(1024) - data[:8] = b"dex\\n035\\0" + 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)), @@ -141,7 +141,7 @@ def self_test(): cursor = 0x200 for i, value in enumerate(strings): struct.pack_into(" Date: Sun, 22 Nov 2026 14:28:54 +0600 Subject: [PATCH 082/129] ci(p3): compile and self-test packaged DEX sink resolver --- .github/workflows/art-fieldwatch-phase1.yml | 2 ++ 1 file changed, 2 insertions(+) diff --git a/.github/workflows/art-fieldwatch-phase1.yml b/.github/workflows/art-fieldwatch-phase1.yml index 8b0cafc..9d66d6f 100644 --- a/.github/workflows/art-fieldwatch-phase1.yml +++ b/.github/workflows/art-fieldwatch-phase1.yml @@ -22,6 +22,8 @@ jobs: - 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: 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 From 9172a86a9caff97f4eeb76b598eb561397658e18 Mon Sep 17 00:00:00 2001 From: Muhtasham Nawr al-Mahmud <72372229+mnalmahmud@users.noreply.github.com> Date: Sun, 22 Nov 2026 14:29:05 +0600 Subject: [PATCH 083/129] ci(p3): inventory exact native sink method ID from built APK --- art-fieldwatch-phase1/ci/dex-inventory.sh | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/art-fieldwatch-phase1/ci/dex-inventory.sh b/art-fieldwatch-phase1/ci/dex-inventory.sh index 2680112..09183c2 100644 --- a/art-fieldwatch-phase1/ci/dex-inventory.sh +++ b/art-fieldwatch-phase1/ci/dex-inventory.sh @@ -10,6 +10,10 @@ 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" analyzer="${ANDROID_HOME:-}/cmdline-tools/latest/bin/apkanalyzer" if [[ ! -x "$analyzer" ]]; then analyzer="$(command -v apkanalyzer || true)" From 5b65880f9dd0ea4d7ef9c577f46b99403bc18bb1 Mon Sep 17 00:00:00 2001 From: Muhtasham Nawr al-Mahmud <72372229+mnalmahmud@users.noreply.github.com> Date: Sun, 22 Nov 2026 14:29:45 +0600 Subject: [PATCH 084/129] test(p3): pass built APK sink method index to passive ART observer --- art-fieldwatch-phase1/ci/smoke_test.py | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/art-fieldwatch-phase1/ci/smoke_test.py b/art-fieldwatch-phase1/ci/smoke_test.py index 3612f8b..2624600 100644 --- a/art-fieldwatch-phase1/ci/smoke_test.py +++ b/art-fieldwatch-phase1/ci/smoke_test.py @@ -34,6 +34,15 @@ def main(): runtime_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 sink_info.get('dex') != 'classes.dex': + raise AssertionError('P3 probe currently supports the primary DEX only') + source = ('globalThis.__artwatchSinkMethodIndex = ' + + json.dumps(sink_info['methodIndex']) + ';\\n' + source) if os.environ.get('ARTWATCH_SHADOW_SHIM') == '1': source = ('globalThis.__artwatchShadowPath = ' + json.dumps('libartwatch_shadow.so') + From 98cdf11a44dc145e10fe2a037c63d171fe87d6d2 Mon Sep 17 00:00:00 2001 From: Muhtasham Nawr al-Mahmud <72372229+mnalmahmud@users.noreply.github.com> Date: Sun, 22 Nov 2026 14:30:00 +0600 Subject: [PATCH 085/129] fix(p3): emit actual newline in injected JS sink metadata --- art-fieldwatch-phase1/ci/smoke_test.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/art-fieldwatch-phase1/ci/smoke_test.py b/art-fieldwatch-phase1/ci/smoke_test.py index 2624600..383f4d3 100644 --- a/art-fieldwatch-phase1/ci/smoke_test.py +++ b/art-fieldwatch-phase1/ci/smoke_test.py @@ -42,7 +42,7 @@ def main(): if sink_info.get('dex') != 'classes.dex': raise AssertionError('P3 probe currently supports the primary DEX only') source = ('globalThis.__artwatchSinkMethodIndex = ' + - json.dumps(sink_info['methodIndex']) + ';\\n' + source) + json.dumps(sink_info['methodIndex']) + ';\n' + source) if os.environ.get('ARTWATCH_SHADOW_SHIM') == '1': source = ('globalThis.__artwatchShadowPath = ' + json.dumps('libartwatch_shadow.so') + From 57eea53683b16939270f5701909a695c22030241 Mon Sep 17 00:00:00 2001 From: Muhtasham Nawr al-Mahmud <72372229+mnalmahmud@users.noreply.github.com> Date: Sun, 22 Nov 2026 14:51:56 +0600 Subject: [PATCH 086/129] feat(p3): add exact-ART gated invoke-clone execution canary and native proof sink --- .../ci/build-passive-shim.sh | 4 +- art-fieldwatch-phase1/native/passive-shadow.c | 78 +++++++++++++++++++ art-fieldwatch-phase1/native/runtime-events.c | 36 ++++++++- .../example/artfieldwatch/FieldEventSink.java | 2 + .../example/artfieldwatch/FieldIRTarget.java | 6 +- .../example/artfieldwatch/MainActivity.java | 6 +- 6 files changed, 126 insertions(+), 6 deletions(-) diff --git a/art-fieldwatch-phase1/ci/build-passive-shim.sh b/art-fieldwatch-phase1/ci/build-passive-shim.sh index 31fbeed..ba67016 100644 --- a/art-fieldwatch-phase1/ci/build-passive-shim.sh +++ b/art-fieldwatch-phase1/ci/build-passive-shim.sh @@ -18,7 +18,7 @@ mkdir -p "$out" 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)' | tee "$out/exports.txt" +readelf -Ws "$out/libartwatch_shadow.so" | grep -E 'artwatch_shadow_(init|graph|node|report|scope_begin|scope_end|block|clone_template_invoke)' | 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. @@ -34,7 +34,7 @@ echo "Native shadow library staged for APK packaging: $jni_dir" art-fieldwatch-phase1/native/runtime-events.c \ -o "$out/libartwatch_events.so" readelf -Ws "$out/libartwatch_events.so" | - grep -E '(artwatch_events_snapshot|Java_com_example_artfieldwatch_FieldEventSink_(recordInt|reset|eventCount))' | + grep -E '(artwatch_events_snapshot|Java_com_example_artfieldwatch_FieldEventSink_(recordInt|reset|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" diff --git a/art-fieldwatch-phase1/native/passive-shadow.c b/art-fieldwatch-phase1/native/passive-shadow.c index 781fc55..f2bff28 100644 --- a/art-fieldwatch-phase1/native/passive-shadow.c +++ b/art-fieldwatch-phase1/native/passive-shadow.c @@ -256,6 +256,84 @@ EXPORT int artwatch_shadow_instruction_dex_pc( *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) { + 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; + void *h=dlopen("libart-compiler.so",RTLD_NOW|RTLD_NOLOAD); + if (h==NULL) return -8; + void (*append)(void*,void*)=(void(*)(void*,void*))dlsym( + h,"_ZN3art19HInstructionBuilder17AppendInstructionEPNS_12HInstructionE"); + if (append==NULL) { dlclose(h); return -8; } + typedef void *(*CloneFn)(const void*,void*); + void *copy=((CloneFn)clone_entry)(source,(void*)arena); + if (!aligned(copy)) {dlclose(h); return -9;} + // AppendInstruction both inserts through HBasicBlock::AddInstruction + // and calls HInstructionBuilder::InitializeInstruction() so an invoke + // gets a compiler-built environment, rather than a copied/stale one. + append(builder,copy); + dlclose(h); + 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; +} // 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; diff --git a/art-fieldwatch-phase1/native/runtime-events.c b/art-fieldwatch-phase1/native/runtime-events.c index 056311f..3ea3ae0 100644 --- a/art-fieldwatch-phase1/native/runtime-events.c +++ b/art-fieldwatch-phase1/native/runtime-events.c @@ -19,6 +19,31 @@ 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; +// 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)!=128u || + atomic_load_explicit(&dropped,memory_order_acquire)!=0u) + return JNI_FALSE; + for (uint32_t i=0;i<128u;++i) { + if (atomic_load_explicit(&ready[i],memory_order_acquire)!=1u || + events[i].site!=9002u || events[i].kind!=1u || + events[i].value!=(int32_t)(7u+3u*i)) + return JNI_FALSE; + } + 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 @@ -26,6 +51,7 @@ static atomic_uint dropped = 0; 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); for (uint32_t i = 0; i < EVENT_CAPACITY; ++i) atomic_store_explicit(&ready[i], 0, memory_order_relaxed); } @@ -42,7 +68,15 @@ Java_com_example_artfieldwatch_FieldEventSink_recordInt( (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) return; + if (site == 0 && kind == 0) { + if (!atomic_load_explicit(&p3_enabled,memory_order_acquire)) return; + // One original Java call and one compiler-cloned call per invocation. + // Counting every second sentinel deliberately fails when no clone ran. + uint32_t n=atomic_fetch_add_explicit(&p3_sentinel_sequence,1u, + memory_order_relaxed); + if ((n & 1u)==0u) return; + site=9002; kind=1; + } uint32_t index = atomic_fetch_add_explicit(&next_index, 1u, memory_order_relaxed); if (index >= EVENT_CAPACITY) { 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 index 3c8031c..850e5d1 100644 --- 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 @@ -16,4 +16,6 @@ private FieldEventSink() {} public static native void recordInt(int site, int kind, int value); 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 index a027f2e..f7589f6 100644 --- 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 @@ -101,8 +101,12 @@ public static int exerciseP3TemplateCarrier() { try { p3TemplateCarrierOn(null, 777); } catch (NullPointerException expected) { threw = true; } if (!threw) throw new AssertionError("P3 template null write did not throw"); - if (FieldEventSink.eventCount() != 0) + if (FieldEventSink.p3Enabled()) { + if (!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; } diff --git a/art-fieldwatch-phase1/test/app/src/main/java/com/example/artfieldwatch/MainActivity.java b/art-fieldwatch-phase1/test/app/src/main/java/com/example/artfieldwatch/MainActivity.java index ec21f02..4e13b9f 100644 --- a/art-fieldwatch-phase1/test/app/src/main/java/com/example/artfieldwatch/MainActivity.java +++ b/art-fieldwatch-phase1/test/app/src/main/java/com/example/artfieldwatch/MainActivity.java @@ -51,8 +51,10 @@ protected void onCreate(Bundle state) { // the native records after this completion marker. if (android.os.Build.VERSION.SDK_INT == 33) { int carrierChecksum = FieldIRTarget.exerciseP3TemplateCarrier(); - Log.i("ARTWATCH_CI","P3_TEMPLATE_DONE count=0 checksum=" + - carrierChecksum + " nullCheck=true"); + 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=" + From fd4ce6e271c4b0c5d3417003877a0cd11a88be92 Mon Sep 17 00:00:00 2001 From: Muhtasham Nawr al-Mahmud <72372229+mnalmahmud@users.noreply.github.com> Date: Sun, 22 Nov 2026 14:53:08 +0600 Subject: [PATCH 087/129] feat(p3): resolve exact carrier DEX get/invoke PCs and method ID --- art-fieldwatch-phase1/ci/dex_method_index.py | 78 ++++++++++++++++++++ 1 file changed, 78 insertions(+) diff --git a/art-fieldwatch-phase1/ci/dex_method_index.py b/art-fieldwatch-phase1/ci/dex_method_index.py index 107b364..0ddaa52 100644 --- a/art-fieldwatch-phase1/ci/dex_method_index.py +++ b/art-fieldwatch-phase1/ci/dex_method_index.py @@ -105,6 +105,82 @@ def signature(idx): 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_get = [] + candidates_invoke = [] + for pc in range(insn_count): + op = u16(data, insns_start + pc*2) & 0xff + 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_get) != 1 or len(candidates_invoke) != 1: + raise ValueError(f"ambiguous P3 opcodes: gets={candidates_get} invokes={candidates_invoke}") + found.append({"carrierMethodIndex":method_index, + "getDexPc":candidates_get[0], + "invokeDexPc":candidates_invoke[0]}) + 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() @@ -120,7 +196,9 @@ def apk_sink_method(apk): if "expected one sink DEX method ID, found 0" in str(e): continue raise + pcs = canary_pcs(data, idx) matches.append({"dex": name, "methodIndex": idx, + **pcs, "sha256": hashlib.sha256(data).hexdigest()}) if len(matches) != 1: raise ValueError(f"expected one fixture sink in APK, found {len(matches)}") From 2f38e7f9433d60aad8fc33b780b996b71e8f3cd2 Mon Sep 17 00:00:00 2001 From: Muhtasham Nawr al-Mahmud <72372229+mnalmahmud@users.noreply.github.com> Date: Sun, 22 Nov 2026 14:53:35 +0600 Subject: [PATCH 088/129] test(p3): explicitly enable and verify compiler-cloned runtime read events --- art-fieldwatch-phase1/ci/smoke_test.py | 15 +++++++++++---- 1 file changed, 11 insertions(+), 4 deletions(-) diff --git a/art-fieldwatch-phase1/ci/smoke_test.py b/art-fieldwatch-phase1/ci/smoke_test.py index 383f4d3..9896d1f 100644 --- a/art-fieldwatch-phase1/ci/smoke_test.py +++ b/art-fieldwatch-phase1/ci/smoke_test.py @@ -41,8 +41,11 @@ def main(): sink_info = json.loads(sink_inventory.read_text()) if sink_info.get('dex') != 'classes.dex': raise AssertionError('P3 probe currently supports the primary DEX only') - source = ('globalThis.__artwatchSinkMethodIndex = ' + - json.dumps(sink_info['methodIndex']) + ';\n' + source) + 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') + @@ -81,9 +84,13 @@ def main(): 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') - template_marker = 'P3_TEMPLATE_DONE count=0 checksum=25280 nullCheck=true' + p3_inject = os.environ.get('ARTWATCH_P3_INJECT') == '1' + if p3_inject: + template_marker = 'P3_TEMPLATE_DONE count=128 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('Resolved P3 invoke template did not run with zero events') + raise AssertionError('P3 compiler-insertion result mismatch: ' + template_marker) 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' From 0c21bef9335a1c9816286a4ce87c0d7cc80ab04b Mon Sep 17 00:00:00 2001 From: Muhtasham Nawr al-Mahmud <72372229+mnalmahmud@users.noreply.github.com> Date: Sun, 22 Nov 2026 14:53:53 +0600 Subject: [PATCH 089/129] feat(p3): execute guarded native invoke-clone at real ART builder boundary --- art-fieldwatch-phase1/jit-boundary-probe.js | 83 ++++++++++++++++++++- 1 file changed, 82 insertions(+), 1 deletion(-) diff --git a/art-fieldwatch-phase1/jit-boundary-probe.js b/art-fieldwatch-phase1/jit-boundary-probe.js index 4d32d66..1fea54e 100644 --- a/art-fieldwatch-phase1/jit-boundary-probe.js +++ b/art-fieldwatch-phase1/jit-boundary-probe.js @@ -177,7 +177,9 @@ function loadPassiveShadow() { linkedGetInvoke: exported('artwatch_shadow_linked_get_invoke','int', ['pointer','pointer','pointer','pointer']), instructionDexPc: exported('artwatch_shadow_instruction_dex_pc','int', - ['pointer','pointer','pointer']) + ['pointer','pointer','pointer']), + cloneTemplate: exported('artwatch_shadow_clone_template_invoke','int', + ['pointer','pointer','pointer','pointer','uint','uint']) }; send({type:'artwatch-shadow-init',ready:true,source:'native', buildIdVerified:true,mutable:false}); @@ -1266,6 +1268,84 @@ function attachExistingInvokeBackend(compiler, symbol, stage) { 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 || !Number.isInteger(fixture.getDexPc) || + !Number.isInteger(fixture.invokeDexPc)) return false; + const append=getExport(compiler,NAMES.appendInstruction); + const vt=getExport(compiler,INVOKE_VTABLE); + const get=getExport(compiler,'_ZTVN3art17HInstanceFieldGetE'); + if (!append || !vt || !get) return false; + const seen=new Set(); + let inClone=false; + let eventEnable=null; + let complete=0; + try { + Interceptor.attach(append.address,{ + onEnter(args) { + this.candidate=null; + if (inClone || complete > 0) return; + const active=compiling.get(this.threadId); + if (!active || !targetMethodPointers.has(active.method)) return; + if (!shadowShim) loadPassiveShadow(); + if (!shadowShim || !shadowShim.cloneTemplate || + !shadowShim.instructionDexPc) return; + const node=args[1]; + try { + if (!node.readPointer().equals(vt.address.add(2*Process.pointerSize))) + return; + const p=Memory.alloc(4); + if (shadowShim.instructionDexPc(node,vt.address,p)!==1 || + p.readU32()!==fixture.invokeDexPc) return; + const previous=node.add(Process.pointerSize).readPointer(); + if (previous.isNull() || + !previous.readPointer().equals(get.address.add(2*Process.pointerSize))) + return; + if (shadowShim.instructionDexPc(previous,get.address,p)!==1 || + p.readU32()!==fixture.getDexPc) return; + if (seen.has(active.method)) return; + this.candidate={builder:args[0],node,method:active.method}; + } catch (_) {} + }, + onLeave() { + if (!this.candidate || inClone) return; + const {builder,node,method}=this.candidate; + inClone=true; + try { + const rc=shadowShim.cloneTemplate(builder,node,get.address, + vt.address,fixture.getDexPc,fixture.invokeDexPc); + send({type:'artwatch-p3-clone',rc,method, + getDexPc:fixture.getDexPc,invokeDexPc:fixture.invokeDexPc}); + if (rc===1) { + complete++; + seen.add(method); + if (eventEnable===null) { + const library=Process.findModuleByName('libartwatch_events.so'); + if (library) { + const p=library.findExportByName('artwatch_events_set_p3'); + if (p) eventEnable=new NativeFunction(p,'void',['int']); + } + } + if (eventEnable) eventEnable(1); + } + } catch(e) { + send({type:'artwatch-p3-clone-error',error:String(e)}); + } finally {inClone=false;} + } + }); + send({type:'artwatch-hook-attached',layer:'p3_clone_canary', + address:append.address.toString(),source:'export'}); + 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 + @@ -1365,6 +1445,7 @@ function main() { 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 From f22aa648279958494d51e2f1b9b45d2730eff3fc Mon Sep 17 00:00:00 2001 From: Muhtasham Nawr al-Mahmud <72372229+mnalmahmud@users.noreply.github.com> Date: Sun, 22 Nov 2026 14:54:22 +0600 Subject: [PATCH 090/129] fix(p3): permit secondary classesN.dex for sink and carrier fixture --- art-fieldwatch-phase1/ci/smoke_test.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/art-fieldwatch-phase1/ci/smoke_test.py b/art-fieldwatch-phase1/ci/smoke_test.py index 9896d1f..5de09ab 100644 --- a/art-fieldwatch-phase1/ci/smoke_test.py +++ b/art-fieldwatch-phase1/ci/smoke_test.py @@ -39,8 +39,8 @@ def main(): '.json') if sink_inventory.is_file() and os.environ.get('ARTWATCH_SHADOW_SHIM') == '1': sink_info = json.loads(sink_inventory.read_text()) - if sink_info.get('dex') != 'classes.dex': - raise AssertionError('P3 probe currently supports the primary DEX only') + 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 = ' + From 40c4531911b25cd296599b217c7144d1dbd0b99b Mon Sep 17 00:00:00 2001 From: Muhtasham Nawr al-Mahmud <72372229+mnalmahmud@users.noreply.github.com> Date: Sun, 22 Nov 2026 14:54:33 +0600 Subject: [PATCH 091/129] ci(p3): enable actual guarded clone injection on API33 debug fixture --- .github/workflows/art-fieldwatch-phase1.yml | 1 + 1 file changed, 1 insertion(+) diff --git a/.github/workflows/art-fieldwatch-phase1.yml b/.github/workflows/art-fieldwatch-phase1.yml index 9d66d6f..7e9b637 100644 --- a/.github/workflows/art-fieldwatch-phase1.yml +++ b/.github/workflows/art-fieldwatch-phase1.yml @@ -49,6 +49,7 @@ jobs: 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. From a375ff383fc26231d4d513d11b1f851880924d24 Mon Sep 17 00:00:00 2001 From: Muhtasham Nawr al-Mahmud <72372229+mnalmahmud@users.noreply.github.com> Date: Sun, 22 Nov 2026 14:54:49 +0600 Subject: [PATCH 092/129] fix(p3): call verified ART append pointer without Android linker-namespace dlopen --- art-fieldwatch-phase1/native/passive-shadow.c | 27 ++++++++++--------- 1 file changed, 15 insertions(+), 12 deletions(-) diff --git a/art-fieldwatch-phase1/native/passive-shadow.c b/art-fieldwatch-phase1/native/passive-shadow.c index f2bff28..3f455fb 100644 --- a/art-fieldwatch-phase1/native/passive-shadow.c +++ b/art-fieldwatch-phase1/native/passive-shadow.c @@ -274,7 +274,8 @@ EXPORT int artwatch_shadow_instruction_dex_pc( 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) { + 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}; @@ -316,19 +317,21 @@ EXPORT int artwatch_shadow_clone_template_invoke( Dl_info ci={0}; if (!aligned(clone_entry) || !dladdr(clone_entry,&ci) || !named(ci.dli_fname,"libart-compiler.so")) return -7; - void *h=dlopen("libart-compiler.so",RTLD_NOW|RTLD_NOLOAD); - if (h==NULL) return -8; - void (*append)(void*,void*)=(void(*)(void*,void*))dlsym( - h,"_ZN3art19HInstructionBuilder17AppendInstructionEPNS_12HInstructionE"); - if (append==NULL) { dlclose(h); return -8; } + // 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)) {dlclose(h); return -9;} - // AppendInstruction both inserts through HBasicBlock::AddInstruction - // and calls HInstructionBuilder::InitializeInstruction() so an invoke - // gets a compiler-built environment, rather than a copied/stale one. - append(builder,copy); - dlclose(h); + 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)); From d370b34ef9d218c42a4f88afc627462d7a5e6e1e Mon Sep 17 00:00:00 2001 From: Muhtasham Nawr al-Mahmud <72372229+mnalmahmud@users.noreply.github.com> Date: Sun, 22 Nov 2026 14:55:01 +0600 Subject: [PATCH 093/129] fix(p3): supply exact native ART append target to clone injector --- art-fieldwatch-phase1/jit-boundary-probe.js | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/art-fieldwatch-phase1/jit-boundary-probe.js b/art-fieldwatch-phase1/jit-boundary-probe.js index 1fea54e..600311a 100644 --- a/art-fieldwatch-phase1/jit-boundary-probe.js +++ b/art-fieldwatch-phase1/jit-boundary-probe.js @@ -179,7 +179,7 @@ function loadPassiveShadow() { 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','pointer','pointer','pointer','uint','uint','pointer']) }; send({type:'artwatch-shadow-init',ready:true,source:'native', buildIdVerified:true,mutable:false}); @@ -1318,7 +1318,7 @@ function attachP3CloneCanary(compiler) { inClone=true; try { const rc=shadowShim.cloneTemplate(builder,node,get.address, - vt.address,fixture.getDexPc,fixture.invokeDexPc); + vt.address,fixture.getDexPc,fixture.invokeDexPc,append.address); send({type:'artwatch-p3-clone',rc,method, getDexPc:fixture.getDexPc,invokeDexPc:fixture.invokeDexPc}); if (rc===1) { From a557de086f060729830ea595f3d1913b9c71f3ad Mon Sep 17 00:00:00 2001 From: Muhtasham Nawr al-Mahmud <72372229+mnalmahmud@users.noreply.github.com> Date: Sun, 22 Nov 2026 14:55:23 +0600 Subject: [PATCH 094/129] fix(p3): pick packaged DEX containing both sink reference and carrier --- art-fieldwatch-phase1/ci/dex_method_index.py | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/art-fieldwatch-phase1/ci/dex_method_index.py b/art-fieldwatch-phase1/ci/dex_method_index.py index 0ddaa52..2dd3a26 100644 --- a/art-fieldwatch-phase1/ci/dex_method_index.py +++ b/art-fieldwatch-phase1/ci/dex_method_index.py @@ -196,7 +196,12 @@ def apk_sink_method(apk): if "expected one sink DEX method ID, found 0" in str(e): continue raise - pcs = canary_pcs(data, idx) + 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, "methodIndex": idx, **pcs, "sha256": hashlib.sha256(data).hexdigest()}) From bd142de35c94183935d8415f0c626b13e8872927 Mon Sep 17 00:00:00 2001 From: Muhtasham Nawr al-Mahmud <72372229+mnalmahmud@users.noreply.github.com> Date: Sun, 22 Nov 2026 14:56:13 +0600 Subject: [PATCH 095/129] fix(p3): clone after original ART append initializes live instruction links --- art-fieldwatch-phase1/jit-boundary-probe.js | 43 +++++++++------------ 1 file changed, 18 insertions(+), 25 deletions(-) diff --git a/art-fieldwatch-phase1/jit-boundary-probe.js b/art-fieldwatch-phase1/jit-boundary-probe.js index 600311a..edc736a 100644 --- a/art-fieldwatch-phase1/jit-boundary-probe.js +++ b/art-fieldwatch-phase1/jit-boundary-probe.js @@ -1281,40 +1281,39 @@ function attachP3CloneCanary(compiler) { const vt=getExport(compiler,INVOKE_VTABLE); const get=getExport(compiler,'_ZTVN3art17HInstanceFieldGetE'); if (!append || !vt || !get) return false; - const seen=new Set(); let inClone=false; - let eventEnable=null; let complete=0; try { Interceptor.attach(append.address,{ onEnter(args) { this.candidate=null; - if (inClone || complete > 0) return; + if (inClone || complete>0) return; const active=compiling.get(this.threadId); if (!active || !targetMethodPointers.has(active.method)) return; if (!shadowShim) loadPassiveShadow(); if (!shadowShim || !shadowShim.cloneTemplate || !shadowShim.instructionDexPc) return; - const node=args[1]; + this.candidate={builder:args[0],node:args[1],method:active.method}; + }, + onLeave() { + if (!this.candidate || inClone || complete>0) return; + const {builder,node,method}=this.candidate; + // At AppendInstruction *entry*, the node is unlinked and has no + // previous_ or block_. Only inspect its ownership AFTER ART's + // original append + InitializeInstruction completed. try { if (!node.readPointer().equals(vt.address.add(2*Process.pointerSize))) return; - const p=Memory.alloc(4); - if (shadowShim.instructionDexPc(node,vt.address,p)!==1 || - p.readU32()!==fixture.invokeDexPc) return; + const pc=Memory.alloc(4); + if (shadowShim.instructionDexPc(node,vt.address,pc)!==1 || + pc.readU32()!==fixture.invokeDexPc) return; const previous=node.add(Process.pointerSize).readPointer(); if (previous.isNull() || !previous.readPointer().equals(get.address.add(2*Process.pointerSize))) return; - if (shadowShim.instructionDexPc(previous,get.address,p)!==1 || - p.readU32()!==fixture.getDexPc) return; - if (seen.has(active.method)) return; - this.candidate={builder:args[0],node,method:active.method}; - } catch (_) {} - }, - onLeave() { - if (!this.candidate || inClone) return; - const {builder,node,method}=this.candidate; + if (shadowShim.instructionDexPc(previous,get.address,pc)!==1 || + pc.readU32()!==fixture.getDexPc) return; + } catch (_) {return;} inClone=true; try { const rc=shadowShim.cloneTemplate(builder,node,get.address, @@ -1323,15 +1322,9 @@ function attachP3CloneCanary(compiler) { getDexPc:fixture.getDexPc,invokeDexPc:fixture.invokeDexPc}); if (rc===1) { complete++; - seen.add(method); - if (eventEnable===null) { - const library=Process.findModuleByName('libartwatch_events.so'); - if (library) { - const p=library.findExportByName('artwatch_events_set_p3'); - if (p) eventEnable=new NativeFunction(p,'void',['int']); - } - } - if (eventEnable) eventEnable(1); + const library=Process.findModuleByName('libartwatch_events.so'); + const address=library && library.findExportByName('artwatch_events_set_p3'); + if (address) new NativeFunction(address,'void',['int'])(1); } } catch(e) { send({type:'artwatch-p3-clone-error',error:String(e)}); From 39b7b36441f3da9be4f286d8f884295f57f49ade Mon Sep 17 00:00:00 2001 From: Muhtasham Nawr al-Mahmud <72372229+mnalmahmud@users.noreply.github.com> Date: Sun, 22 Nov 2026 14:58:10 +0600 Subject: [PATCH 096/129] fix(p3): use actual NUL byte for secondary DEX string parsing --- art-fieldwatch-phase1/ci/dex_method_index.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/art-fieldwatch-phase1/ci/dex_method_index.py b/art-fieldwatch-phase1/ci/dex_method_index.py index 2dd3a26..6099b10 100644 --- a/art-fieldwatch-phase1/ci/dex_method_index.py +++ b/art-fieldwatch-phase1/ci/dex_method_index.py @@ -117,7 +117,7 @@ def string(idx): raise ValueError("bad string ID") off = u32(data, strings_off + 4 * idx) _, pos = uleb128(data, off) - end = data.find(b"\\0", pos) + end = data.find(b"\0", pos) if end < 0: raise ValueError("bad string terminator") return data[pos:end].decode("ascii") From 22f08f58980d591977af7f8ac860037d2e8296d9 Mon Sep 17 00:00:00 2001 From: Muhtasham Nawr al-Mahmud <72372229+mnalmahmud@users.noreply.github.com> Date: Sun, 22 Nov 2026 15:08:46 +0600 Subject: [PATCH 097/129] feat(p3): trigger live gated invoke clone at ART Accept instead of inlined append --- art-fieldwatch-phase1/jit-boundary-probe.js | 98 +++++++++++++-------- 1 file changed, 60 insertions(+), 38 deletions(-) diff --git a/art-fieldwatch-phase1/jit-boundary-probe.js b/art-fieldwatch-phase1/jit-boundary-probe.js index edc736a..82ca69c 100644 --- a/art-fieldwatch-phase1/jit-boundary-probe.js +++ b/art-fieldwatch-phase1/jit-boundary-probe.js @@ -243,6 +243,7 @@ function attach(layer, site) { method: this.method, kind: this.compilationKind, existingInvokeVisits: 0, existingInvokeNodes: new Set(), existingInvokeBlockVisits: 0, + p3Builder: null, existingInvokeLocations: new Set(), existingInvokeEmitted: new Set(), adjacencyProbes: 0, adjacencyMatches: 0, @@ -702,6 +703,12 @@ function attachFieldBuilder(access, site) { 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. @@ -1277,62 +1284,77 @@ function attachP3CloneCanary(compiler) { const fixture=globalThis.__artwatchP3Fixture; if (!fixture || !Number.isInteger(fixture.getDexPc) || !Number.isInteger(fixture.invokeDexPc)) return false; + const site=getExport(compiler,INVOKE_ACCEPT); const append=getExport(compiler,NAMES.appendInstruction); - const vt=getExport(compiler,INVOKE_VTABLE); - const get=getExport(compiler,'_ZTVN3art17HInstanceFieldGetE'); - if (!append || !vt || !get) return false; - let inClone=false; - let complete=0; + const invokeVt=getExport(compiler,INVOKE_VTABLE); + const getVt=getExport(compiler,'_ZTVN3art17HInstanceFieldGetE'); + if (!site || !append || !invokeVt || !getVt) return false; + let cloning=false; + let successes=0; + let attempts=0; + let missedBuilder=0; try { - Interceptor.attach(append.address,{ + Interceptor.attach(site.address,{ onEnter(args) { - this.candidate=null; - if (inClone || complete>0) return; - const active=compiling.get(this.threadId); - if (!active || !targetMethodPointers.has(active.method)) return; + if (cloning || successes!==0) return; + const thread=this.threadId; + const active=compiling.get(thread); + const state=targetStates.get(thread); + if (!active || !state || !targetMethodPointers.has(active.method)) + return; if (!shadowShim) loadPassiveShadow(); if (!shadowShim || !shadowShim.cloneTemplate || !shadowShim.instructionDexPc) return; - this.candidate={builder:args[0],node:args[1],method:active.method}; - }, - onLeave() { - if (!this.candidate || inClone || complete>0) return; - const {builder,node,method}=this.candidate; - // At AppendInstruction *entry*, the node is unlinked and has no - // previous_ or block_. Only inspect its ownership AFTER ART's - // original append + InitializeInstruction completed. + const node=args[0]; + const size=Process.pointerSize; try { - if (!node.readPointer().equals(vt.address.add(2*Process.pointerSize))) + if (!node.readPointer().equals(invokeVt.address.add(2*size))) return; const pc=Memory.alloc(4); - if (shadowShim.instructionDexPc(node,vt.address,pc)!==1 || + if (shadowShim.instructionDexPc(node,invokeVt.address,pc)!==1 || pc.readU32()!==fixture.invokeDexPc) return; - const previous=node.add(Process.pointerSize).readPointer(); + const previous=node.add(size).readPointer(); if (previous.isNull() || - !previous.readPointer().equals(get.address.add(2*Process.pointerSize))) + !previous.readPointer().equals(getVt.address.add(2*size))) return; - if (shadowShim.instructionDexPc(previous,get.address,pc)!==1 || + if (shadowShim.instructionDexPc(previous,getVt.address,pc)!==1 || pc.readU32()!==fixture.getDexPc) return; - } catch (_) {return;} - inClone=true; - try { - const rc=shadowShim.cloneTemplate(builder,node,get.address, - vt.address,fixture.getDexPc,fixture.invokeDexPc,append.address); - send({type:'artwatch-p3-clone',rc,method, - getDexPc:fixture.getDexPc,invokeDexPc:fixture.invokeDexPc}); - if (rc===1) { - complete++; - const library=Process.findModuleByName('libartwatch_events.so'); - const address=library && library.findExportByName('artwatch_events_set_p3'); - if (address) new NativeFunction(address,'void',['int'])(1); + // BuildInstanceFieldAccess records its real HInstructionBuilder* + // for this compilation. Its current block and locals must still + // exist, otherwise AppendInstruction cannot make a valid invoke. + if (!activeGraphBuild.has(thread) || !state.p3Builder) { + if (missedBuilder++<2) + send({type:'artwatch-p3-clone-skipped',reason:'builder-not-live', + method:active.method,getDexPc:fixture.getDexPc, + invokeDexPc:fixture.invokeDexPc}); + return; } + attempts++; + cloning=true; + try { + const rc=shadowShim.cloneTemplate(state.p3Builder,node, + getVt.address,invokeVt.address, + fixture.getDexPc,fixture.invokeDexPc,append.address); + send({type:'artwatch-p3-clone',rc,method:active.method, + attempt:attempts,trigger:'invoke_accept', + getDexPc:fixture.getDexPc,invokeDexPc:fixture.invokeDexPc}); + if (rc===1) { + successes++; + const module=Process.findModuleByName('libartwatch_events.so'); + const address=module && module.findExportByName('artwatch_events_set_p3'); + if (address) + new NativeFunction(address,'void',['int'])(1); + } + } finally {cloning=false;} } catch(e) { - send({type:'artwatch-p3-clone-error',error:String(e)}); - } finally {inClone=false;} + cloning=false; + send({type:'artwatch-p3-clone-error',error:String(e), + method:active.method}); + } } }); send({type:'artwatch-hook-attached',layer:'p3_clone_canary', - address:append.address.toString(),source:'export'}); + address:site.address.toString(),source:'invoke-accept'}); return true; } catch(e) { send({type:'artwatch-p3-clone-error',error:String(e)}); From 2144859be41020de84ece56a8cffc213c8245ef2 Mon Sep 17 00:00:00 2001 From: Muhtasham Nawr al-Mahmud <72372229+mnalmahmud@users.noreply.github.com> Date: Sun, 22 Nov 2026 15:15:26 +0600 Subject: [PATCH 098/129] feat(p3): insert cloned invoke in actual ART block and reconstruct environment --- .../ci/build-passive-shim.sh | 2 +- art-fieldwatch-phase1/jit-boundary-probe.js | 30 +++-- art-fieldwatch-phase1/native/passive-shadow.c | 115 ++++++++++++++++++ 3 files changed, 130 insertions(+), 17 deletions(-) diff --git a/art-fieldwatch-phase1/ci/build-passive-shim.sh b/art-fieldwatch-phase1/ci/build-passive-shim.sh index ba67016..b9c16f9 100644 --- a/art-fieldwatch-phase1/ci/build-passive-shim.sh +++ b/art-fieldwatch-phase1/ci/build-passive-shim.sh @@ -18,7 +18,7 @@ mkdir -p "$out" 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)' | tee "$out/exports.txt" +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. diff --git a/art-fieldwatch-phase1/jit-boundary-probe.js b/art-fieldwatch-phase1/jit-boundary-probe.js index 82ca69c..f709987 100644 --- a/art-fieldwatch-phase1/jit-boundary-probe.js +++ b/art-fieldwatch-phase1/jit-boundary-probe.js @@ -179,7 +179,9 @@ function loadPassiveShadow() { 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']) + ['pointer','pointer','pointer','pointer','uint','uint','pointer']), + cloneBefore: exported('artwatch_shadow_clone_invoke_before','int', + ['pointer','pointer','pointer','uint','uint','pointer','pointer']) }; send({type:'artwatch-shadow-init',ready:true,source:'native', buildIdVerified:true,mutable:false}); @@ -1285,10 +1287,12 @@ function attachP3CloneCanary(compiler) { if (!fixture || !Number.isInteger(fixture.getDexPc) || !Number.isInteger(fixture.invokeDexPc)) return false; const site=getExport(compiler,INVOKE_ACCEPT); - const append=getExport(compiler,NAMES.appendInstruction); + const insert=getExport(compiler, + '_ZN3art11HBasicBlock23InsertInstructionBeforeEPNS_12HInstructionES2_'); + const copyEnv=getExport(compiler,'_ZN3art12HEnvironment8CopyFromEPS0_'); const invokeVt=getExport(compiler,INVOKE_VTABLE); const getVt=getExport(compiler,'_ZTVN3art17HInstanceFieldGetE'); - if (!site || !append || !invokeVt || !getVt) return false; + if (!site || !insert || !copyEnv || !invokeVt || !getVt) return false; let cloning=false; let successes=0; let attempts=0; @@ -1303,7 +1307,7 @@ function attachP3CloneCanary(compiler) { if (!active || !state || !targetMethodPointers.has(active.method)) return; if (!shadowShim) loadPassiveShadow(); - if (!shadowShim || !shadowShim.cloneTemplate || + if (!shadowShim || !shadowShim.cloneBefore || !shadowShim.instructionDexPc) return; const node=args[0]; const size=Process.pointerSize; @@ -1319,22 +1323,16 @@ function attachP3CloneCanary(compiler) { return; if (shadowShim.instructionDexPc(previous,getVt.address,pc)!==1 || pc.readU32()!==fixture.getDexPc) return; - // BuildInstanceFieldAccess records its real HInstructionBuilder* - // for this compilation. Its current block and locals must still - // exist, otherwise AppendInstruction cannot make a valid invoke. - if (!activeGraphBuild.has(thread) || !state.p3Builder) { - if (missedBuilder++<2) - send({type:'artwatch-p3-clone-skipped',reason:'builder-not-live', - method:active.method,getDexPc:fixture.getDexPc, - invokeDexPc:fixture.invokeDexPc}); - return; - } + // 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 rc=shadowShim.cloneTemplate(state.p3Builder,node, + const rc=shadowShim.cloneBefore(node, getVt.address,invokeVt.address, - fixture.getDexPc,fixture.invokeDexPc,append.address); + fixture.getDexPc,fixture.invokeDexPc, + insert.address,copyEnv.address); send({type:'artwatch-p3-clone',rc,method:active.method, attempt:attempts,trigger:'invoke_accept', getDexPc:fixture.getDexPc,invokeDexPc:fixture.invokeDexPc}); diff --git a/art-fieldwatch-phase1/native/passive-shadow.c b/art-fieldwatch-phase1/native/passive-shadow.c index 3f455fb..d17d82c 100644 --- a/art-fieldwatch-phase1/native/passive-shadow.c +++ b/art-fieldwatch-phase1/native/passive-shadow.c @@ -7,6 +7,7 @@ #include #include #include +#include #include #include #define EXPORT __attribute__((visibility("default"))) @@ -337,6 +338,120 @@ EXPORT int artwatch_shadow_clone_template_invoke( 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) { + if (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,"_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,*get_vptr=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; + memcpy(&get_vptr,get,sizeof(get_vptr)); + memcpy(&get_pc,(const uint8_t*)get+32,sizeof(get_pc)); + if (get_vptr!=(const uint8_t*)get_vtable+16 || + get_pc!=expected_get_pc) return -4; + const void *get_next=NULL,*get_block=NULL; + memcpy(&get_next,(const uint8_t*)get+16,sizeof(get_next)); + memcpy(&get_block,(const uint8_t*)get+24,sizeof(get_block)); + if (get_next!=source || get_block!=block) return -5; + + // Verify source environment is uninlined, has a populated vector of + // (instruction, before-use-node) records, and no allocated locations yet. + const void *old_env=NULL; + memcpy(&old_env,src+64,sizeof(old_env)); + if (!aligned(old_env)) return -6; + const uint8_t *oe=(const uint8_t*)old_env; + const void *v_begin=NULL,*v_end=NULL,*v_cap=NULL; + const void *loc_begin=NULL,*loc_end=NULL,*parent=NULL,*holder=NULL; + memcpy(&v_begin,oe+0,8); memcpy(&v_end,oe+8,8); + memcpy(&v_cap,oe+16,8); + memcpy(&loc_begin,oe+32,8); memcpy(&loc_end,oe+40,8); + memcpy(&parent,oe+64,8); memcpy(&holder,oe+88,8); + if (parent!=NULL || holder!=source || loc_begin!=loc_end || + !aligned(v_begin) || !aligned(v_end) || !aligned(v_cap) || + (uintptr_t)v_begin>(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); + return copy_block==block && copy_next==source && copy_env==environment ? + 1 : -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; From 2e1ff7b7c9f3d353a9ec1496e431c5afab77b952 Mon Sep 17 00:00:00 2001 From: Muhtasham Nawr al-Mahmud <72372229+mnalmahmud@users.noreply.github.com> Date: Sun, 22 Nov 2026 15:20:44 +0600 Subject: [PATCH 099/129] fix(p3): wait for completed ART JIT injection before measuring field reads --- art-fieldwatch-phase1/jit-boundary-probe.js | 20 ++++++++++--- .../example/artfieldwatch/FieldIRTarget.java | 28 +++++++++++++++++-- .../example/artfieldwatch/MainActivity.java | 2 +- 3 files changed, 42 insertions(+), 8 deletions(-) diff --git a/art-fieldwatch-phase1/jit-boundary-probe.js b/art-fieldwatch-phase1/jit-boundary-probe.js index f709987..72424a8 100644 --- a/art-fieldwatch-phase1/jit-boundary-probe.js +++ b/art-fieldwatch-phase1/jit-boundary-probe.js @@ -66,6 +66,7 @@ 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; @@ -281,6 +282,20 @@ function attach(layer, site) { 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'); + if (succeeded && fn !== null) { + new NativeFunction(fn,'void',['int'])(1); + send({type:'artwatch-p3-compiled',method:this.method, + codegenSuccess:true}); + } else { + send({type:'artwatch-p3-clone-error',method:this.method, + error:'compiler did not complete or event setter unavailable'}); + } + } if (state && state.existingInvokeVisits > 0) { send({type:'artwatch-existing-invoke-summary', method:this.method,compilationKind:this.compilationKind, @@ -1338,10 +1353,7 @@ function attachP3CloneCanary(compiler) { getDexPc:fixture.getDexPc,invokeDexPc:fixture.invokeDexPc}); if (rc===1) { successes++; - const module=Process.findModuleByName('libartwatch_events.so'); - const address=module && module.findExportByName('artwatch_events_set_p3'); - if (address) - new NativeFunction(address,'void',['int'])(1); + p3PendingMethod = active.method; } } finally {cloning=false;} } catch(e) { 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 index f7589f6..04edf09 100644 --- 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 @@ -82,12 +82,34 @@ public static int p3TemplateCarrierOn(FieldIRTarget receiver, int x) { return observed; } - public static int exerciseP3TemplateCarrier() { + 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++) { @@ -101,8 +123,8 @@ public static int exerciseP3TemplateCarrier() { try { p3TemplateCarrierOn(null, 777); } catch (NullPointerException expected) { threw = true; } if (!threw) throw new AssertionError("P3 template null write did not throw"); - if (FieldEventSink.p3Enabled()) { - if (!FieldEventSink.p3Verified()) + 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"); diff --git a/art-fieldwatch-phase1/test/app/src/main/java/com/example/artfieldwatch/MainActivity.java b/art-fieldwatch-phase1/test/app/src/main/java/com/example/artfieldwatch/MainActivity.java index 4e13b9f..e91ea47 100644 --- a/art-fieldwatch-phase1/test/app/src/main/java/com/example/artfieldwatch/MainActivity.java +++ b/art-fieldwatch-phase1/test/app/src/main/java/com/example/artfieldwatch/MainActivity.java @@ -50,7 +50,7 @@ protected void onCreate(Bundle state) { // 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(); + int carrierChecksum = FieldIRTarget.exerciseP3TemplateCarrier(appDebuggable); Log.i("ARTWATCH_CI","P3_TEMPLATE_DONE count=" + FieldEventSink.eventCount() + " checksum=" + carrierChecksum + " nullCheck=true injected=" + From 0ea2699abbf562efe1c9cfe92d80df5a60cf46dc Mon Sep 17 00:00:00 2001 From: Muhtasham Nawr al-Mahmud <72372229+mnalmahmud@users.noreply.github.com> Date: Sun, 22 Nov 2026 15:25:26 +0600 Subject: [PATCH 100/129] fix(p3): record compiler-cloned invoke rather than original Java sentinel --- art-fieldwatch-phase1/native/runtime-events.c | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/art-fieldwatch-phase1/native/runtime-events.c b/art-fieldwatch-phase1/native/runtime-events.c index 3ea3ae0..a15cf58 100644 --- a/art-fieldwatch-phase1/native/runtime-events.c +++ b/art-fieldwatch-phase1/native/runtime-events.c @@ -70,11 +70,12 @@ Java_com_example_artfieldwatch_FieldEventSink_recordInt( // 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; - // One original Java call and one compiler-cloned call per invocation. - // Counting every second sentinel deliberately fails when no clone ran. + // ART inserts the cloned call immediately BEFORE the source invoke. + // Only record the first (compiler-inserted) invocation of each pair. + // 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; + if ((n & 1u)!=0u) return; site=9002; kind=1; } uint32_t index = atomic_fetch_add_explicit(&next_index, 1u, From 548d6ce47ce92432dfaf4666728e803cdcdb430c Mon Sep 17 00:00:00 2001 From: Muhtasham Nawr al-Mahmud <72372229+mnalmahmud@users.noreply.github.com> Date: Sun, 22 Nov 2026 15:28:05 +0600 Subject: [PATCH 101/129] feat(p3): inject compiler-generated integer field write and read event calls --- art-fieldwatch-phase1/ci/dex_method_index.py | 14 ++++-- art-fieldwatch-phase1/ci/smoke_test.py | 2 +- art-fieldwatch-phase1/jit-boundary-probe.js | 46 +++++++++++-------- art-fieldwatch-phase1/native/passive-shadow.c | 8 ++-- art-fieldwatch-phase1/native/runtime-events.c | 16 ++++--- .../example/artfieldwatch/FieldIRTarget.java | 3 +- 6 files changed, 57 insertions(+), 32 deletions(-) diff --git a/art-fieldwatch-phase1/ci/dex_method_index.py b/art-fieldwatch-phase1/ci/dex_method_index.py index 6099b10..e8ddef0 100644 --- a/art-fieldwatch-phase1/ci/dex_method_index.py +++ b/art-fieldwatch-phase1/ci/dex_method_index.py @@ -161,21 +161,29 @@ def descriptor(idx): 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_get) != 1 or len(candidates_invoke) != 1: - raise ValueError(f"ambiguous P3 opcodes: gets={candidates_get} invokes={candidates_invoke}") + 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}") found.append({"carrierMethodIndex":method_index, + "setDexPc":candidates_set[0], + "writeInvokeDexPc":candidates_invoke[0], "getDexPc":candidates_get[0], - "invokeDexPc":candidates_invoke[0]}) + "readInvokeDexPc":candidates_invoke[1]}) if len(found) != 1: raise ValueError(f"expected one P3 carrier method, found {len(found)}") return found[0] diff --git a/art-fieldwatch-phase1/ci/smoke_test.py b/art-fieldwatch-phase1/ci/smoke_test.py index 5de09ab..0b6b4db 100644 --- a/art-fieldwatch-phase1/ci/smoke_test.py +++ b/art-fieldwatch-phase1/ci/smoke_test.py @@ -86,7 +86,7 @@ def main(): 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=128 checksum=25280 nullCheck=true injected=true' + 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: diff --git a/art-fieldwatch-phase1/jit-boundary-probe.js b/art-fieldwatch-phase1/jit-boundary-probe.js index 72424a8..8424ec2 100644 --- a/art-fieldwatch-phase1/jit-boundary-probe.js +++ b/art-fieldwatch-phase1/jit-boundary-probe.js @@ -182,7 +182,7 @@ function loadPassiveShadow() { 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']) + ['pointer','pointer','pointer','uint','uint','pointer','pointer','int']) }; send({type:'artwatch-shadow-init',ready:true,source:'native', buildIdVerified:true,mutable:false}); @@ -1299,23 +1299,25 @@ function attachExistingInvokeBackend(compiler, symbol, stage) { function attachP3CloneCanary(compiler) { if (globalThis.__artwatchP3Inject !== true) return false; const fixture=globalThis.__artwatchP3Fixture; - if (!fixture || !Number.isInteger(fixture.getDexPc) || - !Number.isInteger(fixture.invokeDexPc)) return false; + 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'); - if (!site || !insert || !copyEnv || !invokeVt || !getVt) return false; + const setVt=getExport(compiler,'_ZTVN3art17HInstanceFieldSetE'); + if (!site || !insert || !copyEnv || !invokeVt || !getVt || !setVt) + return false; let cloning=false; - let successes=0; + const successfulKinds=new Set(); let attempts=0; let missedBuilder=0; try { Interceptor.attach(site.address,{ onEnter(args) { - if (cloning || successes!==0) return; + if (cloning || successfulKinds.size===2) return; const thread=this.threadId; const active=compiling.get(thread); const state=targetStates.get(thread); @@ -1330,14 +1332,22 @@ function attachP3CloneCanary(compiler) { if (!node.readPointer().equals(invokeVt.address.add(2*size))) return; const pc=Memory.alloc(4); - if (shadowShim.instructionDexPc(node,invokeVt.address,pc)!==1 || - pc.readU32()!==fixture.invokeDexPc) return; + 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; const previous=node.add(size).readPointer(); if (previous.isNull() || - !previous.readPointer().equals(getVt.address.add(2*size))) + !previous.readPointer().equals(fieldVt.address.add(2*size))) return; - if (shadowShim.instructionDexPc(previous,getVt.address,pc)!==1 || - pc.readU32()!==fixture.getDexPc) return; + if (shadowShim.instructionDexPc(previous,fieldVt.address,pc)!==1 || + pc.readU32()!==fieldPc) return; // Same-graph clone immediately before original invoke. // No HInstructionBuilder state is required, so this also works // when ART inlines AppendInstruction. @@ -1345,15 +1355,15 @@ function attachP3CloneCanary(compiler) { cloning=true; try { const rc=shadowShim.cloneBefore(node, - getVt.address,invokeVt.address, - fixture.getDexPc,fixture.invokeDexPc, - insert.address,copyEnv.address); + fieldVt.address,invokeVt.address, + fieldPc,invokePc,insert.address,copyEnv.address, + isWrite?2:1); send({type:'artwatch-p3-clone',rc,method:active.method, - attempt:attempts,trigger:'invoke_accept', - getDexPc:fixture.getDexPc,invokeDexPc:fixture.invokeDexPc}); + kind,attempt:attempts,trigger:'invoke_accept', + fieldDexPc:fieldPc,invokeDexPc}); if (rc===1) { - successes++; - p3PendingMethod = active.method; + successfulKinds.add(kind); + if (successfulKinds.size===2) p3PendingMethod=active.method; } } finally {cloning=false;} } catch(e) { diff --git a/art-fieldwatch-phase1/native/passive-shadow.c b/art-fieldwatch-phase1/native/passive-shadow.c index d17d82c..aa37ba1 100644 --- a/art-fieldwatch-phase1/native/passive-shadow.c +++ b/art-fieldwatch-phase1/native/passive-shadow.c @@ -359,12 +359,14 @@ EXPORT int artwatch_shadow_clone_template_invoke( 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) { - if (ready != 1 || !aligned(source) || !aligned(get_vtable) || + const void *insert_address, const void *copy_env_address, + int field_kind) { + 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,"_ZTVN3art17HInstanceFieldGetE"}, + {get_vtable,field_kind==2 ? + "_ZTVN3art17HInstanceFieldSetE" : "_ZTVN3art17HInstanceFieldGetE"}, {invoke_vtable,"_ZTVN3art21HInvokeStaticOrDirectE"}, {insert_address, "_ZN3art11HBasicBlock23InsertInstructionBeforeEPNS_12HInstructionES2_"}, diff --git a/art-fieldwatch-phase1/native/runtime-events.c b/art-fieldwatch-phase1/native/runtime-events.c index a15cf58..86d8491 100644 --- a/art-fieldwatch-phase1/native/runtime-events.c +++ b/art-fieldwatch-phase1/native/runtime-events.c @@ -33,13 +33,16 @@ Java_com_example_artfieldwatch_FieldEventSink_p3Enabled(JNIEnv *env,jclass cls) 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)!=128u || + 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[i],memory_order_acquire)!=1u || - events[i].site!=9002u || events[i].kind!=1u || - events[i].value!=(int32_t)(7u+3u*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; } return JNI_TRUE; @@ -71,12 +74,13 @@ Java_com_example_artfieldwatch_FieldEventSink_recordInt( 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. - // Only record the first (compiler-inserted) invocation of each pair. + // 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=9002; kind=1; + site=(n & 2u)==0u ? 9001 : 9002; + kind=(n & 2u)==0u ? 2 : 1; } uint32_t index = atomic_fetch_add_explicit(&next_index, 1u, memory_order_relaxed); 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 index 04edf09..4ff98b2 100644 --- 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 @@ -77,8 +77,9 @@ public static int watchedOn(FieldIRTarget receiver, int x) { // 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); + FieldEventSink.recordInt(0, 0, observed); // read template (cloned by ART) return observed; } From e0654c12d4064c94fe3cc72400c12c746f0e1b08 Mon Sep 17 00:00:00 2001 From: Muhtasham Nawr al-Mahmud <72372229+mnalmahmud@users.noreply.github.com> Date: Sun, 22 Nov 2026 15:28:20 +0600 Subject: [PATCH 102/129] fix(p3): include exact matched invoke DEX PC in clone event --- art-fieldwatch-phase1/jit-boundary-probe.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/art-fieldwatch-phase1/jit-boundary-probe.js b/art-fieldwatch-phase1/jit-boundary-probe.js index 8424ec2..78991f3 100644 --- a/art-fieldwatch-phase1/jit-boundary-probe.js +++ b/art-fieldwatch-phase1/jit-boundary-probe.js @@ -1360,7 +1360,7 @@ function attachP3CloneCanary(compiler) { isWrite?2:1); send({type:'artwatch-p3-clone',rc,method:active.method, kind,attempt:attempts,trigger:'invoke_accept', - fieldDexPc:fieldPc,invokeDexPc}); + fieldDexPc:fieldPc,invokeDexPc:invokePc}); if (rc===1) { successfulKinds.add(kind); if (successfulKinds.size===2) p3PendingMethod=active.method; From a81d82e1cf4a49d758c27a70a172a1152e4cd3b9 Mon Sep 17 00:00:00 2001 From: Muhtasham Nawr al-Mahmud <72372229+mnalmahmud@users.noreply.github.com> Date: Sun, 22 Nov 2026 15:34:03 +0600 Subject: [PATCH 103/129] fix(p3): match write field store through same-block IR predecessors --- art-fieldwatch-phase1/jit-boundary-probe.js | 23 +++++++++---- art-fieldwatch-phase1/native/passive-shadow.c | 34 ++++++++++++++----- 2 files changed, 41 insertions(+), 16 deletions(-) diff --git a/art-fieldwatch-phase1/jit-boundary-probe.js b/art-fieldwatch-phase1/jit-boundary-probe.js index 78991f3..c5275e5 100644 --- a/art-fieldwatch-phase1/jit-boundary-probe.js +++ b/art-fieldwatch-phase1/jit-boundary-probe.js @@ -1312,6 +1312,7 @@ function attachP3CloneCanary(compiler) { return false; let cloning=false; const successfulKinds=new Set(); + let successfulMethod=null; let attempts=0; let missedBuilder=0; try { @@ -1321,7 +1322,8 @@ function attachP3CloneCanary(compiler) { const thread=this.threadId; const active=compiling.get(thread); const state=targetStates.get(thread); - if (!active || !state || !targetMethodPointers.has(active.method)) + if (!active || !state || !targetMethodPointers.has(active.method) || + (successfulMethod!==null && successfulMethod!==active.method)) return; if (!shadowShim) loadPassiveShadow(); if (!shadowShim || !shadowShim.cloneBefore || @@ -1342,12 +1344,18 @@ function attachP3CloneCanary(compiler) { if (successfulKinds.has(kind)) return; const fieldVt=isWrite?setVt:getVt; const fieldPc=isWrite?fixture.setDexPc:fixture.getDexPc; - 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; + 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. @@ -1362,6 +1370,7 @@ function attachP3CloneCanary(compiler) { kind,attempt:attempts,trigger:'invoke_accept', fieldDexPc:fieldPc,invokeDexPc:invokePc}); if (rc===1) { + if (successfulMethod===null) successfulMethod=active.method; successfulKinds.add(kind); if (successfulKinds.size===2) p3PendingMethod=active.method; } diff --git a/art-fieldwatch-phase1/native/passive-shadow.c b/art-fieldwatch-phase1/native/passive-shadow.c index aa37ba1..cb16b33 100644 --- a/art-fieldwatch-phase1/native/passive-shadow.c +++ b/art-fieldwatch-phase1/native/passive-shadow.c @@ -380,7 +380,7 @@ EXPORT int artwatch_shadow_clone_invoke_before( 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,*get_vptr=NULL; + 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)); @@ -388,14 +388,30 @@ EXPORT int artwatch_shadow_clone_invoke_before( 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; - memcpy(&get_vptr,get,sizeof(get_vptr)); - memcpy(&get_pc,(const uint8_t*)get+32,sizeof(get_pc)); - if (get_vptr!=(const uint8_t*)get_vtable+16 || - get_pc!=expected_get_pc) return -4; - const void *get_next=NULL,*get_block=NULL; - memcpy(&get_next,(const uint8_t*)get+16,sizeof(get_next)); - memcpy(&get_block,(const uint8_t*)get+24,sizeof(get_block)); - if (get_next!=source || get_block!=block) return -5; + // 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 Date: Mon, 23 Nov 2026 02:00:15 +0600 Subject: [PATCH 104/129] test(p3): prove cloned field invokes survive JIT backend emission --- art-fieldwatch-phase1/ci/smoke_test.py | 32 +++++++++++++++++++ art-fieldwatch-phase1/jit-boundary-probe.js | 31 ++++++++++++++---- art-fieldwatch-phase1/native/passive-shadow.c | 11 +++++-- 3 files changed, 64 insertions(+), 10 deletions(-) diff --git a/art-fieldwatch-phase1/ci/smoke_test.py b/art-fieldwatch-phase1/ci/smoke_test.py index 0b6b4db..1725e39 100644 --- a/art-fieldwatch-phase1/ci/smoke_test.py +++ b/art-fieldwatch-phase1/ci/smoke_test.py @@ -158,6 +158,38 @@ def main(): 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: + 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. diff --git a/art-fieldwatch-phase1/jit-boundary-probe.js b/art-fieldwatch-phase1/jit-boundary-probe.js index c5275e5..731814f 100644 --- a/art-fieldwatch-phase1/jit-boundary-probe.js +++ b/art-fieldwatch-phase1/jit-boundary-probe.js @@ -182,7 +182,7 @@ function loadPassiveShadow() { 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','pointer','pointer','uint','uint','pointer','pointer','int','pointer']) }; send({type:'artwatch-shadow-init',ready:true,source:'native', buildIdVerified:true,mutable:false}); @@ -246,7 +246,7 @@ function attach(layer, site) { method: this.method, kind: this.compilationKind, existingInvokeVisits: 0, existingInvokeNodes: new Set(), existingInvokeBlockVisits: 0, - p3Builder: null, + p3Builder: null, p3ClonedNodes: new Map(), existingInvokeLocations: new Set(), existingInvokeEmitted: new Set(), adjacencyProbes: 0, adjacencyMatches: 0, @@ -287,13 +287,22 @@ function attach(layer, site) { p3PendingMethod = null; const module = Process.findModuleByName('libartwatch_events.so'); const fn = module && module.findExportByName('artwatch_events_set_p3'); - if (succeeded && fn !== null) { + 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; + if (succeeded && codegenProven && fn !== null) { new NativeFunction(fn,'void',['int'])(1); send({type:'artwatch-p3-compiled',method:this.method, - codegenSuccess:true}); + codegenSuccess:true,cloneProof:proofs}); } else { send({type:'artwatch-p3-clone-error',method:this.method, - error:'compiler did not complete or event setter unavailable'}); + error:'compiler completion, cloned invoke codegen, or event setter failed', + compilerSucceeded:succeeded,cloneProof:proofs}); } } if (state && state.existingInvokeVisits > 0) { @@ -1362,17 +1371,25 @@ function attachP3CloneCanary(compiler) { 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); + 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) { + 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) { diff --git a/art-fieldwatch-phase1/native/passive-shadow.c b/art-fieldwatch-phase1/native/passive-shadow.c index cb16b33..63ce827 100644 --- a/art-fieldwatch-phase1/native/passive-shadow.c +++ b/art-fieldwatch-phase1/native/passive-shadow.c @@ -360,7 +360,9 @@ 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) { + 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; @@ -467,8 +469,11 @@ EXPORT int artwatch_shadow_clone_invoke_before( memcpy(©_block,(const uint8_t*)copy+24,8); memcpy(©_next,(const uint8_t*)copy+16,8); memcpy(©_env,(const uint8_t*)copy+64,8); - return copy_block==block && copy_next==source && copy_env==environment ? - 1 : -12; + 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) { From 3d0c53141b3d880c660a6195d1955ae4868f9b21 Mon Sep 17 00:00:00 2001 From: Muhtasham Nawr al-Mahmud <72372229+mnalmahmud@users.noreply.github.com> Date: Mon, 23 Nov 2026 02:11:08 +0600 Subject: [PATCH 105/129] test(p3): archive actual compiler-injected event stream before P2 reset --- art-fieldwatch-phase1/ci/smoke_test.py | 24 +++++++++++++ art-fieldwatch-phase1/jit-boundary-probe.js | 11 ++++++ art-fieldwatch-phase1/native/runtime-events.c | 35 +++++++++++++++---- 3 files changed, 63 insertions(+), 7 deletions(-) diff --git a/art-fieldwatch-phase1/ci/smoke_test.py b/art-fieldwatch-phase1/ci/smoke_test.py index 1725e39..6f19445 100644 --- a/art-fieldwatch-phase1/ci/smoke_test.py +++ b/art-fieldwatch-phase1/ci/smoke_test.py @@ -32,6 +32,7 @@ def main(): record('host','spawned-pid='+str(pid)) session = device.attach(pid) runtime_snapshot = None + p3_snapshot = None try: source = (BASE/'jit-boundary-probe.js').read_text() sink_inventory = LOG_DIR / ('p3-sink-method-' + @@ -60,6 +61,13 @@ def main(): 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() + if os.environ.get('ARTWATCH_P3_INJECT') == '1': + p3_snapshot = script.exports_sync.p3events() + (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")} ' @@ -91,6 +99,22 @@ def main(): 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}') + 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' diff --git a/art-fieldwatch-phase1/jit-boundary-probe.js b/art-fieldwatch-phase1/jit-boundary-probe.js index 731814f..e4e50b8 100644 --- a/art-fieldwatch-phase1/jit-boundary-probe.js +++ b/art-fieldwatch-phase1/jit-boundary-probe.js @@ -1546,6 +1546,17 @@ function main() { // 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 = { + 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'}; diff --git a/art-fieldwatch-phase1/native/runtime-events.c b/art-fieldwatch-phase1/native/runtime-events.c index 86d8491..7ee39c4 100644 --- a/art-fieldwatch-phase1/native/runtime-events.c +++ b/art-fieldwatch-phase1/native/runtime-events.c @@ -7,6 +7,7 @@ #include #include #include +#include #define EVENT_EXPORT __attribute__((visibility("default"))) #define EVENT_CAPACITY 512u @@ -21,6 +22,9 @@ 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; // 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); @@ -45,6 +49,8 @@ Java_com_example_artfieldwatch_FieldEventSink_p3Verified(JNIEnv *env,jclass cls) events[2u*i+1u].value!=(int32_t)(7u+3u*i)) 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; } @@ -103,24 +109,25 @@ Java_com_example_artfieldwatch_FieldEventSink_eventCount(JNIEnv *env, jclass cls // 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. -EVENT_EXPORT int artwatch_events_snapshot(char *out, uint32_t length) { +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; - 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 stored = total < EVENT_CAPACITY ? total : EVENT_CAPACITY; 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 < stored; ++i) { - if (atomic_load_explicit(&ready[i], memory_order_acquire) != 1u) return 0; + 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, - events[i].site, events[i].kind, events[i].value); + 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; } @@ -130,3 +137,17 @@ EVENT_EXPORT int artwatch_events_snapshot(char *out, uint32_t length) { 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); +} From b6106bc2e7261887e06bf525b0688b0d51d47a8d Mon Sep 17 00:00:00 2001 From: Muhtasham Nawr al-Mahmud <72372229+mnalmahmud@users.noreply.github.com> Date: Mon, 23 Nov 2026 02:16:03 +0600 Subject: [PATCH 106/129] feat(fieldwatch): index arbitrary DEX field access sites with method, field, PC and line --- art-fieldwatch-phase1/ci/dex_field_sites.py | 237 ++++++++++++++++++++ 1 file changed, 237 insertions(+) create mode 100644 art-fieldwatch-phase1/ci/dex_field_sites.py 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..a74b612 --- /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 name in names: + dex=Dex(z.read(name),name) + sites=dex.sites() + dex_files.append({"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"*4,0,0,6)==6 + 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) From 3805f1542d7caf9394d5219ff13f86e177ddd929 Mon Sep 17 00:00:00 2001 From: Muhtasham Nawr al-Mahmud <72372229+mnalmahmud@users.noreply.github.com> Date: Mon, 23 Nov 2026 02:16:33 +0600 Subject: [PATCH 107/129] fix(fieldwatch): correct debug-info parsing and DEX bytes in decoder self-tests --- art-fieldwatch-phase1/ci/dex_field_sites.py | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/art-fieldwatch-phase1/ci/dex_field_sites.py b/art-fieldwatch-phase1/ci/dex_field_sites.py index a74b612..d25e8d4 100644 --- a/art-fieldwatch-phase1/ci/dex_field_sites.py +++ b/art-fieldwatch-phase1/ci/dex_field_sites.py @@ -86,7 +86,7 @@ def debug_lines(data, off): 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): + elif op == 9: _,off=uleb128(data,off) elif op in (7,8): pass else: @@ -212,10 +212,10 @@ def self_test(): 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"*4,0,0,6)==6 - try: insn_width(b"\\x52\\x00",0,0,1) + 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"*4,0,0,6)==6 + 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") From eeaa40ab708eddc883657c0aaaf9ca6b2ed8b463 Mon Sep 17 00:00:00 2001 From: Muhtasham Nawr al-Mahmud <72372229+mnalmahmud@users.noreply.github.com> Date: Mon, 23 Nov 2026 02:16:57 +0600 Subject: [PATCH 108/129] test(fieldwatch): audit all APK field sites across debug and release CI --- .github/workflows/art-fieldwatch-phase1.yml | 1 + art-fieldwatch-phase1/ci/dex-inventory.sh | 4 ++++ art-fieldwatch-phase1/ci/dex_field_sites.py | 2 +- 3 files changed, 6 insertions(+), 1 deletion(-) diff --git a/.github/workflows/art-fieldwatch-phase1.yml b/.github/workflows/art-fieldwatch-phase1.yml index 7e9b637..9ac94e4 100644 --- a/.github/workflows/art-fieldwatch-phase1.yml +++ b/.github/workflows/art-fieldwatch-phase1.yml @@ -24,6 +24,7 @@ jobs: - 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: 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 diff --git a/art-fieldwatch-phase1/ci/dex-inventory.sh b/art-fieldwatch-phase1/ci/dex-inventory.sh index 09183c2..99a1317 100644 --- a/art-fieldwatch-phase1/ci/dex-inventory.sh +++ b/art-fieldwatch-phase1/ci/dex-inventory.sh @@ -14,6 +14,10 @@ unzip -p "$apk" classes.dex | sha256sum | tee "$out/dex-sha256-$variant.txt" # 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)" diff --git a/art-fieldwatch-phase1/ci/dex_field_sites.py b/art-fieldwatch-phase1/ci/dex_field_sites.py index d25e8d4..7288130 100644 --- a/art-fieldwatch-phase1/ci/dex_field_sites.py +++ b/art-fieldwatch-phase1/ci/dex_field_sites.py @@ -214,7 +214,7 @@ def self_test(): 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"*4,0,0,6)==6 + 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") From 56a4fac3d1b8cc6932e08ce6ee76fea0fd6ea4a2 Mon Sep 17 00:00:00 2001 From: Muhtasham Nawr al-Mahmud <72372229+mnalmahmud@users.noreply.github.com> Date: Mon, 23 Nov 2026 02:17:11 +0600 Subject: [PATCH 109/129] fix(fieldwatch): decode END_LOCAL and RESTART_LOCAL register operands --- art-fieldwatch-phase1/ci/dex_field_sites.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/art-fieldwatch-phase1/ci/dex_field_sites.py b/art-fieldwatch-phase1/ci/dex_field_sites.py index 7288130..e81c2d8 100644 --- a/art-fieldwatch-phase1/ci/dex_field_sites.py +++ b/art-fieldwatch-phase1/ci/dex_field_sites.py @@ -86,7 +86,7 @@ def debug_lines(data, off): elif op in (3,4): count=4 if op==4 else 3 for __ in range(count): _,off=uleb128(data,off) - elif op == 9: + elif op in (5,6,9): _,off=uleb128(data,off) elif op in (7,8): pass else: From 5d5582f863a19301146c621a8f5cfbb036417617 Mon Sep 17 00:00:00 2001 From: Muhtasham Nawr al-Mahmud <72372229+mnalmahmud@users.noreply.github.com> Date: Mon, 23 Nov 2026 02:18:10 +0600 Subject: [PATCH 110/129] feat(fieldwatch): add typed field-event ABI with explicit DEX method, field and PC metadata --- .../ci/build-passive-shim.sh | 2 +- art-fieldwatch-phase1/jit-boundary-probe.js | 11 ++++ art-fieldwatch-phase1/native/runtime-events.c | 65 +++++++++++++++++++ 3 files changed, 77 insertions(+), 1 deletion(-) diff --git a/art-fieldwatch-phase1/ci/build-passive-shim.sh b/art-fieldwatch-phase1/ci/build-passive-shim.sh index b9c16f9..4a52494 100644 --- a/art-fieldwatch-phase1/ci/build-passive-shim.sh +++ b/art-fieldwatch-phase1/ci/build-passive-shim.sh @@ -34,7 +34,7 @@ echo "Native shadow library staged for APK packaging: $jni_dir" art-fieldwatch-phase1/native/runtime-events.c \ -o "$out/libartwatch_events.so" readelf -Ws "$out/libartwatch_events.so" | - grep -E '(artwatch_events_snapshot|Java_com_example_artfieldwatch_FieldEventSink_(recordInt|reset|eventCount|p3Enabled|p3Verified))' | + grep -E '(artwatch_events_(snapshot|p3_snapshot|record_field|field_snapshot)|Java_com_example_artfieldwatch_FieldEventSink_(recordInt|reset|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" diff --git a/art-fieldwatch-phase1/jit-boundary-probe.js b/art-fieldwatch-phase1/jit-boundary-probe.js index e4e50b8..1d4366c 100644 --- a/art-fieldwatch-phase1/jit-boundary-probe.js +++ b/art-fieldwatch-phase1/jit-boundary-probe.js @@ -1546,6 +1546,17 @@ function main() { // 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 = { + 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'}; diff --git a/art-fieldwatch-phase1/native/runtime-events.c b/art-fieldwatch-phase1/native/runtime-events.c index 7ee39c4..8e71144 100644 --- a/art-fieldwatch-phase1/native/runtime-events.c +++ b/art-fieldwatch-phase1/native/runtime-events.c @@ -151,3 +151,68 @@ EVENT_EXPORT int artwatch_events_snapshot(char *out, uint32_t length) { 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; +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); +} +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; +} From d519d2738fb0f252c6642980049cab9d2c0a07fd Mon Sep 17 00:00:00 2001 From: Muhtasham Nawr al-Mahmud <72372229+mnalmahmud@users.noreply.github.com> Date: Mon, 23 Nov 2026 06:02:01 +0600 Subject: [PATCH 111/129] feat(fieldwatch): assign stable APK DEX IDs and retain exact P3 field index --- art-fieldwatch-phase1/ci/dex_field_sites.py | 4 ++-- art-fieldwatch-phase1/ci/dex_method_index.py | 10 ++++++++-- 2 files changed, 10 insertions(+), 4 deletions(-) diff --git a/art-fieldwatch-phase1/ci/dex_field_sites.py b/art-fieldwatch-phase1/ci/dex_field_sites.py index e81c2d8..704222c 100644 --- a/art-fieldwatch-phase1/ci/dex_field_sites.py +++ b/art-fieldwatch-phase1/ci/dex_field_sites.py @@ -198,10 +198,10 @@ def inventory(apk): (n.startswith("classes") and n.endswith(".dex") and n[7:-4].isdigit())) if not names: raise ValueError("APK has no DEX") dex_files=[] - for name in names: + for dex_id,name in enumerate(names): dex=Dex(z.read(name),name) sites=dex.sites() - dex_files.append({"name":name,"sha256":dex.shasum, + 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), diff --git a/art-fieldwatch-phase1/ci/dex_method_index.py b/art-fieldwatch-phase1/ci/dex_method_index.py index e8ddef0..650f9bf 100644 --- a/art-fieldwatch-phase1/ci/dex_method_index.py +++ b/art-fieldwatch-phase1/ci/dex_method_index.py @@ -179,7 +179,12 @@ def descriptor(idx): 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], @@ -196,7 +201,7 @@ def apk_sink_method(apk): (x.startswith("classes") and x.endswith(".dex") and x[7:-4].isdigit())) matches = [] - for name in dex_names: + for dex_id, name in enumerate(dex_names): data = archive.read(name) try: idx = sink_method_index(data) @@ -210,7 +215,8 @@ def apk_sink_method(apk): if "expected one P3 carrier method, found 0" in str(e): continue raise - matches.append({"dex": name, "methodIndex": idx, + matches.append({"dex": name, "dexId":dex_id, + "methodIndex": idx, **pcs, "sha256": hashlib.sha256(data).hexdigest()}) if len(matches) != 1: From 75b9de4ffbf85c11a9ba015275e18b1444bf50d5 Mon Sep 17 00:00:00 2001 From: Muhtasham Nawr al-Mahmud <72372229+mnalmahmud@users.noreply.github.com> Date: Mon, 23 Nov 2026 06:03:30 +0600 Subject: [PATCH 112/129] feat(p3): emit exact DEX method/field/PC metadata for compiler-cloned int accesses --- art-fieldwatch-phase1/ci/smoke_test.py | 33 ++++++++++++++++- art-fieldwatch-phase1/jit-boundary-probe.js | 24 ++++++++++--- art-fieldwatch-phase1/native/runtime-events.c | 35 +++++++++++++++++++ 3 files changed, 87 insertions(+), 5 deletions(-) diff --git a/art-fieldwatch-phase1/ci/smoke_test.py b/art-fieldwatch-phase1/ci/smoke_test.py index 6f19445..1cf90a9 100644 --- a/art-fieldwatch-phase1/ci/smoke_test.py +++ b/art-fieldwatch-phase1/ci/smoke_test.py @@ -33,6 +33,7 @@ def main(): session = device.attach(pid) runtime_snapshot = None p3_snapshot = None + field_snapshot = None try: source = (BASE/'jit-boundary-probe.js').read_text() sink_inventory = LOG_DIR / ('p3-sink-method-' + @@ -63,6 +64,11 @@ def main(): runtime_snapshot = script.exports_sync.runtimeevents() if os.environ.get('ARTWATCH_P3_INJECT') == '1': p3_snapshot = script.exports_sync.p3events() + field_snapshot = script.exports_sync.fieldmeta() + (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")} ' @@ -113,6 +119,30 @@ def main(): 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}') + 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'): @@ -199,7 +229,8 @@ def main(): 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: + 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 diff --git a/art-fieldwatch-phase1/jit-boundary-probe.js b/art-fieldwatch-phase1/jit-boundary-probe.js index 1d4366c..d1cf5b1 100644 --- a/art-fieldwatch-phase1/jit-boundary-probe.js +++ b/art-fieldwatch-phase1/jit-boundary-probe.js @@ -287,6 +287,7 @@ function attach(layer, site) { 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, @@ -295,10 +296,25 @@ function attach(layer, site) { }); const codegenProven=proofs.every(p => p.node && p.locations && p.emitted) && proofs[0].node !== proofs[1].node; - if (succeeded && codegenProven && fn !== null) { - new NativeFunction(fn,'void',['int'])(1); - send({type:'artwatch-p3-compiled',method:this.method, - codegenSuccess:true,cloneProof:proofs}); + 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', diff --git a/art-fieldwatch-phase1/native/runtime-events.c b/art-fieldwatch-phase1/native/runtime-events.c index 8e71144..90f9b23 100644 --- a/art-fieldwatch-phase1/native/runtime-events.c +++ b/art-fieldwatch-phase1/native/runtime-events.c @@ -25,6 +25,29 @@ 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; +// 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); @@ -87,6 +110,18 @@ Java_com_example_artfieldwatch_FieldEventSink_recordInt( 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); From 7f82ad0ac973392a3bacc6851a72e5e091a973a4 Mon Sep 17 00:00:00 2001 From: Muhtasham Nawr al-Mahmud <72372229+mnalmahmud@users.noreply.github.com> Date: Mon, 23 Nov 2026 06:04:49 +0600 Subject: [PATCH 113/129] feat(p3): implement source-matched integer access cloning across instance/static get/set --- .../native/p3-clone-injector-art.cc | 218 ++++++++++++++++++ 1 file changed, 218 insertions(+) diff --git a/art-fieldwatch-phase1/native/p3-clone-injector-art.cc b/art-fieldwatch-phase1/native/p3-clone-injector-art.cc index a53f5d8..2fda4f6 100644 --- a/art-fieldwatch-phase1/native/p3-clone-injector-art.cc +++ b/art-fieldwatch-phase1/native/p3-clone-injector-art.cc @@ -155,5 +155,223 @@ CloneResult CloneUniqueIntReadInGraph( 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 From 1d1fabbcb181f064ceae83eb0dbabbe9994f6b11 Mon Sep 17 00:00:00 2001 From: Muhtasham Nawr al-Mahmud <72372229+mnalmahmud@users.noreply.github.com> Date: Mon, 23 Nov 2026 06:39:34 +0600 Subject: [PATCH 114/129] fix(p3): isolate typed metadata measurement and preserve verified events across P2 reset --- .../ci/build-passive-shim.sh | 2 +- art-fieldwatch-phase1/ci/smoke_test.py | 2 +- art-fieldwatch-phase1/jit-boundary-probe.js | 11 ++++ art-fieldwatch-phase1/native/runtime-events.c | 62 +++++++++++++++++++ 4 files changed, 75 insertions(+), 2 deletions(-) diff --git a/art-fieldwatch-phase1/ci/build-passive-shim.sh b/art-fieldwatch-phase1/ci/build-passive-shim.sh index 4a52494..f8776ee 100644 --- a/art-fieldwatch-phase1/ci/build-passive-shim.sh +++ b/art-fieldwatch-phase1/ci/build-passive-shim.sh @@ -34,7 +34,7 @@ echo "Native shadow library staged for APK packaging: $jni_dir" 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)|Java_com_example_artfieldwatch_FieldEventSink_(recordInt|reset|eventCount|p3Enabled|p3Verified))' | + grep -E '(artwatch_events_(snapshot|p3_snapshot|record_field|field_snapshot|p3_field_snapshot|configure_p3)|Java_com_example_artfieldwatch_FieldEventSink_(recordInt|reset|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" diff --git a/art-fieldwatch-phase1/ci/smoke_test.py b/art-fieldwatch-phase1/ci/smoke_test.py index 1cf90a9..3fdc8a1 100644 --- a/art-fieldwatch-phase1/ci/smoke_test.py +++ b/art-fieldwatch-phase1/ci/smoke_test.py @@ -64,7 +64,7 @@ def main(): runtime_snapshot = script.exports_sync.runtimeevents() if os.environ.get('ARTWATCH_P3_INJECT') == '1': p3_snapshot = script.exports_sync.p3events() - field_snapshot = script.exports_sync.fieldmeta() + 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")} ' diff --git a/art-fieldwatch-phase1/jit-boundary-probe.js b/art-fieldwatch-phase1/jit-boundary-probe.js index d1cf5b1..fbc8602 100644 --- a/art-fieldwatch-phase1/jit-boundary-probe.js +++ b/art-fieldwatch-phase1/jit-boundary-probe.js @@ -1562,6 +1562,17 @@ function main() { // 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 = { + 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'}; diff --git a/art-fieldwatch-phase1/native/runtime-events.c b/art-fieldwatch-phase1/native/runtime-events.c index 90f9b23..2014ea5 100644 --- a/art-fieldwatch-phase1/native/runtime-events.c +++ b/art-fieldwatch-phase1/native/runtime-events.c @@ -25,6 +25,8 @@ 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. @@ -72,6 +74,9 @@ Java_com_example_artfieldwatch_FieldEventSink_p3Verified(JNIEnv *env,jclass cls) 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; @@ -84,6 +89,7 @@ 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); } @@ -209,6 +215,38 @@ 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) { @@ -251,3 +289,27 @@ EVENT_EXPORT int artwatch_events_field_snapshot(char *out,uint32_t length) { 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; +} From efe23cbc68f6224a3ecf44568d0b41e49700c3bb Mon Sep 17 00:00:00 2001 From: Muhtasham Nawr al-Mahmud <72372229+mnalmahmud@users.noreply.github.com> Date: Mon, 23 Nov 2026 06:39:48 +0600 Subject: [PATCH 115/129] fix(p3): terminate archived metadata JSON with NUL byte --- art-fieldwatch-phase1/native/runtime-events.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/art-fieldwatch-phase1/native/runtime-events.c b/art-fieldwatch-phase1/native/runtime-events.c index 2014ea5..4ea14be 100644 --- a/art-fieldwatch-phase1/native/runtime-events.c +++ b/art-fieldwatch-phase1/native/runtime-events.c @@ -310,6 +310,6 @@ EVENT_EXPORT int artwatch_events_p3_field_snapshot(char *out,uint32_t length) { used+=(size_t)n; } if (used+3u>length) return 0; - out[used++]=']';out[used++]='}';out[used]='\\0'; + out[used++]=']';out[used++]='}';out[used]='\0'; return 1; } From ac999fa36bdb6f06d9a824deaf66af82604da713 Mon Sep 17 00:00:00 2001 From: Muhtasham Nawr al-Mahmud <72372229+mnalmahmud@users.noreply.github.com> Date: Mon, 23 Nov 2026 07:07:41 +0600 Subject: [PATCH 116/129] feat(art): construct typed field event invokes directly from SSA without template --- .../native/p3-direct-injector-art.cc | 189 ++++++++++++++++++ 1 file changed, 189 insertions(+) create mode 100644 art-fieldwatch-phase1/native/p3-direct-injector-art.cc 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..74bfc3d --- /dev/null +++ b/art-fieldwatch-phase1/native/p3-direct-injector-art.cc @@ -0,0 +1,189 @@ +// 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; + } + 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; + } + // 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 From e5be1590b6125b3c8a96b15f6674e947be49772c Mon Sep 17 00:00:00 2001 From: Muhtasham Nawr al-Mahmud <72372229+mnalmahmud@users.noreply.github.com> Date: Mon, 23 Nov 2026 07:08:58 +0600 Subject: [PATCH 117/129] feat(fieldwatch): exercise direct 6-int JNI field event ABI on actual Android runtime --- .../ci/build-passive-shim.sh | 2 +- art-fieldwatch-phase1/ci/smoke_test.py | 22 +++++++++++++++++ art-fieldwatch-phase1/native/runtime-events.c | 22 +++++++++++++++++ .../artfieldwatch/DirectAbiTarget.java | 24 +++++++++++++++++++ .../example/artfieldwatch/FieldEventSink.java | 4 ++++ .../example/artfieldwatch/MainActivity.java | 5 ++++ 6 files changed, 78 insertions(+), 1 deletion(-) create mode 100644 art-fieldwatch-phase1/test/app/src/main/java/com/example/artfieldwatch/DirectAbiTarget.java diff --git a/art-fieldwatch-phase1/ci/build-passive-shim.sh b/art-fieldwatch-phase1/ci/build-passive-shim.sh index f8776ee..44e53bd 100644 --- a/art-fieldwatch-phase1/ci/build-passive-shim.sh +++ b/art-fieldwatch-phase1/ci/build-passive-shim.sh @@ -34,7 +34,7 @@ echo "Native shadow library staged for APK packaging: $jni_dir" 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|reset|eventCount|p3Enabled|p3Verified))' | + grep -E '(artwatch_events_(snapshot|p3_snapshot|record_field|field_snapshot|p3_field_snapshot|configure_p3)|Java_com_example_artfieldwatch_FieldEventSink_(recordInt|recordFieldInt|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" diff --git a/art-fieldwatch-phase1/ci/smoke_test.py b/art-fieldwatch-phase1/ci/smoke_test.py index 3fdc8a1..cca98ff 100644 --- a/art-fieldwatch-phase1/ci/smoke_test.py +++ b/art-fieldwatch-phase1/ci/smoke_test.py @@ -34,6 +34,7 @@ def main(): runtime_snapshot = None p3_snapshot = None field_snapshot = None + direct_abi_snapshot = None try: source = (BASE/'jit-boundary-probe.js').read_text() sink_inventory = LOG_DIR / ('p3-sink-method-' + @@ -62,6 +63,9 @@ def main(): 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() + (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() @@ -152,6 +156,24 @@ def main(): 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: + 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)] + if direct_abi_snapshot.get('total') != 4 or ( + direct_abi_snapshot.get('dropped') != 0 or len(records_abi) != 4): + raise AssertionError('Direct six-int native ABI count mismatch') + for i,(value,kind,field_id,method_id,dex_pc) in enumerate(values_abi): + expected_abi = { + 'seq':i+1,'dexId':0,'methodId':method_id,'fieldId':field_id, + 'dexPc':dex_pc,'kind':kind,'type':5, + 'valueBits':f'0x{value & ((1<<64)-1):016x}'} + if records_abi[i] != expected_abi: + raise AssertionError(f'Direct JNI ABI record invalid: {records_abi[i]}') + record('host','PASS: direct six-int JNI ABI, four exact field records') 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') diff --git a/art-fieldwatch-phase1/native/runtime-events.c b/art-fieldwatch-phase1/native/runtime-events.c index 4ea14be..dbd2447 100644 --- a/art-fieldwatch-phase1/native/runtime-events.c +++ b/art-fieldwatch-phase1/native/runtime-events.c @@ -224,6 +224,16 @@ static void reset_detailed_events(void) { for(uint32_t i=0;i 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") From 27f0533bb4f084badadb602775c274addaf2fdfe Mon Sep 17 00:00:00 2001 From: Muhtasham Nawr al-Mahmud <72372229+mnalmahmud@users.noreply.github.com> Date: Mon, 23 Nov 2026 15:06:26 +0600 Subject: [PATCH 120/129] test(fieldwatch): join live P3 events with packaged DEX field and caller identities --- .github/workflows/art-fieldwatch-phase1.yml | 1 + art-fieldwatch-phase1/ci/smoke_test.py | 20 ++++++++++++++++++++ 2 files changed, 21 insertions(+) diff --git a/.github/workflows/art-fieldwatch-phase1.yml b/.github/workflows/art-fieldwatch-phase1.yml index 9ac94e4..f8f405b 100644 --- a/.github/workflows/art-fieldwatch-phase1.yml +++ b/.github/workflows/art-fieldwatch-phase1.yml @@ -25,6 +25,7 @@ jobs: - 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 diff --git a/art-fieldwatch-phase1/ci/smoke_test.py b/art-fieldwatch-phase1/ci/smoke_test.py index cca98ff..7f593eb 100644 --- a/art-fieldwatch-phase1/ci/smoke_test.py +++ b/art-fieldwatch-phase1/ci/smoke_test.py @@ -7,6 +7,7 @@ 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')) @@ -145,6 +146,25 @@ def main(): 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 ' From 0726e10e0e45bda8e8abd5e616d9ffeaeb0109c1 Mon Sep 17 00:00:00 2001 From: Muhtasham Nawr al-Mahmud <72372229+mnalmahmud@users.noreply.github.com> Date: Mon, 23 Nov 2026 16:21:51 +0600 Subject: [PATCH 121/129] feat(fieldwatch): carry exact long/float/double and narrow primitives through executable JNI ABI --- .../ci/build-passive-shim.sh | 2 +- art-fieldwatch-phase1/ci/smoke_test.py | 39 ++++++++++--- art-fieldwatch-phase1/native/runtime-events.c | 58 +++++++++++++++++++ .../example/artfieldwatch/FieldEventSink.java | 10 ++++ .../example/artfieldwatch/MainActivity.java | 4 ++ .../artfieldwatch/PrimitiveAbiTarget.java | 35 +++++++++++ 6 files changed, 138 insertions(+), 10 deletions(-) create mode 100644 art-fieldwatch-phase1/test/app/src/main/java/com/example/artfieldwatch/PrimitiveAbiTarget.java diff --git a/art-fieldwatch-phase1/ci/build-passive-shim.sh b/art-fieldwatch-phase1/ci/build-passive-shim.sh index 44e53bd..0bf9aa4 100644 --- a/art-fieldwatch-phase1/ci/build-passive-shim.sh +++ b/art-fieldwatch-phase1/ci/build-passive-shim.sh @@ -34,7 +34,7 @@ echo "Native shadow library staged for APK packaging: $jni_dir" 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|reset|resetFieldMeta|fieldMetaCount|eventCount|p3Enabled|p3Verified))' | + 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" diff --git a/art-fieldwatch-phase1/ci/smoke_test.py b/art-fieldwatch-phase1/ci/smoke_test.py index 7f593eb..5088fea 100644 --- a/art-fieldwatch-phase1/ci/smoke_test.py +++ b/art-fieldwatch-phase1/ci/smoke_test.py @@ -176,6 +176,9 @@ def main(): 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 '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: @@ -183,17 +186,35 @@ def main(): 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)] - if direct_abi_snapshot.get('total') != 4 or ( - direct_abi_snapshot.get('dropped') != 0 or len(records_abi) != 4): - raise AssertionError('Direct six-int native ABI count mismatch') - for i,(value,kind,field_id,method_id,dex_pc) in enumerate(values_abi): + 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':0,'methodId':method_id,'fieldId':field_id, - 'dexPc':dex_pc,'kind':kind,'type':5, - 'valueBits':f'0x{value & ((1<<64)-1):016x}'} + '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 JNI ABI record invalid: {records_abi[i]}') - record('host','PASS: direct six-int JNI ABI, four exact field records') + 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') diff --git a/art-fieldwatch-phase1/native/runtime-events.c b/art-fieldwatch-phase1/native/runtime-events.c index dbd2447..57d654a 100644 --- a/art-fieldwatch-phase1/native/runtime-events.c +++ b/art-fieldwatch-phase1/native/runtime-events.c @@ -284,6 +284,64 @@ Java_com_example_artfieldwatch_FieldEventSink_recordFieldInt( (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); 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 index 7933108..7cd9b63 100644 --- 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 @@ -16,6 +16,16 @@ private FieldEventSink() {} 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(); diff --git a/art-fieldwatch-phase1/test/app/src/main/java/com/example/artfieldwatch/MainActivity.java b/art-fieldwatch-phase1/test/app/src/main/java/com/example/artfieldwatch/MainActivity.java index d8d5e2e..cef5847 100644 --- a/art-fieldwatch-phase1/test/app/src/main/java/com/example/artfieldwatch/MainActivity.java +++ b/art-fieldwatch-phase1/test/app/src/main/java/com/example/artfieldwatch/MainActivity.java @@ -69,6 +69,10 @@ protected void onCreate(Bundle state) { 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; } Log.i("ARTWATCH_CI","WARMUP_DONE checksum=" + accumulator); } catch (Throwable t) { 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; + } +} From f4d18d2fdb76a55b2238be7d438b546d0c4e4e8d Mon Sep 17 00:00:00 2001 From: Muhtasham Nawr al-Mahmud <72372229+mnalmahmud@users.noreply.github.com> Date: Mon, 23 Nov 2026 16:29:54 +0600 Subject: [PATCH 122/129] feat(fieldwatch): add executable ART JVMTI no-template field access watcher --- .../native/jvmti-fieldwatch.cc | 190 ++++++++++++++++++ 1 file changed, 190 insertions(+) create mode 100644 art-fieldwatch-phase1/native/jvmti-fieldwatch.cc diff --git a/art-fieldwatch-phase1/native/jvmti-fieldwatch.cc b/art-fieldwatch-phase1/native/jvmti-fieldwatch.cc new file mode 100644 index 0000000..9b4d665 --- /dev/null +++ b/art-fieldwatch-phase1/native/jvmti-fieldwatch.cc @@ -0,0 +1,190 @@ +// 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. + 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: return; + } + if (env->ExceptionCheck()) {env->ExceptionClear();return;} + 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; +} From 00ae3418d24c8f1965ab7e5316c75729831754e1 Mon Sep 17 00:00:00 2001 From: Muhtasham Nawr al-Mahmud <72372229+mnalmahmud@users.noreply.github.com> Date: Mon, 23 Nov 2026 16:30:36 +0600 Subject: [PATCH 123/129] fix(jvmti): avoid recursive field callbacks when sampling primitive reads --- art-fieldwatch-phase1/native/jvmti-fieldwatch.cc | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/art-fieldwatch-phase1/native/jvmti-fieldwatch.cc b/art-fieldwatch-phase1/native/jvmti-fieldwatch.cc index 9b4d665..4c16dbd 100644 --- a/art-fieldwatch-phase1/native/jvmti-fieldwatch.cc +++ b/art-fieldwatch-phase1/native/jvmti-fieldwatch.cc @@ -85,6 +85,8 @@ void JNICALL OnRead(jvmtiEnv* ti,JNIEnv* env,jthread,jmethodID method,jlocation 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': @@ -96,9 +98,10 @@ void JNICALL OnRead(jvmtiEnv* ti,JNIEnv* env,jthread,jmethodID method,jlocation case 'Z': value.z=object?env->GetBooleanField(object,field):env->GetStaticBooleanField(klass,field); break; - default: return; + default: in_callback=false;return; } - if (env->ExceptionCheck()) {env->ExceptionClear();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) { From 5da7d17ab1c9f81c940443bf71b590fc9535dd08 Mon Sep 17 00:00:00 2001 From: Muhtasham Nawr al-Mahmud <72372229+mnalmahmud@users.noreply.github.com> Date: Mon, 23 Nov 2026 16:31:22 +0600 Subject: [PATCH 124/129] build(jvmti): compile and package API33 x86_64 ART fieldwatch agent --- art-fieldwatch-phase1/ci/build-passive-shim.sh | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/art-fieldwatch-phase1/ci/build-passive-shim.sh b/art-fieldwatch-phase1/ci/build-passive-shim.sh index 0bf9aa4..5a2caee 100644 --- a/art-fieldwatch-phase1/ci/build-passive-shim.sh +++ b/art-fieldwatch-phase1/ci/build-passive-shim.sh @@ -38,3 +38,18 @@ readelf -Ws "$out/libartwatch_events.so" | 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 "$JAVA_HOME/include" \ + 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" From 701d5cb9ee1d0fccf67d923f4d04fa85efc9ab11 Mon Sep 17 00:00:00 2001 From: Muhtasham Nawr al-Mahmud <72372229+mnalmahmud@users.noreply.github.com> Date: Mon, 23 Nov 2026 16:31:52 +0600 Subject: [PATCH 125/129] test(jvmti): attach ART field watcher and exercise sink-free instance/static operations --- .github/workflows/art-fieldwatch-phase1.yml | 1 + art-fieldwatch-phase1/jit-boundary-probe.js | 10 ++++++++++ .../example/artfieldwatch/JvmtiTarget.java | 20 +++++++++++++++++++ .../example/artfieldwatch/MainActivity.java | 15 ++++++++++++++ 4 files changed, 46 insertions(+) create mode 100644 art-fieldwatch-phase1/test/app/src/main/java/com/example/artfieldwatch/JvmtiTarget.java diff --git a/.github/workflows/art-fieldwatch-phase1.yml b/.github/workflows/art-fieldwatch-phase1.yml index f8f405b..64d34f6 100644 --- a/.github/workflows/art-fieldwatch-phase1.yml +++ b/.github/workflows/art-fieldwatch-phase1.yml @@ -118,6 +118,7 @@ jobs: 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' diff --git a/art-fieldwatch-phase1/jit-boundary-probe.js b/art-fieldwatch-phase1/jit-boundary-probe.js index fbc8602..6897685 100644 --- a/art-fieldwatch-phase1/jit-boundary-probe.js +++ b/art-fieldwatch-phase1/jit-boundary-probe.js @@ -1562,6 +1562,16 @@ function main() { // 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'}; 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 Date: Mon, 23 Nov 2026 16:33:38 +0600 Subject: [PATCH 127/129] fix(jvmti): prioritize Android NDK JNI headers over host JDK JNI --- art-fieldwatch-phase1/ci/build-passive-shim.sh | 1 + 1 file changed, 1 insertion(+) diff --git a/art-fieldwatch-phase1/ci/build-passive-shim.sh b/art-fieldwatch-phase1/ci/build-passive-shim.sh index 5a2caee..e5f65c2 100644 --- a/art-fieldwatch-phase1/ci/build-passive-shim.sh +++ b/art-fieldwatch-phase1/ci/build-passive-shim.sh @@ -45,6 +45,7 @@ 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" \ art-fieldwatch-phase1/native/jvmti-fieldwatch.cc -llog \ -o "$out/libartwatch_jvmti.so" From 20c107ad97c20ed7f29672719f1f13d89b7bcbfa Mon Sep 17 00:00:00 2001 From: Muhtasham Nawr al-Mahmud <72372229+mnalmahmud@users.noreply.github.com> Date: Mon, 23 Nov 2026 16:34:58 +0600 Subject: [PATCH 128/129] fix(jvmti): supply matching JNI platform typedef header for JDK JVMTI ABI --- art-fieldwatch-phase1/ci/build-passive-shim.sh | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/art-fieldwatch-phase1/ci/build-passive-shim.sh b/art-fieldwatch-phase1/ci/build-passive-shim.sh index e5f65c2..1baa897 100644 --- a/art-fieldwatch-phase1/ci/build-passive-shim.sh +++ b/art-fieldwatch-phase1/ci/build-passive-shim.sh @@ -46,7 +46,7 @@ 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" -I "$JAVA_HOME/include/linux" \ art-fieldwatch-phase1/native/jvmti-fieldwatch.cc -llog \ -o "$out/libartwatch_jvmti.so" readelf -Ws "$out/libartwatch_jvmti.so" | From 62c6400191dca7dcc8dafb761f47b395ada86d48 Mon Sep 17 00:00:00 2001 From: Muhtasham Nawr al-Mahmud <72372229+mnalmahmud@users.noreply.github.com> Date: Mon, 23 Nov 2026 16:40:21 +0600 Subject: [PATCH 129/129] fix(jvmti): use classloader library name to avoid base64 '=' APK path rejection --- .../src/main/java/com/example/artfieldwatch/MainActivity.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/art-fieldwatch-phase1/test/app/src/main/java/com/example/artfieldwatch/MainActivity.java b/art-fieldwatch-phase1/test/app/src/main/java/com/example/artfieldwatch/MainActivity.java index cbc1b5e..1e22eb5 100644 --- a/art-fieldwatch-phase1/test/app/src/main/java/com/example/artfieldwatch/MainActivity.java +++ b/art-fieldwatch-phase1/test/app/src/main/java/com/example/artfieldwatch/MainActivity.java @@ -26,7 +26,7 @@ protected void onCreate(Bundle state) { if (appDebuggable) { try { android.os.Debug.attachJvmtiAgent( - getApplicationInfo().nativeLibraryDir + "/libartwatch_jvmti.so", + "libartwatch_jvmti.so", "Lcom/example/artfieldwatch/JvmtiTarget;", getClassLoader()); Log.i("ARTWATCH_CI","JVMTI_ATTACH=true"); } catch (Throwable failure) {