| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383 |
- #!/usr/bin/env python3
- """Minimal multi-target firmware entry. Users remember: target + action."""
- from __future__ import annotations
- import argparse
- import ast
- import hashlib
- import json
- import os
- import re
- import signal
- import shutil
- import subprocess
- import sys
- import tempfile
- import uuid
- import xml.etree.ElementTree as ET
- from pathlib import Path
- ROOT = Path(__file__).resolve().parents[1]
- sys.dont_write_bytecode=True
- os.environ['PYTHONDONTWRITEBYTECODE']='1'
- if str(ROOT) not in sys.path:
- sys.path.insert(0, str(ROOT))
- site_pkg = Path("/workspace/site-packages")
- if site_pkg.is_dir() and str(site_pkg) not in sys.path:
- sys.path.insert(0, str(site_pkg))
- from tools.fw_targets import list_aliases, load_registry, resolve_target as resolve_dict, target_status_line
- from tools.generate_target import generate_named_target
- from tools.target_registry import TargetError, resolve_target
- from tools.source_identity import source_identity
- def _new_run_path(name: str) -> Path:
- base=Path(os.environ.get('XDG_STATE_HOME') or tempfile.gettempdir())/'prod2u/fw'
- return base/(name+'-'+uuid.uuid4().hex[:12])
- def _die(message: str, code: int = 2) -> int:
- print(message, file=sys.stderr)
- return code
- def cmd_list(_args: argparse.Namespace) -> int:
- for alias in list_aliases(ROOT):
- print(target_status_line(alias, ROOT))
- return 0
- def _generate_one(alias: str, *, check: bool=False) -> dict:
- return generate_named_target(alias, check=check)
- def cmd_generate(args: argparse.Namespace) -> int:
- names=list_aliases(ROOT) if args.target=='all' else (args.target,)
- for name in names:
- print(json.dumps(_generate_one(name,check=args.check),sort_keys=True))
- return 0
- def _python() -> str:
- return sys.executable
- def cmd_build(args: argparse.Namespace) -> int:
- target=resolve_target(args.target)
- if sys.platform!='linux':return _die('Run TD builds in the authorized Linux container')
- _generate_one(target.alias,check=True)
- out=args.run_root or _new_run_path(target.project_id+'-td')
- print('TD run: '+str(out.resolve()),flush=True)
- command=[_python(),str(ROOT/'tools/run_6400_td.py'),'--profile',target.project_id,'--run-root',str(out)]
- if getattr(args,'host_baud',None) is not None:command.extend(['--host-baud',str(args.host_baud)])
- if getattr(args,'allow_dirty',False):command.append('--allow-dirty')
- return subprocess.call(command,cwd=ROOT)
- def cmd_test(args: argparse.Namespace) -> int:
- if sys.platform!='linux':return _die('Run current product verification in the authorized Linux container')
- products=tuple(resolve_target(name).project_id for name in list_aliases(ROOT)) if args.target=='all' else (resolve_target(args.target).project_id,)
- for product in products:_generate_one(product,check=True)
- out=(args.run_root or _new_run_path('current-regression')).resolve()
- if out==ROOT or ROOT in out.parents:return _die('--run-root must be outside the source checkout')
- out.mkdir(parents=True,exist_ok=False)
- manifest=json.loads((ROOT/'config/current-product-tests.json').read_text(encoding='utf-8'))
- unit_tests=list(manifest['shared_unit_tests'])
- for product in products:unit_tests.extend(manifest['targets'][product]['unit_tests'])
- unit_tests=list(dict.fromkeys(unit_tests))
- if not unit_tests:return _die('empty current unit test set')
- identity=source_identity(ROOT)
- receipt={'schema':'prod2u-current-regression-v1','scope':'current unit and RTL regression; not Full acceptance',
- 'run_id':out.name,'products':products,'source':identity,'status':'RUNNING','complete':False}
- receipt_path=out/'RESULT.json'
- receipt_path.write_text(json.dumps(receipt,indent=2)+'\n')
- command=[_python(),'-m','pytest','-q',*unit_tests,'--junitxml='+str(out/'python.xml'),'--basetemp='+str(out/'pytest-temp'),'-o','cache_dir='+str(out/'pytest-cache')]
- log_path=out/'python.log'
- with log_path.open('w') as log:
- log.write(json.dumps(command)+'\n');log.flush()
- process=subprocess.Popen(command,cwd=ROOT,stdout=log,stderr=subprocess.STDOUT,start_new_session=True)
- try:unit_code=process.wait(timeout=args.timeout)
- except subprocess.TimeoutExpired:os.killpg(process.pid,signal.SIGKILL);process.wait();unit_code=124
- unit_count=0;unit_errors=1;unit_skipped=1
- try:
- suites=list(ET.parse(out/'python.xml').getroot().iter('testsuite'))
- unit_count=sum(int(x.get('tests','0')) for x in suites)
- unit_errors=sum(int(x.get('errors','0'))+int(x.get('failures','0')) for x in suites)
- unit_skipped=sum(int(x.get('skipped','0')) for x in suites)
- except (OSError,ET.ParseError,ValueError):pass
- unit_pass=unit_code==0 and unit_count>0 and unit_errors==0 and unit_skipped==0
- receipt['unit']={'command':command,'exit_code':unit_code,'tests':unit_count,'skipped':unit_skipped,'status':'PASS' if unit_pass else 'FAIL','log':str(log_path),'log_sha256':hashlib.sha256(log_path.read_bytes()).hexdigest()}
- print('Unit tests: '+('PASS' if unit_pass else 'FAIL')+'; '+str(log_path),flush=True)
- try:
- rtl_code=cmd_diagnose(argparse.Namespace(target='all' if len(products)>1 else products[0],run_root=out/'rtl',
- timeout=args.timeout,reuse_rtl=getattr(args,'reuse_rtl',None)))
- except (ValueError,OSError) as error:
- rtl_code=2;receipt['rtl_error']=str(error)
- rtl_receipt=out/'rtl/RESULT.json'
- receipt['rtl_result']=str(rtl_receipt) if rtl_receipt.is_file() else None;receipt['complete']=True
- receipt['status']='PASS' if unit_pass and rtl_code==0 else 'FAIL'
- receipt_path.write_text(json.dumps(receipt,indent=2)+'\n')
- print(str(receipt_path),flush=True)
- return 0 if receipt['status']=='PASS' else (unit_code or rtl_code or 1)
- def cmd_package(args: argparse.Namespace) -> int:
- # There is only one public package implementation/command surface.
- from tools.package_prod2u import main as package_main
- return package_main(args.package_args)
- def _file_hash(path):
- with Path(path).open('rb') as stream:return hashlib.file_digest(stream,'sha256').hexdigest()
- def _json_hash(value):
- return hashlib.sha256(json.dumps(value,sort_keys=True,separators=(',',':')).encode()).hexdigest()
- def _generator_dependencies():
- pending=['tools/generate_target.py','tools/generate_6400_manual.py','tools/generate_mrdimm_params.py',
- 'tools/generate_mrdimm_adc.py','tools/target_registry.py','tools/fw_targets.py']
- found=set()
- while pending:
- name=pending.pop()
- if name in found:continue
- found.add(name)
- for node in ast.walk(ast.parse((ROOT/name).read_text(encoding='utf-8-sig'))):
- modules=[a.name for a in node.names] if isinstance(node,ast.Import) else (
- [node.module,*[node.module+'.'+a.name for a in node.names]] if isinstance(node,ast.ImportFrom) and node.module else [])
- for module in modules:
- path=module.replace('.','/')+'.py'
- if module.startswith('tools.') and (ROOT/path).is_file():pending.append(path)
- return found
- def rtl_plan(products,tests,tools):
- registry=load_registry(ROOT)
- inputs={};steps=[]
- generator_files=_generator_dependencies()
- for product in products:
- manifest_path='products/'+product+'/source-closure.json'
- manifest=json.loads((ROOT/manifest_path).read_text(encoding='utf-8'))
- sources=manifest['sources']
- target=next(row for row in registry['targets'].values() if row['project_id']==product)
- paths=set(sources)|generator_files|{manifest_path,'tools/fw_cli.py','projects/registry.json'}
- paths.update(p.relative_to(ROOT).as_posix() for p in (ROOT/'contracts').glob('*') if p.suffix in ('.json','.yaml'))
- for key in ('project_config','adc','sdc'):
- if target.get(key):paths.add(target[key])
- projects=[target['project_config']];seen_projects=set()
- while projects:
- name=projects.pop()
- if name in seen_projects:continue
- seen_projects.add(name);paths.add(name)
- configuration=json.loads((ROOT/name).read_text(encoding='utf-8'))
- if configuration.get('inherits'):projects.append(configuration['inherits'])
- for key in ('board_evidence','constraints','source_closure'):
- value=configuration.get(key)
- if isinstance(value,str) and (ROOT/value).is_file():paths.add(value)
- if product=='mrdimm-chamber':paths.add('config/pin_inventory.prod2u_door_temp_v1_2.json')
- paths.update('tests/sim/'+name+'.v' for name in tests[product])
- if product=='6400-front-rear':paths.add('src/modules/double_bank_target_store.v')
- pending=list(paths)
- while pending:
- name=pending.pop()
- if Path(name).suffix not in ('.v','.sv','.vh'):continue
- for include in re.findall(chr(96)+r'include\s+"([^"]+)"',(ROOT/name).read_text(encoding='utf-8')):
- path=include if (ROOT/include).is_file() else (Path(name).parent/include).as_posix()
- if path not in paths:paths.add(path);pending.append(path)
- inputs[product]={name:_file_hash(ROOT/name) for name in sorted(paths)}
- source_args=[name for name in sources if name.endswith('.v')]
- for top,behavior in [(manifest['top_module'],False),*((name,True) for name in tests[product])]:
- if not re.fullmatch(r'[A-Za-z_][A-Za-z0-9_]*',top):raise ValueError('invalid regression top')
- step_tag = f"{product}-{top}" if len(products) > 1 else top
- binary='{run_root}/'+step_tag+'.vvp'
- command=['iverilog','-g2012','-Wall','-I.','-B',tools['iverilog']['library_root'],'-s',top,'-o',binary,*source_args]
- if behavior:
- command.append('tests/sim/'+top+'.v')
- if top=='prod2u_6400_uart_e2e_tb':command.append('src/modules/double_bank_target_store.v')
- steps.append({'name':step_tag+'-compile','command':command,'marker':None,'binary':step_tag+'.vvp'})
- if behavior:steps.append({'name':step_tag,'command':['vvp',binary,'+ARTIFACT_DIR={run_root}'],'marker':top+' PASS','binary':None})
- if len({x['name'] for x in steps})!=len(steps):raise ValueError('duplicate regression output names')
- return {'schema':'prod2u-rtl-input-closure-v1','inputs':inputs,'tools':tools,
- 'test_configuration':{p:tests[p] for p in products},'steps':steps}
- def _render_command(step,run_root):
- return [arg.replace('{run_root}',str(run_root)) for arg in step['command']]
- def validate_rtl_cache(path,plan):
- path=Path(path).resolve();receipt_bytes=path.read_bytes();cached=json.loads(receipt_bytes)
- if cached.get('schema')!='prod2u-rtl-regression-v2' or cached.get('status')!='PASS' or cached.get('complete') is not True:
- raise ValueError('RTL_REUSE_REJECTED: only complete v2 PASS receipts can be reused')
- key=_json_hash(plan)
- if cached.get('cache_key')!=key or cached.get('plan')!=plan:
- raise ValueError('RTL_REUSE_REJECTED: input/tool/command closure differs')
- if not plan['steps'] or cached.get('inputs')!=plan['inputs']:
- raise ValueError('RTL_REUSE_REJECTED: empty or inconsistent input evidence')
- origin=cached.get('source',{})
- if any(not re.fullmatch('[0-9a-f]{40}',str(origin.get(k,''))) or origin.get(k)!=cached.get(k) for k in ('commit','tree')):
- raise ValueError('RTL_REUSE_REJECTED: source identity missing or inconsistent')
- rows=cached.get('results',[])
- if len(rows)!=len(plan['steps']) or cached.get('expected_check_count')!=len(rows):
- raise ValueError('RTL_REUSE_REJECTED: missing checks')
- native_root=cached.get('native_run_root')
- if not native_root or not Path(native_root).is_absolute():raise ValueError('RTL_REUSE_REJECTED: native command root missing')
- copies={}
- for expected,row in zip(plan['steps'],rows):
- command=_render_command(expected,native_root)
- name=expected['name']+'.log'
- if (row.get('name')!=expected['name'] or row.get('command')!=command or row.get('required_marker')!=expected['marker']
- or row.get('status')!='PASS' or row.get('exit_code')!=0 or row.get('log')!=name):
- raise ValueError('RTL_REUSE_REJECTED: result/command mismatch')
- data=(path.parent/name).read_bytes()
- if hashlib.sha256(data).hexdigest()!=row.get('log_sha256'):raise ValueError('RTL_REUSE_REJECTED: log hash mismatch')
- text=data.decode('utf-8',errors='replace')
- lines=text.splitlines()
- if not lines or json.loads(lines[0])!=command or (expected['marker'] and expected['marker'] not in text):
- raise ValueError('RTL_REUSE_REJECTED: native log/marker mismatch')
- copies[name]=data
- artifacts=cached.get('artifacts',{})
- required={step['binary'] for step in plan['steps'] if step['binary']}
- if not required<=set(artifacts):raise ValueError('RTL_REUSE_REJECTED: compiled binaries missing')
- for name,expected_hash in artifacts.items():
- if not re.fullmatch(r'[A-Za-z0-9_.-]+\.(vvp|hex)',name):
- raise ValueError('RTL_REUSE_REJECTED: invalid artifact name')
- data=(path.parent/name).read_bytes()
- if not data or hashlib.sha256(data).hexdigest()!=expected_hash:raise ValueError('RTL_REUSE_REJECTED: artifact hash mismatch')
- copies[name]=data
- return cached,copies,receipt_bytes
- def _rtl_tools():
- result={}
- driver=Path(shutil.which('iverilog') or '')
- requested=os.environ.get('PROD2U_IVERILOG_LIBDIR')
- candidates=[Path(requested)] if requested else [driver.parent.parent/'lib/ivl',*sorted(Path('/usr/lib').glob('*/ivl'))]
- library=next((p.resolve() for p in candidates if (p/'ivl').is_file() and (p/'ivlpp').is_file()),None)
- if library is None:raise ValueError('Icarus backend directory unavailable; set PROD2U_IVERILOG_LIBDIR')
- for tool in ('iverilog','vvp'):
- path=Path(shutil.which(tool) or '')
- if not path.is_file():raise ValueError('RTL tool missing: '+tool)
- version=subprocess.check_output([tool,*(['-B',str(library)] if tool=='iverilog' else []),'-V'],stderr=subprocess.STDOUT)
- result[tool]={'path':str(path.resolve()),'sha256':_file_hash(path),'version':version.decode(errors='replace').splitlines()[0],
- 'version_output_sha256':hashlib.sha256(version).hexdigest()}
- result['iverilog']['library_root']=str(library)
- result['iverilog']['library_files']={p.relative_to(library).as_posix():_file_hash(p) for p in sorted(library.rglob('*')) if p.is_file()}
- import yaml
- result['python']=sys.version;result['PyYAML']=yaml.__version__
- return result
- def cmd_diagnose(args: argparse.Namespace) -> int:
- """Bounded migrated RTL checks; explicitly not the full Quick/Full gate."""
- if sys.platform != "linux":
- return _die("Run RTL diagnostics in the authorized LAN Linux container")
- out = args.run_root.resolve()
- if out == ROOT or ROOT in out.parents:
- return _die("--run-root must be outside the source checkout")
- test_manifest_path=ROOT/'config/current-product-tests.json'
- test_manifest=json.loads(test_manifest_path.read_text(encoding='utf-8'))
- products = tuple(test_manifest.get('targets', {}).keys()) if args.target == "all" else (args.target,)
- if test_manifest.get('schema')!='prod2u-current-product-tests-v1':
- return _die('current test manifest schema mismatch')
- tests={name:entry['testbenches'] for name,entry in test_manifest['targets'].items()}
- if any(not tests[p] for p in products):
- return _die('empty current product test set')
- for product in products:_generate_one(product,check=True)
- plan=rtl_plan(products,tests,_rtl_tools())
- identity=source_identity(ROOT)
- reuse=getattr(args,'reuse_rtl',None)
- if reuse:
- cached,copies,receipt_bytes=validate_rtl_cache(reuse,plan)
- out.mkdir(parents=True,exist_ok=False)
- for name,data in copies.items():(out/name).write_bytes(data)
- receipt={**cached,'run_id':out.name,'source':identity,'commit':identity['commit'],'tree':identity['tree'],
- 'execution':'reused','reuse':{'receipt':str(Path(reuse).resolve()),'sha256':hashlib.sha256(receipt_bytes).hexdigest(),
- 'source':cached['source'],'scope':'copied verified native evidence; no RTL command rerun'}}
- (out/'REUSED-RECEIPT.json').write_bytes(receipt_bytes)
- (out/'RESULT.json').write_text(json.dumps(receipt,indent=2)+'\n',encoding='utf-8')
- print('RTL evidence reused after exact closure/log/artifact checks: '+str(reuse),flush=True)
- return 0
- out.mkdir(parents=True,exist_ok=False)
- receipt = {"schema":"prod2u-rtl-regression-v2","scope": "migration-diagnostic-only", "run_id": out.name,
- "hardware": "NOT_RUN", "results": [], "inputs": {}, "status": "RUNNING", "complete": False,
- "expected_check_count":len(plan['steps']),"plan":plan,"cache_key":_json_hash(plan),
- "native_run_root":str(out),"execution":"fresh"}
- receipt['commit']=identity['commit'];receipt['tree']=identity['tree'];receipt['source']=identity
- for tool in ('iverilog','vvp'):receipt[tool]=plan['tools'][tool]['version']
- def execute(name: str, command: list[str], marker: str | None = None,binary=None) -> bool:
- log_path = out / (name + ".log")
- with log_path.open("w", encoding="utf-8") as log:
- log.write(json.dumps(command) + "\n"); log.flush()
- process = subprocess.Popen(command, cwd=ROOT, stdout=log, stderr=subprocess.STDOUT, start_new_session=True)
- try:
- code = process.wait(timeout=args.timeout)
- except subprocess.TimeoutExpired:
- os.killpg(process.pid, signal.SIGKILL); process.wait(); code = 124
- observed = log_path.read_text(errors="replace")
- passed = code == 0 and (marker is None or marker in observed) and (not binary or ((out/binary).is_file() and (out/binary).stat().st_size>0))
- receipt["results"].append({"name": name, "command": command, "exit_code": code,
- "status": "PASS" if passed else "FAIL", "required_marker": marker,
- "log": log_path.name, "log_sha256": hashlib.sha256(log_path.read_bytes()).hexdigest()})
- # An interrupted partial run must never look like a completed PASS.
- receipt["status"] = "RUNNING"
- (out / "RESULT.json").write_text(json.dumps(receipt, indent=2) + "\n")
- print(f"{name}: {'PASS' if passed else 'FAIL'}", flush=True)
- return passed
- receipt['inputs']=plan['inputs']
- compile_pass={}
- for step in plan['steps']:
- if step['binary']:
- compile_pass[step['name'].removesuffix('-compile')]=execute(step['name'],_render_command(step,out),None,step['binary'])
- elif compile_pass.get(step['name']):
- execute(step['name'],_render_command(step,out),step['marker'])
- receipt["complete"] = True
- receipt["artifacts"] = {p.name: _file_hash(p) for p in out.iterdir() if p.suffix in (".hex",".vvp")}
- receipt["status"] = "PASS" if len(receipt["results"]) == receipt["expected_check_count"] and all(
- item["status"] == "PASS" for item in receipt["results"]) else "FAIL"
- (out / "RESULT.json").write_text(json.dumps(receipt, indent=2) + "\n")
- return 0 if receipt["status"] == "PASS" else 1
- def main(argv: list[str] | None = None) -> int:
- parser = argparse.ArgumentParser(prog="fw", description="Prod2U multi-target firmware entry")
- sub = parser.add_subparsers(dest="command", required=True)
- sub.add_parser("list")
- gen = sub.add_parser("generate")
- gen.add_argument("target")
- gen.add_argument("--check",action="store_true")
- tes = sub.add_parser("test")
- tes.add_argument("target")
- tes.add_argument("--run-root",type=Path)
- tes.add_argument("--timeout",type=int,default=180)
- tes.add_argument("--reuse-rtl",type=Path,help="reuse only matching complete RTL evidence; Python tests still run")
- diag = sub.add_parser("diagnose", help="bounded migration tests; not Full acceptance")
- diag.add_argument("target", choices=("all", "6400-front-rear", "mrdimm-chamber", "6400-v2"))
- diag.add_argument("--run-root", type=Path, required=True)
- diag.add_argument("--timeout", type=int, default=60)
- diag.add_argument("--reuse-rtl",type=Path,help="verified v2 RTL receipt; mismatches reject instead of silently rerunning")
- bld = sub.add_parser("build")
- bld.add_argument("target")
- bld.add_argument("--run-root",type=Path)
- bld.add_argument("--host-baud",type=int,choices=(921600,460800,230400,115200))
- bld.add_argument("--allow-dirty",action="store_true")
- pkg = sub.add_parser("package")
- pkg.add_argument("package_args",nargs=argparse.REMAINDER)
- args = parser.parse_args(argv)
- commands = {
- "list": cmd_list,
- "generate": cmd_generate,
- "test": cmd_test,
- "diagnose": cmd_diagnose,
- "build": cmd_build,
- "package": cmd_package,
- }
- try:
- return commands[args.command](args)
- except SystemExit as exc:
- return int(exc.code or 0)
- except (TargetError, ValueError, OSError) as exc:
- return _die(str(exc), 2)
- if __name__ == "__main__":
- load_registry(ROOT)
- raise SystemExit(main())
|