245 lines
18 KiB
Python
245 lines
18 KiB
Python
#!/usr/bin/env python3
|
|
"""Finite replay of production loader/View/renderer callbacks over exact APK bytes.
|
|
Android EGL/codec/music/record confirmations are doubles; no device or sockets.
|
|
"""
|
|
from pathlib import Path
|
|
import ast,subprocess,tempfile,json,hashlib
|
|
import argparse, zipfile
|
|
parser=argparse.ArgumentParser(description=__doc__)
|
|
parser.add_argument('--apk',type=Path,required=True)
|
|
parser.add_argument('--sha256',required=True)
|
|
parser.add_argument('--startup-loader',action='store_true',help='Production background repository over actual APK bytes, isolated private receipt, no rendering/connection')
|
|
parser.add_argument('--user-asset-candidate',action='store_true',help='Exact user-authorized correct03 APK; this offline replay uses local media callback doubles and does not assert network admission')
|
|
args=parser.parse_args()
|
|
assert hashlib.sha256(args.apk.read_bytes()).hexdigest()==args.sha256, 'APK hash drift'
|
|
ROOT=Path(__file__).resolve().parents[1];script=ROOT/'scripts/check-reply-regressions.py'
|
|
tree=ast.parse(script.read_text());nodes=[]
|
|
for node in tree.body:
|
|
if isinstance(node,ast.Assign) and any(isinstance(t,ast.Name) and t.id=='parser' for t in node.targets):break
|
|
nodes.append(node)
|
|
ns={'__file__':str(script)};exec(compile(ast.Module(body=nodes,type_ignores=[]),str(script),'exec'),ns)
|
|
java,compiler,cp=ns['JAVA'],ns['compiler'],ns['cp'];real=next(x[2] for x in ns['suites'] if x[0]=='avatar')
|
|
json_adapter=r'''
|
|
package org.json
|
|
private fun wrap(v: Any?): Any? = when(v) { is Map<*,*> -> JSONObject(v as Map<String,Any?>); is List<*> -> JSONArray(v); null -> JSONObject.NULL;else ->v }
|
|
class JSONObject(private val map: Map<String,Any?>) {
|
|
constructor(raw: String):this(Parser(raw).value() as Map<String,Any?>)
|
|
fun keys()=map.keys.iterator()
|
|
fun get(k: String): Any? = wrap(map.getValue(k))
|
|
fun getString(k: String)=map.getValue(k) as String
|
|
fun getJSONObject(k: String)=JSONObject(map.getValue(k) as Map<String,Any?>)
|
|
fun getLong(k: String)=(map.getValue(k) as Number).toLong()
|
|
fun getInt(k: String)=(map.getValue(k) as Number).toInt()
|
|
fun getBoolean(k: String)=map.getValue(k) as Boolean
|
|
fun getJSONArray(k: String)=JSONArray(map.getValue(k) as List<*>)
|
|
companion object { val NULL=Any() }
|
|
}
|
|
class JSONArray(private val values: List<*>) {
|
|
fun length()=values.size
|
|
fun get(i: Int): Any? =wrap(values[i])
|
|
fun getJSONObject(i: Int)=get(i) as JSONObject
|
|
fun getLong(i: Int)=(values[i] as Number).toLong()
|
|
}
|
|
private class Parser(val s: String) {
|
|
var i=0
|
|
fun space() { while(i<s.length && s[i].isWhitespace()) i++ }
|
|
fun value(): Any? {
|
|
space()
|
|
return when(s[i]) {
|
|
'{' -> { i++;space();val m=linkedMapOf<String,Any?>();if(s[i]!='}') while(true) { val k=value() as String;space();check(s[i++]==':');m[k]=value();space();if(s[i]!=',')break;i++ };check(s[i++]=='}');m }
|
|
'[' -> { i++;space();val a=mutableListOf<Any?>();if(s[i]!=']')while(true) { a.add(value());space();if(s[i]!=',')break;i++ };check(s[i++]==']');a }
|
|
'"' -> { i++;val b=StringBuilder();while(s[i]!='"') { var c=s[i++];if(c=='\\') { c=s[i++];c=when(c) { 'n'->'\n';'r'->'\r';'t'->'\t';'b'->'\b';'f'->'\u000c';'u'->{ val x=s.substring(i,i+4).toInt(16).toChar();i+=4;x };else->c } };b.append(c) };i++;b.toString() }
|
|
't' -> {check(s.substring(i,i+4)=="true");i+=4;true}
|
|
'f' -> {check(s.substring(i,i+5)=="false");i+=5;false}
|
|
'n' -> {check(s.substring(i,i+4)=="null");i+=4;null}
|
|
else -> { val start=i;while(i<s.length && s[i] in "-+0123456789.eE")i++;val n=s.substring(start,i);if(n.any { it in ".eE" })n.toDouble() else n.toIntOrNull() ?: n.toLong() }
|
|
}
|
|
}
|
|
}
|
|
'''
|
|
context=r'''
|
|
package android.content
|
|
class Context {
|
|
val assets = Assets();val applicationContext get()=this;val packageName="com.gorios.lanvoice"
|
|
val packageManager=PackageManager();val filesDir get()=Archive.privateDir
|
|
}
|
|
class PackageManager { fun getPackageInfo(name: String,flags: Int)=PackageInfo() }
|
|
class PackageInfo { val versionCode=22;val lastUpdateTime=123456L }
|
|
class Assets {
|
|
fun open(path: String): java.io.InputStream {
|
|
if(Archive.requireWorker) check(Thread.currentThread()!==Archive.owner) { "asset_read_on_main" }
|
|
synchronized(Archive.reads) {Archive.reads.add(path)}
|
|
return java.io.ByteArrayInputStream(Archive.zip.getInputStream(checkNotNull(Archive.zip.getEntry("assets/"+path)) { "missing_asset" }).use { it.readBytes() })
|
|
}
|
|
fun openFd(path: String) = Descriptor(path)
|
|
}
|
|
object Archive { lateinit var zip: java.util.zip.ZipFile;lateinit var privateDir: java.io.File;var requireWorker=false;val owner=Thread.currentThread();val reads=mutableListOf<String>() }
|
|
object AssetFixture { val paths=mutableMapOf<java.io.FileDescriptor,String>() }
|
|
class Descriptor(path: String="") : java.io.Closeable {
|
|
val fileDescriptor=java.io.FileDescriptor();val startOffset=0L;val length=20L
|
|
init { AssetFixture.paths[fileDescriptor]=path };override fun close() {}
|
|
}
|
|
'''
|
|
graphics=(ROOT/'tests/avatar/Graphics.kt').read_text();graphics=graphics.replace(' fun decodeStream(input: java.io.InputStream): Bitmap = Bitmap(if(wrongSize) 41 else 40,22)',r'''
|
|
class Options { var inJustDecodeBounds=false;var outWidth=0;var outHeight=0 }
|
|
fun decodeStream(input: java.io.InputStream): Bitmap { val image=javax.imageio.ImageIO.read(input);return Bitmap(image.width,image.height) }
|
|
fun decodeByteArray(bytes: ByteArray,offset: Int,length: Int,options: Options): Bitmap? {
|
|
val input=java.io.ByteArrayInputStream(bytes,offset,length);val image=javax.imageio.ImageIO.read(input)
|
|
options.outWidth=image.width;options.outHeight=image.height
|
|
return if(options.inJustDecodeBounds) null else Bitmap(image.width,image.height)
|
|
}
|
|
''')
|
|
build='''package com.gorios.lanvoice
|
|
object BuildConfig { const val AVATAR_STARTUP_FIX=false;const val DEBUG=true;const val AVATAR_NATURAL=true;const val AVATAR_ENGINEERING=true;const val AVATAR_MOUTH_CANDIDATE=true
|
|
const val EMOTION_MANIFEST_SHA="987e125a7d7a2cde99121b5f5246c82f4dbe36c4899d3d49eaffd1a68bafb887"
|
|
const val NATURAL_MANIFEST_SHA="0a3c4918ba746019cf1df885bec66e5858a8950997dac4f64e7d37094be64dad"
|
|
}'''
|
|
if args.user_asset_candidate:
|
|
import importlib.util
|
|
spec=importlib.util.spec_from_file_location('user_startup',ROOT/'scripts/prepare-user-avatar-startup.py');asset_config=importlib.util.module_from_spec(spec);spec.loader.exec_module(asset_config)
|
|
with zipfile.ZipFile(args.apk) as archive:
|
|
raw=archive.read('assets/'+asset_config.ASSET_ROOT+'manifest.json');assert hashlib.sha256(raw).hexdigest()==asset_config.PIN
|
|
index=json.loads(raw);refs=[p['runtimeManifest'] for p in index['conversationPackages']]+[e['mouthRuntimeManifest'] for e in index['edges'] if 'mouthRuntimeManifest' in e]
|
|
patch_count=sum(len(json.loads(archive.read('assets/'+asset_config.ASSET_ROOT+r['path']))['patches'])*5 for r in refs)
|
|
build=build.replace('const val EMOTION_MANIFEST_SHA="987e125a7d7a2cde99121b5f5246c82f4dbe36c4899d3d49eaffd1a68bafb887"','const val EMOTION_MANIFEST_SHA="'+asset_config.PIN+'"')
|
|
build=build.replace('const val AVATAR_STARTUP_FIX=false','const val AVATAR_STARTUP_FIX=true')
|
|
build=build.replace('object BuildConfig {','object BuildConfig { const val AVATAR_USER_ASSET_CANDIDATE=true;const val EMOTION_ASSET_ROOT="'+asset_config.ASSET_ROOT+'";const val STARTUP_ASSET_ROOT="'+asset_config.BASIC_ROOT+'";const val STARTUP_MANIFEST_SHA="'+hashlib.sha256((ROOT/'manifests/startup-black-tulle-correct03.json').read_bytes()).hexdigest()+'";')
|
|
else:
|
|
patch_count=3185
|
|
build=build.replace('object BuildConfig {','object BuildConfig { const val AVATAR_USER_ASSET_CANDIDATE=false;const val EMOTION_ASSET_ROOT="avatar/a01-expression-action-v1/";const val STARTUP_ASSET_ROOT="avatar/startup-white-01/";const val STARTUP_MANIFEST_SHA="461f5cfc10036de5f10ca3ce765fb8d9998697d3fd035aa9b1862d2ccfc3eaa2";')
|
|
main=r'''
|
|
import com.gorios.lanvoice.avatar.*
|
|
import com.gorios.lanvoice.dialogue.*
|
|
import android.os.TestScheduler
|
|
import android.media.CodecFixture
|
|
import android.media.MediaPlayer
|
|
import android.graphics.SurfaceTexture
|
|
import android.view.TextureView
|
|
fun main(args: Array<String>) {
|
|
android.content.Archive.zip=java.util.zip.ZipFile(args.single())
|
|
val context=android.content.Context();val pack=checkNotNull(AvatarPack.load(context))
|
|
println("LOADER|status=${pack.motionStatus}|full=${pack.emotionAction!=null}|actions=${pack.emotionAction?.actionPack?.assets?.size}")
|
|
val index=checkNotNull(pack.emotionAction)
|
|
fun rig(): Triple<EmotionActionAvatarView,AvatarMediaBinding,MutableList<Pair<Long,VideoPresentation>>> {
|
|
TestScheduler.reset();CodecFixture.reset();CodecFixture.width=pack.continuous!!.body.width;CodecFixture.height=pack.continuous!!.body.height;MediaPlayer.created.clear();CodecFixture.emitNativeSurface=true
|
|
index.packages.values.forEach { CodecFixture.timelines[it.root+it.body.path]=it.body.ptsUs }
|
|
index.edges.mapNotNull { it.mouthRuntime }.forEach { CodecFixture.timelines[it.root+it.body.path]=it.body.ptsUs }
|
|
index.actionPack?.assets?.mapNotNull { it.media }?.forEach { CodecFixture.timelines[it.root+it.path]=it.ptsUs;CodecFixture.audioPaths.add(it.root+it.path) }
|
|
val binding=AvatarMediaBinding();binding.beginTurn(7)
|
|
val trace=mutableListOf<Pair<Long,VideoPresentation>>()
|
|
val view=EmotionActionAvatarView(context,pack,binding,{ trace.add(TestScheduler.now to it) })
|
|
view.render(true);TestScheduler.advanceBy(1);return Triple(view,binding,trace)
|
|
}
|
|
fun printTrace(case: String,trace: List<Pair<Long,VideoPresentation>>) {
|
|
var old="";for((ms,v) in trace)if(v.actual!=old) { println("FRAME|case=$case|ms=$ms|actual=${v.actual}|cursor=${v.clipId}|reason=${v.reason}");old=v.actual }
|
|
}
|
|
run {
|
|
val(view,binding,trace)=rig();TestScheduler.advanceBy(30_000)
|
|
printTrace("idle30s",trace);println("IDLE|current=${binding.currentPackageId}|visual=${binding.visualStatus}")
|
|
check(trace.none { it.second.actual=="media_failed" });check(trace.any { it.second.actual.startsWith("body_idle-") })
|
|
TestScheduler.until(15_000) { binding.currentPackageId?.startsWith("idle-")==true }
|
|
val parked=checkNotNull(binding.currentPackageId);val startRows=trace.size
|
|
binding.beginTurn(8);binding.intent(null,false);TestScheduler.advanceBy(30_000)
|
|
val changed=trace.drop(startRows).any { it.second.actual=="bridge" || it.second.actual.startsWith("idle_variant_") }
|
|
println("IDLE_NEWTURN|parked=$parked|after30s=${binding.currentPackageId}|routed=$changed|status=${binding.visualStatus}")
|
|
check(changed)
|
|
check(trace.drop(startRows).any { it.second.actual=="body_neutral-01" })
|
|
for(wanted in listOf("idle-breathe-01","idle-microshift-01")) {
|
|
// Begin at a genuine fresh entry, not an arbitrary late frame of an already
|
|
// visible variant. Legal return may otherwise occur during the next700ms.
|
|
TestScheduler.until(70_000) { binding.currentPackageId==wanted && trace.lastOrNull()?.second?.clipId=="f0_loop0" }
|
|
val start=trace.size
|
|
repeat(5) { i -> binding.beginTurn(10L+i);binding.intent(null,false);TestScheduler.advanceBy(100) }
|
|
binding.prepare(mediaReply(RoleEmotion.HAPPY,turn=14,seq=1))
|
|
binding.intent(mediaReply(RoleEmotion.NEUTRAL,turn=14,seq=2),true)
|
|
TestScheduler.advanceBy(200);check(binding.currentPackageId==wanted)
|
|
binding.intent(null,false)
|
|
TestScheduler.advanceBy(30_000)
|
|
val returned=trace.drop(start).any { it.second.actual=="body_neutral-01" }
|
|
check(returned && trace.drop(start).any { it.second.actual=="bridge" })
|
|
println("IDLE_NEWTURN|parked=$wanted|turns=5|legal_return=$returned|after30s=${binding.currentPackageId}")
|
|
}
|
|
view.dispose();TestScheduler.advanceBy(100)
|
|
}
|
|
run {
|
|
val(view,binding,trace)=rig()
|
|
binding.prepare(mediaReply(RoleEmotion.HAPPY,seq=1));TestScheduler.advanceBy(500)
|
|
println("EMOTION|prepare_only|current=${binding.currentPackageId}|visual=${binding.visualStatus}")
|
|
binding.intent(mediaReply(RoleEmotion.HAPPY,seq=2),true);TestScheduler.advanceBy(1000)
|
|
binding.intent(null,false) // Same MainActivity path when short reply drained.
|
|
TestScheduler.advanceBy(6000)
|
|
println("EMOTION|requested=happy1|current=${binding.currentPackageId}|visual=${binding.visualStatus}")
|
|
binding.intent(mediaReply(RoleEmotion.SAD,seq=3),true);TestScheduler.advanceBy(1500);binding.intent(null,false);TestScheduler.advanceBy(7000)
|
|
println("EMOTION|requested=sad1|current=${binding.currentPackageId}|visual=${binding.visualStatus}")
|
|
printTrace("happy_sad",trace);check(trace.none { it.second.actual=="media_failed" });check(binding.currentPackageId=="sad-01");view.dispose();TestScheduler.advanceBy(100)
|
|
}
|
|
for(initial in listOf(RoleEmotion.NEUTRAL,RoleEmotion.HAPPY)) {
|
|
val(view,binding,trace)=rig();binding.intent(mediaReply(initial),false);TestScheduler.advanceBy(6000)
|
|
var stop: ((Boolean)->Unit)?=null;val statuses=mutableListOf<ActionStatus>()
|
|
val controller=ActionController(index.actionPack,binding,{TestScheduler.now},{stop=it},statuses::add,choose={0})
|
|
check(controller.offer(ActionPlan("public_fixture_action_id_001",7,index.actionPack!!.manifestSha,120000)))
|
|
println("DANCE|initial=${initial.wire}|offered=true|before_stop_players=${MediaPlayer.created.size}")
|
|
stop!!(true);MediaPlayer.created.single().let { it.prepared!!(it) };TestScheduler.until(15000) { MediaPlayer.created.any { it.started } || trace.any { it.second.actual=="media_failed" } }
|
|
val movie=MediaPlayer.created.single();println("DANCE|started=${movie.started}|current=${binding.currentPackageId}|status=${statuses.last().status}")
|
|
val field=view.javaClass.getDeclaredField("textures").apply { isAccessible=true };val textures=field.get(view) as List<TextureView>
|
|
val listener=textures[3].surfaceTextureListener!!;val surface=textures[3].surfaceTexture!!
|
|
index.actionPack.assets.first().media!!.ptsUs.forEachIndexed { i,pts ->
|
|
if(i>0) TestScheduler.advanceBy(42);surface.timestamp=pts*1000;listener.onSurfaceTextureUpdated(surface)
|
|
if(i==0) {
|
|
println("DANCE_LAYER|initial=${initial.wire}|first_frame_alpha=${textures[3].alpha}|body_alpha=${textures.take(3).map { it.alpha }}")
|
|
TestScheduler.advanceBy(21)
|
|
println("DANCE_LAYER|initial=${initial.wire}|after_21ms_alpha=${textures[3].alpha}|body_alpha=${textures.take(3).map { it.alpha }}|movie_started=${movie.started}|phase=${binding.visualStatus}")
|
|
check(movie.started && textures[3].alpha==1f && textures.take(3).all { it.alpha==0f })
|
|
}
|
|
check(textures[3].alpha==1f && textures.take(3).all { it.alpha==0f })
|
|
}
|
|
println("DANCE_OWNER|initial=${initial.wire}|frames=${index.actionPack.assets.first().media!!.ptsUs.size}|music_visible=${index.actionPack.assets.first().media!!.ptsUs.size}|conversation_visible=0|state=${binding.diagnosticState}")
|
|
TestScheduler.advanceBy(50);movie.completion!!(movie);TestScheduler.until(15000) { statuses.last().status!="started" }
|
|
println("DANCE|ended=${statuses.last().status}|released=${movie.released}|return=${binding.currentPackageId}")
|
|
printTrace("dance_${initial.wire}",trace);check(statuses.last().status=="completed");check(binding.currentPackageId=="neutral-01");view.dispose();TestScheduler.advanceBy(100)
|
|
}
|
|
println("HOST_REPLAY|fix_verified=true|dance_layer_retained=true|idle_newturn_legal_return=true|native_device=false|surface_availability_mock=true|record_stop_mock=true|json_adapter=host")
|
|
}
|
|
'''
|
|
startup_main=r'''
|
|
import com.gorios.lanvoice.avatar.*
|
|
import android.os.TestScheduler
|
|
fun main(args: Array<String>) {
|
|
android.content.Archive.zip=java.util.zip.ZipFile(args[0]);android.content.Archive.privateDir=java.io.File(args[1])
|
|
android.os.Looper.getMainLooper();android.content.Archive.requireWorker=true
|
|
val context=android.content.Context();var base: ContinuousAvatarPack?=null;var pack: AvatarPack?=null
|
|
fun waitReady() {
|
|
val deadline=System.nanoTime()+40_000_000_000L
|
|
while(pack==null || base==null) { TestScheduler.advanceBy(0);check(System.nanoTime()<deadline);Thread.sleep(1) }
|
|
}
|
|
StartupAvatarRepository.request(context,{base=it},{pack=it.getOrThrow()});waitReady()
|
|
check(base!!.body.frameCount==97 && base!!.patches.isEmpty() && base!!.curves.isEmpty())
|
|
check(pack!!.emotionAdmission=="accepted" && pack!!.emotionAction!!.packages.size==5)
|
|
val patchReads=android.content.Archive.reads.count { it.contains("/patches/") }
|
|
check(patchReads==if(args[2]=="cold") 3185 else 0)
|
|
val count=android.content.Archive.reads.size;val original=pack;base=null;pack=null
|
|
StartupAvatarRepository.request(context,{base=it},{pack=it.getOrThrow()});waitReady()
|
|
check(pack===original && android.content.Archive.reads.size==count)
|
|
println("STARTUP_REPOSITORY|mode=${args[2]}|main_asset_reads=0|patch_reads=$patchReads|same_process_reloads=0|packages=5|bridge_mouths=8|sensors=0|device=false")
|
|
}
|
|
'''
|
|
with tempfile.TemporaryDirectory(prefix='baji-runtime-audit-') as td:
|
|
tmp=Path(td);files=[]
|
|
for path in (ROOT/'tests/avatar').glob('*.kt'):
|
|
if path.name not in ('Pack.kt','Context.kt','Graphics.kt','BuildConfig.kt') and not(args.startup_loader and path.name=='Clock.kt'):files.append(path)
|
|
if args.startup_loader:
|
|
clock=(ROOT/'tests/avatar/Clock.kt').read_text().replace('fun getMainLooper() = main','private val owner=Thread.currentThread();fun myLooper(): Looper?=if(Thread.currentThread()===owner) main else null;fun getMainLooper() = main')
|
|
clock=clock.replace(' fun add(', ' @Synchronized fun add(').replace(' fun remove(', ' @Synchronized fun remove(').replace(' fun advanceBy(', ' @Synchronized fun advanceBy(')
|
|
p=tmp/'Clock.kt';p.write_text(clock);files.append(p)
|
|
startup_main=startup_main.replace("3185",str(patch_count))
|
|
for name,txt in [('Json.kt',json_adapter),('Context.kt',context),('Graphics.kt',graphics),('BuildConfig.kt',build),('Audit.kt',startup_main if args.startup_loader else main)]:
|
|
p=tmp/name;p.write_text(txt);files.append(p)
|
|
files+=real+[ROOT/'app/src/main/java/com/gorios/lanvoice'/p for p in ('avatar/AvatarPack.kt','avatar/StartupAvatarView.kt','avatar/StartupLoadCache.kt','diag/StartupTrace.kt')]
|
|
if args.startup_loader: files.append(ROOT/'app/src/main/java/com/gorios/lanvoice/avatar/StartupAvatarRepository.kt')
|
|
subprocess.run([java,'-cp',compiler,'org.jetbrains.kotlin.cli.jvm.K2JVMCompiler','-no-stdlib','-no-reflect','-jvm-target','17','-nowarn','-classpath',cp,'-d',str(tmp),*map(str,files)],check=True)
|
|
if args.startup_loader:
|
|
receipt=tmp/'private';receipt.mkdir()
|
|
for mode in ('cold','receipt'):
|
|
subprocess.run([java,'-cp',str(tmp)+':'+cp,'AuditKt',str(args.apk.resolve()),str(receipt),mode],check=True,timeout=45)
|
|
else: subprocess.run([java,'-cp',str(tmp)+':'+cp,'AuditKt',str(args.apk.resolve())],check=True,timeout=45)
|