// Builds a K2101+ feature candidate: the last accepted candidate's sources, // specialized to the product-control boot (every earlier probe chain is // compiled out, as K2100 specialized to one mode), plus the feature EL0 // harness, the feature's runtime model, its guest experiment and its native // EL0 programs. The Image span stays inside the 8 MiB loader capacity. import assert from 'node:assert/strict'; import {appendFileSync,copyFileSync,cpSync,existsSync,mkdtempSync,readFileSync,rmSync,writeFileSync} from 'node:fs'; import {join,relative,resolve} from 'node:path'; import {spawnSync} from 'node:child_process'; import {hashAt,frozenSnapshot} from './boot-contract-report.mjs'; assert.equal(process.argv.length,4,'usage: node feature-candidate.mjs '); const root=process.cwd(),specPath=relative(root,resolve(process.argv[2])),spec=JSON.parse(readFileSync(specPath,'utf8')),integration=spec.integration; const userPath=relative(root,resolve(process.argv[3])),user=JSON.parse(readFileSync(userPath,'utf8')); const read=p=>JSON.parse(readFileSync(p,'utf8')),artifact=p=>({path:relative(root,p),sha256:hashAt(root,relative(root,p))}); const check=item=>{assert.equal(hashAt(root,item.path),item.sha256,item.path);return item;}; assert.equal(user.status,'USER_BUILD_PASSED');assert.equal(user.milestone,spec.milestone); // Base: either the last accepted candidate named by a readiness record, or an // explicitly declared unaccepted candidate source (recorded as such). let readiness=null,matrixCheck=null,baseCandidate; if(integration.base){readiness=read(integration.base);assert.ok(['ACCEPTED_AND_PRODUCTION_PUBLISHED','DEVELOPMENT_ACCEPTED'].includes(readiness.status),'accepted base'); matrixCheck=read(readiness.matrixCheck);assert.equal(matrixCheck.guestAccepted,true);baseCandidate=check(matrixCheck.candidate);} else{assert.equal(integration.baseCandidate.accepted,false);assert.ok(integration.baseCandidate.reason?.length>40);baseCandidate=check({path:integration.baseCandidate.path,sha256:integration.baseCandidate.sha256});} const base=read(baseCandidate.path); const frozenBefore=frozenSnapshot(root),directory=mkdtempSync(join(root,`reports/os-implementation/${spec.milestone}-${spec.slug}-candidate-`)),sources=join(directory,'sources'); cpSync(join(root,base.sourceDirectory),sources,{recursive:true,filter:p=>!p.split('/').includes('target')}); const report={schema:'turkos-feature-candidate/v1',milestone:spec.milestone,slug:spec.slug,experiment:Number(spec.milestone.slice(1)),feature:spec.feature, status:'RUNNING',guestAccepted:false,productAccepted:false,spec:artifact(join(root,specPath)), base:readiness?{accepted:true,readiness:artifact(join(root,integration.base)),matrixCheck:artifact(join(root,readiness.matrixCheck)),candidate:baseCandidate} :{accepted:false,candidate:baseCandidate,reason:integration.baseCandidate.reason}, userBuild:artifact(join(root,userPath)),sourceDirectory:relative(root,sources),captures:integration.captures,transforms:[],sources:{}, harness:artifact(join(root,'scripts/os-acceptance/feature-candidate.mjs')),frozenBefore}; const mainPath=join(sources,'kernel/src/main.rs');let main=readFileSync(mainPath,'utf8'); function replaceOnce(name,before,after){assert.equal(main.split(before).length,2,`${name}: anchor must occur exactly once`);main=main.replace(before,after);report.transforms.push(name);} // Foundation (first K2101+ milestone only; later bases already carry it). if(!main.includes('fn os_feature_experiment(')){ const guards=[' if mode>210 || (144..=209).contains(&mode) {return Err("policy-probe-mode");}\n Ok(mode)',' if mode!=210 {return Err("policy-probe-mode");}\n Ok(210)'].filter(g=>main.includes(g)); assert.equal(guards.length,1,'exactly one known probe-mode guard'); replaceOnce('product-control-specialization',guards[0],' if mode!=0 {return Err("policy-probe-mode");}\n Ok(0)'); // Inline the enable gate so every probe-chain branch folds to false. replaceOnce('product-control-gate-inline','fn os_k1100_product_probe_enabled(boot:&BootData)->Result{\n', '#[inline(always)]\nfn os_k1100_product_probe_enabled(boot:&BootData)->Result{\n'); replaceOnce('feature-hook',` if let Err(reason) = os_k720_accept(&mut os_runtime.memory_mut().expect("frame authority").allocator, &tables) { write_str("TURKOS/OS/FRAME: REJECTED reason="); write_line(reason); park(); } write_line("TURKOS/MMU-NORMAL: PASS");`,` if let Err(reason) = os_k720_accept(&mut os_runtime.memory_mut().expect("frame authority").allocator, &tables) { write_str("TURKOS/OS/FRAME: REJECTED reason="); write_line(reason); park(); } if cfg!(feature="os-runtime-product") { if let Err(reason)=os_feature_experiment(&mut os_runtime,&tables,boot) { write_str("TURKOS/OS/FEATURE: REJECTED reason="); write_line(reason); park(); } } write_line("TURKOS/MMU-NORMAL: PASS");`); main+=` // K2101+ feature experiments in the specialized product Image. Zero (or an // absent property) is the plain product-control boot. #[path="feature_el0.rs"] mod feature_el0; #[inline(never)] fn os_feature_experiment(runtime:&mut OsK660Runtime,tables:&mmu::Tables,boot:&BootData)->Result<(),&'static str>{ let blob=unsafe{core::slice::from_raw_parts(boot.dtb_address as *const u8,boot.dtb_size)}; let scratch=unsafe{&*core::ptr::addr_of!(OS_K700_WORKSPACE)}; let experiment=turkos_kernel::runtime::platform::chosen_u32(blob,scratch,b"turkos,feature-experiment").map_err(|_|"feature-experiment-property")?.unwrap_or(0); match experiment { 0=>Ok(()), _=>Err("feature-experiment"), } } `;report.transforms.push('feature-dispatcher'); for(const name of['feature_el0.rs','feature_el0.S']){copyFileSync(join(root,'scripts/os-acceptance/features/foundation',name),join(sources,'kernel/src',name));report.sources[name]=artifact(join(sources,'kernel/src',name));} } const module=integration.module,number=report.experiment;assert.match(module,/^k2[1-5]\d\d_[a-z0-9_]+$/); assert.ok(!main.includes(`mod ${module};`),'feature already integrated in base'); replaceOnce('feature-module','#[path="feature_el0.rs"] mod feature_el0;\n',`#[path="feature_el0.rs"] mod feature_el0;\n#[path="${integration.experiment.to}"] mod ${module};\n`); replaceOnce('feature-arm',' _=>Err("feature-experiment"),\n',` ${number}=>{${module}::run(runtime,tables,boot)?;write_line("TURKOS/OS/${spec.milestone}: PASS");Ok(())}\n _=>Err("feature-experiment"),\n`); writeFileSync(mainPath,main); copyFileSync(join(root,integration.experiment.from),join(sources,'kernel/src',integration.experiment.to));report.sources[integration.experiment.to]=artifact(join(sources,'kernel/src',integration.experiment.to)); for(const m of integration.runtime){ const to=join(sources,'kernel/src/runtime',m.module+'.rs');assert.ok(!existsSync(to),`runtime module ${m.module} exists`); copyFileSync(join(root,m.from),to);appendFileSync(join(sources,'kernel/src/runtime/mod.rs'),`\npub mod ${m.module};\n`); assert.equal(hashAt(root,relative(root,to)),hashAt(root,m.from),'runtime model must equal the tested crate source');report.sources['runtime/'+m.module+'.rs']=artifact(to); } for(const p of user.programs){check(p.image);const to=join(sources,'kernel/src',p.name+'.bin');copyFileSync(join(root,p.image.path),to);report.sources[p.name+'.bin']=artifact(to);} report.sources['main.rs']=artifact(mainPath);report.sources['runtime/mod.rs']=artifact(join(sources,'kernel/src/runtime/mod.rs')); const env={...process.env,CARGO_TARGET_DIR:join(directory,'target'),CARGO_BUILD_JOBS:'8', RUSTFLAGS:'-C opt-level=s -C llvm-args=--enable-machine-outliner=always -C relocation-model=static -C link-arg=-T'+join(sources,'kernel/linker.ld')+' -C link-arg=--build-id=none -A warnings'}; delete env.CARGO_ENCODED_RUSTFLAGS; const args=['build','--manifest-path',join(sources,'kernel/Cargo.toml'),'--offline','--release','--target','aarch64-unknown-none','--bin','turkos-kernel','--no-default-features','--features','os-runtime-product']; const build=spawnSync('cargo',args,{cwd:root,env,encoding:'utf8',timeout:900000,maxBuffer:128*1024*1024}); writeFileSync(join(directory,'kernel-product.log'),(build.stdout??'')+(build.stderr??'')); report.build={args:args.map(a=>a.replaceAll(root+'/','')),rustflags:env.RUSTFLAGS.replaceAll(root+'/',''),exitCode:build.status,error:build.error?.message??null,log:artifact(join(directory,'kernel-product.log'))}; if(!build.error&&build.status===0){ const sysroot=spawnSync('rustc',['--print','sysroot'],{encoding:'utf8'}).stdout.trim(),host=spawnSync('rustc',['-vV'],{encoding:'utf8'}).stdout.match(/^host: (.+)$/m)[1]; const tool=(n,a)=>{const r=spawnSync(join(sysroot,'lib/rustlib',host,'bin',n),a,{encoding:'utf8',maxBuffer:64*1024*1024});assert.equal(r.status,0,r.stderr);return r.stdout;}; const elf=join(directory,'product.elf'),image=join(directory,'product.Image'),nm=join(directory,'product.nm'); copyFileSync(join(directory,'target/aarch64-unknown-none/release/turkos-kernel'),elf);tool('llvm-objcopy',['-O','binary',elf,image]);writeFileSync(nm,tool('llvm-nm',['-n','-S',elf])); report.artifacts={elf:artifact(elf),image:artifact(image),nm:artifact(nm)}; const symbols=readFileSync(nm,'utf8'),address=n=>Number.parseInt(symbols.match(new RegExp('^([a-f0-9]{16}) [a-f0-9]{16} [A-Za-z] '+n+'$','m'))?.[1]??symbols.match(new RegExp('^([a-f0-9]{16}) [A-Za-z] '+n+'$','m'))?.[1],16); const start=address('_image_start'),end=address('_image_end');report.imageSpan={start,end,bytes:end-start,maximum:8*1024*1024}; for(const name of[...integration.captures,`OS_${spec.milestone}_CAPTURE_GATE`])assert.ok(new RegExp(` ${name}$`,'m').test(symbols),`symbol ${name}`); report.status=Number.isSafeInteger(start)&&Number.isSafeInteger(end)&&end>start&&end-start<=report.imageSpan.maximum?'COMPILED_FEATURE_CANDIDATE':'FEATURE_CANDIDATE_IMAGE_SPAN_FAILED'; }else report.status='FEATURE_CANDIDATE_COMPILE_FAILED'; rmSync(join(directory,'target'),{recursive:true,force:true});report.buildOutputsRemoved=true; report.frozenAfter=frozenSnapshot(root);assert.deepEqual(report.frozenAfter,frozenBefore); writeFileSync(join(directory,'report.json'),JSON.stringify(report,null,2)+'\n'); console.log(JSON.stringify({status:report.status,report:relative(root,join(directory,'report.json')),imageSpan:report.imageSpan})); if(report.status!=='COMPILED_FEATURE_CANDIDATE')process.exitCode=1;