// K2160 two-process, one-QEMU-at-a-time collector. It does not grant admission. // The writer must exit through guest PSCI SYSTEM_OFF before any reader starts. import assert from 'node:assert/strict'; import {createConnection} from 'node:net'; import {spawn,spawnSync} from 'node:child_process'; import {randomBytes} from 'node:crypto'; import {copyFileSync,mkdirSync,mkdtempSync,readFileSync,rmSync,statfsSync,writeFileSync} from 'node:fs'; import {join,relative,resolve} from 'node:path'; import {tmpdir} from 'node:os'; import {setTimeout as delay} from 'node:timers/promises'; import {hashAt,frozenSnapshot} from './boot-contract-report.mjs'; import {qmpConnect} from './paused-capture-qmp.mjs'; import {dmaGdbConnect} from './dma-gdb.mjs'; import {dmaNetworkConnect,dmaPacket} from './dma-network.mjs'; import {beforeDisk,expectedAfter,readerDisk,CASES,checkedIdentity} from './k2160-fixture.mjs'; import {checkReopenDiskPair} from './features/k2160-disk-check.mjs'; import {collectReopenPhysical,reopenStages,checkReopenStageOrder,readOnlyImageSpans} from './features/k2160-capture.mjs'; import {checkReopenGuestPhysical} from './features/k2160-physical-check.mjs'; export const PROFILES=Object.freeze(['direct','uefi'].flatMap(route=>[256,512,1024].flatMap(memoryMiB=>[1,2,4].map(cpuCount=> Object.freeze({id:`${route}-${memoryMiB}-cpu-${cpuCount}`,route,memoryMiB,cpuCount}))))); const DEFERRED_MODES=['diag','platform','metadata','dma','page-fault','exceptions','gic','threads']; const root=process.cwd(),read=p=>JSON.parse(readFileSync(p,'utf8')); const artifact=p=>({path:relative(root,p),sha256:hashAt(root,relative(root,p))}); const json=(p,v)=>writeFileSync(p,JSON.stringify(v,null,2)+'\n'); const bootValue=()=>{let n;do{n=randomBytes(8).readBigUInt64BE()}while(n===0n);return n;}; const hex64=n=>n.toString(16).padStart(16,'0'); const words64=n=>[Number((n>>32n)&0xffffffffn),Number(n&0xffffffffn)]; const assertStatus=(status,wanted)=>assert.equal(status,wanted,`QMP state: expected ${wanted}`); function command(log,executable,args,env=process.env){ const r=spawnSync(executable,args,{cwd:root,env,encoding:'utf8',timeout:900000,maxBuffer:64*1024*1024}); writeFileSync(log,`$ ${executable} ${args.join(' ')}\n${r.stdout??''}${r.stderr??''}`); assert.ifError(r.error);assert.equal(r.status,0,`${executable} failed: ${relative(root,log)}`);return r.stdout; } function symbolsOf(path){ const symbols={};for(const line of readFileSync(path,'utf8').split('\n')){ const m=line.match(/^([a-f0-9]{16}) (?:([a-f0-9]{16}) )?[A-Za-z] (\S+)$/); if(m)symbols[m[3]]={address:Number.parseInt(m[1],16),size:m[2]?Number.parseInt(m[2],16):0}; }return symbols; } function qemuRunning(){const r=spawnSync('ps',['-axo','comm'],{encoding:'utf8'});assert.equal(r.status,0);return r.stdout.split('\n').some(l=>l.trim().endsWith('qemu-system-aarch64'));} export function selectedProfiles(value){ const ids=value==='all'?PROFILES.map(p=>p.id):value==='smoke'?['direct-256-cpu-1']:value.split(',').filter(Boolean); assert.equal(new Set(ids).size,ids.length,'duplicate profile');assert.ok(ids.length>0); return ids.map(id=>{const p=PROFILES.find(row=>row.id===id);assert.ok(p,`unknown profile ${id}`);return p;}); } export function selectedCases(value){ assert.ok(value==='all'||/^[0-4](,[0-4])*$/.test(value),'case list syntax'); const ids=value==='all'?CASES.map(c=>c.id):value.split(',').map(Number); assert.ok(ids.length>0&&ids.length<=CASES.length);assert.equal(new Set(ids).size,ids.length,'duplicate case'); for(const id of ids)assert.ok(CASES.some(c=>c.id===id),`unknown case ${id}`);return ids; } export function guestShutdownEvidence(transcript,exit,serial,phase,caseId,bootId){ const events=transcript.filter(row=>row.direction==='rx'&&row.message?.event==='SHUTDOWN'); assert.equal(events.length,1,'exactly one QMP SHUTDOWN'); const shutdown=events[0].message.data; assert.equal(shutdown?.guest,true,'guest-originated shutdown');assert.equal(shutdown?.reason,'guest-shutdown'); assert.ok(!transcript.some(row=>row.direction==='tx'&&['quit','system_powerdown'].includes(row.message?.execute)),'host shutdown'); assert.deepEqual(exit,{code:0,signal:null},'QEMU normal exit'); const marker=`TURKOS/OS/K2160: GUEST-SYSTEM-OFF PHASE=0x${BigInt(phase).toString(16).padStart(16,'0')} CASE=0x${BigInt(caseId).toString(16).padStart(16,'0')} BOOT=0x${bootId.toString(16).padStart(16,'0')} FREE_EQUAL=0x0000000000000001`; assert.ok(serial.includes(marker),'guest did not announce SYSTEM_OFF with expected identity'); assert.ok(!/TURKOS\/OS\/K2160: NATIVE-FAILED|PANIC|TURKOS\/FATAL/.test(serial),'guest failed'); return shutdown; } function freeBytes(path){const s=statfsSync(path);return Number(s.bavail)*Number(s.bsize);} export async function main(){ assert.equal(process.argv.length,3,'usage: node k2160-reopen-guest-runner.mjs '); const candidatePath=resolve(process.argv[2]),candidate=read(candidatePath); assert.equal(candidate.schema,'turkos-feature-candidate/v1');assert.equal(candidate.status,'COMPILED_FEATURE_CANDIDATE'); assert.equal(candidate.milestone,'K2160');assert.equal(candidate.slug,'shutdown-native-reopen'); assert.equal(candidate.experiment,2160);assert.equal(candidate.guestAccepted,false); assert.equal(hashAt(root,candidate.spec.path),candidate.spec.sha256); for(const item of Object.values(candidate.artifacts))assert.equal(hashAt(root,item.path),item.sha256,item.path); const spec=read(join(root,candidate.spec.path));assert.equal(spec.prototypeOnly,true);assert.equal(spec.guestAdmissionEnabled,false); const profiles=selectedProfiles(process.env.FX_PROFILES??'smoke'); const cases=selectedCases(process.env.FX_REOPEN_CASES??'all'); assert.ok(cases.includes(0),'matched reader must be included'); const progress=read(join(root,'reports/os-implementation/progress.json')); for(const id of ['K2100','K2155']){ const move=progress.moves.find(row=>row.id===id); assert.equal(move?.status,'DEVELOPMENT_GUEST_ACCEPTED',`${id} guest prerequisite remains open`); } assert.ok(!qemuRunning(),'ARM64 QEMU lane occupied'); // Each profile can create more than 100 MiB of capture evidence. Keep a // conservative reserve while the independent K2100 lane is still active. assert.ok(freeBytes(root)>=20*1024**3,'less than 20 GiB free; no guest launch'); const dir=mkdtempSync(join(root,'reports/os-implementation/K2160-shutdown-native-reopen-matrix-')); const lifecycle={schema:'turkos-k2160-two-boot-lifecycle/v1',status:'RUNNING',startedAt:new Date().toISOString(), candidate:artifact(candidatePath),selection:profiles.map(p=>p.id),cases,guestAccepted:false,productAccepted:false,profiles:[]}; json(join(dir,'scoped-lifecycle.json'),lifecycle);console.log('MATRIX-DIRECTORY '+relative(root,dir)); const frozenBefore=frozenSnapshot(root),symbols=symbolsOf(join(root,candidate.artifacts.nm.path)); const image=join(root,candidate.artifacts.image.path),imageBytes=readFileSync(image); const captures=candidate.captures.map(name=>{const s=symbols[name];assert.ok(s&&s.size>0,`capture symbol ${name}`);return {name,...s};}); assert.ok(symbols.OS_K2160_CAPTURE_GATE);assert.ok(symbols.__os_fx_kernel_context); const imageSpans=readOnlyImageSpans(readFileSync(join(root,candidate.artifacts.elf.path)),candidate.imageSpan); const fixtures=join(dir,'fixtures'),firmware=join(dir,'firmware');mkdirSync(fixtures);mkdirSync(firmware); const journalFixture=readFileSync(join(root,'kernel/tests/os/fixtures/turkfs-journal-v1.bin')); const initial=beforeDisk(journalFixture),initialPath=join(fixtures,'initial.img');writeFileSync(initialPath,initial); const rng=join(fixtures,'remote-wake-synthetic.bin');writeFileSync(rng,Buffer.alloc(128,0xc3)); for(const name of ['edk2-aarch64-code.fd','edk2-arm-vars.fd'])copyFileSync(join('/opt/homebrew/share/qemu',name),join(firmware,name)); const sourcePaths=['scripts/os-acceptance/k2160-reopen-guest-runner-v2.mjs','scripts/os-acceptance/k2160-fixture.mjs', 'scripts/os-acceptance/features/k2160-capture.mjs','scripts/os-acceptance/features/k2160-disk-check.mjs', 'scripts/os-acceptance/features/k2160-physical-check.mjs']; const sourceRefs=sourcePaths.map(path=>artifact(join(root,path))); const preflight={schema:'turkos-k2160-runner-preflight/v1',candidate:artifact(candidatePath), sources:sourceRefs, fixture:{initial:artifact(initialPath),journal:artifact(join(root,'kernel/tests/os/fixtures/turkfs-journal-v1.bin')),rng:artifact(rng)}, qemu:command(join(dir,'qemu-version.log'),'qemu-system-aarch64',['--version']).split('\n')[0], captures,imageSpans,firmware:['edk2-aarch64-code.fd','edk2-arm-vars.fd'].map(n=>artifact(join(firmware,n))),bases:{}}; for(const p of profiles){const key=`${p.memoryMiB}-${p.cpuCount}`;if(preflight.bases[key])continue; const dtb=join(fixtures,`base-${key}.dtb`); command(join(dir,`dtb-${key}.log`),'qemu-system-aarch64',['-machine',`virt-11.1,gic-version=3,dtb-randomness=off,dumpdtb=${dtb}`, '-accel','hvf','-cpu','host','-smp',String(p.cpuCount),'-m',String(p.memoryMiB),'-display','none']); preflight.bases[key]=artifact(dtb); } if(profiles.some(p=>p.route==='uefi')){ const env={...process.env,CARGO_TARGET_DIR:join(dir,'target'),TURKOS_RELEASE_IMAGE_BYTES:String(imageBytes.length), TURKOS_RELEASE_IMAGE_SHA256:candidate.artifacts.image.sha256};delete env.RUSTFLAGS;delete env.CARGO_ENCODED_RUSTFLAGS; command(join(dir,'loader-product.log'),'cargo',['build','--manifest-path',join(root,candidate.sourceDirectory,'bootloader/Cargo.toml'), '--locked','--offline','--release','--target','aarch64-unknown-uefi','--features','kernel-handoff-test'],env); const loader=join(dir,'loader-product.efi');copyFileSync(join(dir,'target/aarch64-unknown-uefi/release/turkos-bootloader.efi'),loader); rmSync(join(dir,'target'),{recursive:true,force:true});preflight.loader=artifact(loader); } json(join(dir,'preflight.json'),preflight); async function physicalProof(ref,path){ assert.equal(hashAt(root,ref.path),ref.sha256,'guest result changed'); const proof=await checkReopenGuestPhysical({root,result:read(join(root,ref.path)),candidate}); assert.equal(proof.guestAccepted,false);assert.equal(proof.productAccepted,false); json(path,{schema:'turkos-k2160-physical-component-proof/v1',status:'PHYSICAL_COMPONENT_PASSED', guest:ref,candidate:artifact(candidatePath),...proof}); return artifact(path); } try{ for(const profile of profiles){ assert.ok(!qemuRunning(),'ARM64 QEMU lane occupied before profile'); assert.ok(freeBytes(root)>=20*1024**3,'space reserve before profile'); const profileDir=join(dir,profile.id);mkdirSync(profileDir); const writerBoot=bootValue(),seed=bootValue(),oldBoot=bootValue(); const writerPath=join(profileDir,'writer.img');copyFileSync(initialPath,writerPath); const writer=await guest({profile,phase:1,caseId:0,bootId:writerBoot,oldBoot,seed,block:writerPath,readOnly:false,directory:join(profileDir,'writer')}); assert.equal(writer.status,'GUEST_SYSTEM_OFF','writer failed'); const writerPhysical=await physicalProof(writer.result,join(profileDir,'writer-physical.json')); const afterWriter=readFileSync(writerPath),expected=expectedAfter(initial,seed,writerBoot); assert.deepEqual(afterWriter,expected,'writer persisted bytes differ'); const readers=[]; for(const caseId of cases){ const readerBoot=bootValue();assert.notEqual(readerBoot,writerBoot); const claimedPreviousBoot=caseId===3?readerBoot:writerBoot; const readerPath=join(profileDir,`reader-${caseId}.img`); writeFileSync(readerPath,readerDisk(initial,afterWriter,caseId)); const beforeReader=readFileSync(readerPath); const row=await guest({profile,phase:2,caseId,bootId:readerBoot,oldBoot:claimedPreviousBoot,seed, block:readerPath,readOnly:true,directory:join(profileDir,`reader-${caseId}`)}); assert.equal(row.status,'GUEST_SYSTEM_OFF',`reader case ${caseId} failed`); const physical=await physicalProof(row.result,join(profileDir,`reader-${caseId}-physical.json`)); checkReopenDiskPair({initial,afterWriter,readerBefore:beforeReader,afterReader:readFileSync(readerPath), seed,writerBoot,readerBoot,claimedPreviousBoot,caseId}); readers.push({caseId,result:row.result,physical}); } lifecycle.profiles.push({profile,writer:writer.result,writerPhysical,readers,initial:artifact(initialPath),afterWriter:artifact(writerPath), seed:hex64(seed),writerBoot:hex64(writerBoot),status:'PHYSICAL_COMPONENT_CHECKED',guestAccepted:false}); json(join(dir,'scoped-lifecycle.json'),lifecycle); } lifecycle.status='RUNNER_PHYSICAL_COMPONENTS_CHECKED'; }catch(error){lifecycle.status='RUNNER_FAILED';lifecycle.error=String(error.stack??error).slice(0,6000);process.exitCode=1; }finally{ lifecycle.completedAt=new Date().toISOString();lifecycle.frozenStable=JSON.stringify(frozenSnapshot(root))===JSON.stringify(frozenBefore); lifecycle.runnerSourcesStable=sourceRefs.every(ref=>hashAt(root,ref.path)===ref.sha256); lifecycle.allOwnedGuestsStopped=!qemuRunning(); if(!lifecycle.frozenStable||!lifecycle.runnerSourcesStable||!lifecycle.allOwnedGuestsStopped){lifecycle.status='RUNNER_FAILED';process.exitCode=1;} json(join(dir,'scoped-lifecycle.json'),lifecycle); json(join(dir,'report.json'),{...lifecycle,preflight:artifact(join(dir,'preflight.json'))}); console.log(JSON.stringify({status:lifecycle.status,report:relative(root,join(dir,'report.json')),profiles:lifecycle.profiles.length})); } async function guest({profile,phase,caseId,bootId,oldBoot,seed,block,readOnly,directory}){ checkedIdentity(bootId);checkedIdentity(oldBoot);checkedIdentity(seed); assert.ok(!qemuRunning(),'another QEMU process is already running');mkdirSync(directory); const beforePath=join(directory,'before-disk.img');copyFileSync(block,beforePath); const dtb=join(directory,'boot.dtb');copyFileSync(join(fixtures,`base-${profile.memoryMiB}-${profile.cpuCount}.dtb`),dtb); let property=0;const put=(name,words)=>command(join(directory,`fdtput-${++property}.log`),'fdtput', ['-t','x',dtb,'/chosen',name,...words.map(w=>w.toString(16))]); put('turkos,policy-probe-mode',[0]);put('turkos,boot-id',words64(bootId)); for(const mode of DEFERRED_MODES)put(`turkos,${mode}-mode`,[0]); put('turkos,feature-experiment',[2160]);put('turkos,k2160-phase',[phase]);put('turkos,k2160-case',[caseId]); put('turkos,k2160-old-hi',words64(oldBoot).slice(0,1));put('turkos,k2160-old-lo',words64(oldBoot).slice(1)); put('turkos,k2160-seed-hi',words64(seed).slice(0,1));put('turkos,k2160-seed-lo',words64(seed).slice(1)); const imageHash=Buffer.from(candidate.artifacts.image.sha256,'hex');assert.equal(imageHash.length,32); for(let i=0;i<8;i++)put(`turkos,k2160-image-${i}`,[imageHash.readUInt32BE(i*4)]); const temporary=mkdtempSync(join(tmpdir(),'tk2160-')),serialSocket=join(temporary,'serial.sock'); const argv=['-machine','virt-11.1,gic-version=3,dtb-randomness=off','-accel','hvf','-cpu','host','-smp',String(profile.cpuCount),'-m',String(profile.memoryMiB), '-dtb',dtb,'-display','none','-monitor','none','-nic','none','-S','-chardev',`socket,id=serial0,path=${serialSocket},server=on,wait=off`, '-serial','chardev:serial0','-qmp',`unix:${join(temporary,'q.sock')},server=on,wait=off`]; if(profile.route==='direct')argv.push('-kernel',image); else{ const esp=join(temporary,'esp');mkdirSync(join(esp,'EFI/BOOT'),{recursive:true}); copyFileSync(join(dir,'loader-product.efi'),join(esp,'EFI/BOOT/BOOTAA64.EFI'));copyFileSync(image,join(esp,'TURKOS.IMG')); copyFileSync(join(firmware,'edk2-arm-vars.fd'),join(temporary,'vars.fd')); argv.push('-drive',`if=pflash,format=raw,readonly=on,file=${join(firmware,'edk2-aarch64-code.fd')}`, '-drive',`if=pflash,format=raw,file=${join(temporary,'vars.fd')}`, '-drive',`if=none,id=esp,format=raw,readonly=on,file=fat:${esp}`,'-device','virtio-blk-pci,drive=esp,addr=0x1','-boot','order=c'); } argv.push('-global','virtio-mmio.force-legacy=false', '-drive',`if=none,id=k2160block,format=raw,readonly=${readOnly?'on':'off'},file=${block}`, '-device','virtio-blk-device,drive=k2160block', '-netdev',`stream,id=dma0,server=on,addr.type=unix,addr.path=${join(temporary,'net.sock')}`, '-device','virtio-net-device,netdev=dma0,mac=52:54:00:12:34:56', '-object',`rng-random,id=k1465mmiorng,filename=${rng}`,'-device','virtio-rng-device,rng=k1465mmiorng', '-object','rng-random,id=k1425rng,filename=/dev/urandom', '-device',profile.route==='uefi'?'virtio-rng-pci,rng=k1425rng,addr=0x2':'virtio-rng-pci,rng=k1425rng,addr=0x1', '-device','pci-bridge,id=k1440outer,addr=0x3,chassis_nr=1','-device','pci-bridge,id=k1440inner,bus=k1440outer,addr=0x1,chassis_nr=2', '-object','rng-random,id=k1440rng,filename=/dev/urandom','-device','virtio-rng-pci,rng=k1440rng,bus=k1440inner,addr=0x1', '-device','edu,bus=k1440inner,addr=0x2','-object','rng-random,id=k1465hotrng,filename=/dev/urandom', '-device','pcie-root-port,id=k1465rp,addr=0x4','-gdb',`unix:${join(temporary,'gdb.sock')},server=on,wait=off`); json(join(directory,'qemu-command.json'),{executable:'qemu-system-aarch64',argv:argv.map(a=>a.replaceAll(temporary,'').replaceAll(root+'/','')), profile,phase,caseId,readOnly,bootId:hex64(bootId),oldBoot:hex64(oldBoot),seed:hex64(seed)}); const result={schema:'turkos-k2160-guest-result/v1',profile,phase,caseId,readOnly,bootId:hex64(bootId), claimedPreviousBoot:hex64(oldBoot),seed:hex64(seed),status:'RUNNING',gates:[],experimentStages:[], beforeDisk:artifact(beforePath),dtb:artifact(dtb),qemuCommand:artifact(join(directory,'qemu-command.json')), guestAccepted:false,productAccepted:false}; const audit=[];const event=(kind,fields={})=>audit.push({sequence:audit.length,kind,...fields}); const plan={ramStart:0x40000000,ramEnd:0x40000000+profile.memoryMiB*1024*1024, allowedMmioBases:new Set(Array.from({length:32},(_,i)=>0x0a000000+i*0x200)),imageSpans}; const started=Date.now();let child,qmp,gdb,network,uart,serial='',stderr='',injected=false,featureActive=false; let exitValue,uartError,spawnError;let exited; const takeFile=async(name,address,size,out)=>{ const tmp=join(temporary,`${name}.bin`);await qmp.request('pmemsave',{val:address,size,filename:tmp}); copyFileSync(tmp,out);const item={name,address,size,...artifact(out)};return item; }; try{ child=spawn('qemu-system-aarch64',argv,{stdio:['ignore','ignore','pipe']});child.stderr.on('data',b=>{stderr+=b;}); child.on('error',error=>{spawnError=error;}); exited=new Promise(done=>child.once('exit',(code,signal)=>{exitValue={code,signal};done(exitValue);})); qmp=await qmpConnect(join(temporary,'q.sock')); const originalRequest=qmp.request;qmp.request=async(execute,args)=>{ event('qmp-request',{execute,args:args??null});const answer=await originalRequest(execute,args); event('qmp-response',{execute,answer});return answer;}; network=await dmaNetworkConnect(join(temporary,'net.sock')); uart=createConnection(serialSocket);uart.on('data',bytes=>{serial+=bytes.toString('latin1');}); uart.on('error',error=>{uartError=error;}); await new Promise((done,fail)=>{uart.once('connect',done);uart.once('error',fail);}); assertStatus((await qmp.request('query-status')).status,'prelaunch');await qmp.request('cont'); const handled=new Set(),expectedStages=reopenStages(phase,caseId); for(const deadline=Date.now()+300000;;){ assert.ok(Date.now()event('gdb-packet',{packet})); await gdb.writeCheckpoint(gate.address);gdb.close();gdb=null;event('gdb-close'); result.gates.push({milestone:`K${n}`,stage});await qmp.request('cont'); assertStatus((await qmp.request('query-status')).status,'running');continue; } featureActive=true;assert.equal(stage,expectedStages[result.experimentStages.length],'unexpected K2160 stage'); const auditStart=audit.length;event('capture-start',{stage}); assertStatus((await qmp.request('query-status')).status,'running'); const saved=[];for(const c of captures){const out=join(directory,`stage-${stage}-${c.name}.bin`); saved.push({symbol:c.name,...await takeFile(`stage-${stage}-${c.name}`,c.address,c.size,out)});} const data=Object.fromEntries(saved.map(item=>[item.symbol,readFileSync(join(root,item.path))])); const physical=[];const byName=new Set(); async function take(name,address,size,mmio=false){ assert.ok(!byName.has(name),'duplicate dynamic span');byName.add(name); const out=join(directory,`stage-${stage}-${name}.bin`); const item=await takeFile(`stage-${stage}-${name}`,address,size,out);physical.push({...item,name,mmio}); return readFileSync(out); } await collectReopenPhysical({stage,phase,caseId,data,symbols,take,plan}); const confirmations=[]; for(const [i,span] of [...saved,...physical].entries()){ const out=join(directory,`stage-${stage}-confirm-${i}.bin`); const c=await takeFile(`stage-${stage}-confirm-${i}`,span.address,span.size,out); assert.equal(c.sha256,span.sha256,'capture changed before gate release');confirmations.push(c); } assertStatus((await qmp.request('query-status')).status,'running'); const token=Buffer.alloc(12);token.write('K215');token.writeUInt32LE(stage,4);token.writeUInt32LE((~stage)>>>0,8); event('uart-release',{stage,hex:token.toString('hex')}); await new Promise((done,fail)=>uart.write(token,error=>error?fail(error):done())); event('capture-end',{stage});result.experimentStages.push({stage,captures:saved,physical,confirmations,auditStart,auditEnd:audit.length}); } await delay(20); } assert.deepEqual(exitValue,{code:0,signal:null}); // QMP event and UART bytes arrive before process exit; let pending data callbacks settle. await delay(50);checkReopenStageOrder(result.experimentStages.map(s=>s.stage),phase,caseId); assert.ok(injected,'inherited K790 frame was not supplied'); result.exit=exitValue;result.qmpShutdown=guestShutdownEvidence(qmp.transcript,exitValue,serial,phase,caseId,bootId); result.status='GUEST_SYSTEM_OFF'; }catch(error){ result.status='GUEST_FAILED';result.error=String(error.stack??error).slice(0,6000); // Failed collection is diagnostic only. SIGKILL cannot become a pass. try{child?.kill('SIGKILL');}catch{} if(exited)await Promise.race([exited,delay(5000)]); }finally{ gdb?.close();qmp?.close?.();uart?.destroy();network?.close(); writeFileSync(join(directory,'serial.log'),serial);result.serial=artifact(join(directory,'serial.log')); json(join(directory,'capture-audit.json'),audit);result.captureAudit=artifact(join(directory,'capture-audit.json')); json(join(directory,'qmp-transcript.json'),qmp?.transcript??[]);result.qmpTranscript=artifact(join(directory,'qmp-transcript.json')); if(stderr){writeFileSync(join(directory,'qemu-stderr.log'),stderr);result.stderr=artifact(join(directory,'qemu-stderr.log'));} const afterPath=join(directory,'after-disk.img');copyFileSync(block,afterPath); result.afterDisk=artifact(afterPath);result.elapsedMs=Date.now()-started; result.allOwnedGuestStopped=child?.exitCode!==null&&child?.signalCode===null; json(join(directory,'result.json'),result);rmSync(temporary,{recursive:true,force:true}); } return {status:result.status,result:artifact(join(directory,'result.json'))}; } } if(process.argv[1]&&resolve(process.argv[1])===resolve(new URL(import.meta.url).pathname))await main();