Files

199 lines
9.7 KiB
Python

#!/usr/bin/env python3
# SPDX-License-Identifier: GPL-3.0-or-later
"""Prepare the explicitly supplied private archive image with HD1 and DriveWire guest modules.
Never modifies the input. No OS or archived application bytes are in this tool.
The exact source hash pins all layout assumptions; unknown inputs are rejected.
"""
import hashlib
from pathlib import Path
import sys
SOURCE_SHA256 = '2ccd07cdfd6aa4d8a1d3ceff04f0a6c3490bde23e40e7c136830334f2264f462'
PREPARED_SHA256 = 'b4a3bf2804a229e7ebf5bc711f326b64fc35171bd4d975caee69d86c9ccb3954'
def add_drivewire_startup(image):
"""Add a persistent module pack to the OS-9 partition of the pinned seed."""
def integer(offset, length):
return int.from_bytes(image[offset:offset + length], 'big')
def extent(descriptor):
offset = descriptor * 256
size = integer(offset + 9, 4)
start = integer(offset + 16, 3) * 256
capacity = integer(offset + 19, 2) * 256
if size > capacity or integer(offset + 21, 3):
raise ValueError('Expected single-extent OS-9 file')
return start, size, capacity
def directory(descriptor):
start, size, _ = extent(descriptor)
result = {}
for offset in range(start, start + size, 32):
raw = image[offset:offset + 29]
if raw[0]:
name = bytes(c & 127 for c in raw).split(b'\0')[0].lower()
result[name] = integer(offset + 29, 3)
return result
root = directory(integer(8, 3))
pack_directory = root[b'boot_with_beckerdw']
drivers = directory(pack_directory)
pack = bytearray()
for name in (b'dwio', b'scdwv', b'n', b'n1'):
start, size, _ = extent(drivers[name])
pack.extend(image[start:start + size])
# The archive uses one sector per allocation bit. This region is the
# first eight contiguous *zeroed* free sectors of the pinned original.
# Never reuse sectors marked allocated, or overwrite recoverable old data.
sector = 0x28000
data_sectors = (len(pack) + 255) // 256
sector_count = 1 + data_sectors # one file descriptor, then its extent
if integer(6, 2) != 1 or sector + sector_count > integer(4, 2) * 8:
raise ValueError('Unexpected allocation bitmap')
for i in range(sector, sector + sector_count):
mask = 0x80 >> (i % 8)
if image[256 + i // 8] & mask or any(image[i*256:(i+1)*256]):
raise ValueError('DriveWire pack requires free, zeroed sectors')
image[256 + i // 8] |= mask
# Borrow owner, timestamps and regular-file attributes from dwio. The pack
# needs owner read + execute permissions for the stock "load" command.
offset = sector * 256
template = drivers[b'dwio'] * 256
image[offset:offset + 16] = image[template:template + 16]
image[offset] |= 0x04
image[offset + 9:offset + 13] = len(pack).to_bytes(4, 'big')
image[offset + 16:offset + 19] = (sector + 1).to_bytes(3, 'big')
image[offset + 19:offset + 21] = data_sectors.to_bytes(2, 'big')
image[offset + 256:offset + 256 + len(pack)] = pack
start, size, capacity = extent(pack_directory)
entry = start + size
if b'dwnet' in drivers or size + 32 > capacity:
raise ValueError('Expected unused directory entry for the module pack')
image[entry:entry + 32] = bytes(32)
image[entry:entry + 5] = b'dwne\xf4'
image[entry + 29:entry + 32] = sector.to_bytes(3, 'big')
offset = pack_directory * 256 + 9
image[offset:offset + 4] = (size + 32).to_bytes(4, 'big')
# Load the pack after the utilities, before the interactive shells start.
# Loading the modules does not open a connection or attach /N. Guest
# applications open the device on demand when the host setting is enabled.
descriptor = root[b'startup']
start, size, capacity = extent(descriptor)
startup = image[start:start + size]
marker = b'load utilpak1\r'
if startup.count(marker) != 1:
raise ValueError('Unexpected OS-9 startup script')
startup = startup.replace(marker, marker + b'load /dd/boot_with_beckerdw/dwnet\r')
if len(startup) > capacity:
raise ValueError('Insufficient space in existing startup extent')
image[start:start + len(startup)] = startup
offset = descriptor * 256 + 9
image[offset:offset + 4] = len(startup).to_bytes(4, 'big')
def prepare(source):
digest = hashlib.sha256(source).hexdigest()
if digest == PREPARED_SHA256:
return source
if digest != SOURCE_SHA256:
raise ValueError('Expected the original VCCEmuDisk.vhd from the NitrOS-9 L2 V3.3.0 archive')
b = bytearray(source)
def u(o,n=3):return int.from_bytes(b[o:o+n],'big')
def put(o,v,n):b[o:o+n]=v.to_bytes(n,'big')
def crc(data):
value=0xffffff
for c in data:
value ^= c << 16
for _ in range(8):
value <<= 1
if value & 0x1000000:value ^= 0x800063
value &= 0xffffff
return (value ^ 0xffffff).to_bytes(3,'big')
def file(base,fd):
o=base+fd*256;size=u(o+9,4);start=base+u(o+16)*256;capacity=u(o+19,2)*256
if size>capacity or u(o+21)!=0:raise ValueError('Expected single contiguous file')
return o,start,size,capacity
def boot_file(base):
_,r,size,_=file(base,u(base+8))
for off in range(r,r+size,32):
name=bytes(c&127 for c in b[off:off+29]).split(b'\0')[0].lower()
if name==b'os9boot':return file(base,u(off+29))
raise ValueError('No OS9Boot file')
def add_h1(base):
fd,start,size,capacity=boot_file(base)
boot=b[start:start+size];o=0;h0=None;modules=[];patched=False
while o<len(boot):
if boot[o:o+2]!=b'\x87\xcd':raise ValueError('Bad module header')
length=int.from_bytes(boot[o+2:o+4],'big');name_offset=int.from_bytes(boot[o+4:o+6],'big');name=''
for c in boot[o+name_offset:o+length]:
name+=chr(c&127)
if c&128:break
if name.lower()=='h1':raise ValueError('Unexpected existing H1 module')
module=bytearray(boot[o:o+length])
if name.lower()=='h0':h0=bytearray(module)
if name.lower()=='emudsk':
# The archived driver rejects every unit except zero. Replace
# its five-byte TST PD.DRV,Y / BNE NotReady with a call to an
# appended helper and BCS to the same error branch. All old
# code offsets stay unchanged. The helper selects FF86 on
# every read/write, preserving A (the command) and rejecting
# units >1. This is the VCC two-drive register contract.
def redirect(pattern, helper, suffix):
nonlocal module
pattern=bytes.fromhex(pattern);helper=bytes.fromhex(helper)
if module.count(pattern)!=1:raise ValueError('Unexpected EmuDsk code layout')
off=module.index(pattern);target=len(module)-3
replacement=bytes([0x17])+int(target-off-3).to_bytes(2,'big',signed=True)+bytes.fromhex(suffix)
if len(replacement)>len(pattern):raise ValueError('Patch exceeds original instruction area')
module[off:off+len(pattern)]=replacement+bytes([0x12])*(len(pattern)-len(replacement))
module=module[:-3]+helper+bytes(3)
# GetSect: select each unit, preserving the command in A.
redirect('6d a8 21 26 17',
'34 02 a6 a8 21 81 02 24 07 b7 ff 86 1c fe 35 82 1a 01 35 82', '25 17')
# Init: V.NDRV=2, two 38-byte tables at DRVBEG=15. The
# original 255-byte static allocation already has room.
redirect('86 ff 30 4f a7 84 a7 88 15 5f 39',
'cc ff 02 e7 46 30 4f a7 84 a7 88 15 30 88 26 5a 26 f5 39', '5f 39')
# Read LSN0 into the selected unit's table, not always unit 0.
redirect('33 4f c6 15', '33 4f a6 a8 21 c6 26 3d 33 cb c6 15 39', '')
module[2:4]=len(module).to_bytes(2,'big')
parity=255
for c in module[:8]:parity^=c
module[8]=parity;module[-3:]=crc(module[:-3]);patched=True
modules.append(module)
if length<9:raise ValueError('Invalid module length')
o+=length
if not patched or h0 is None or len(h0)!=47:raise ValueError('Expected 47-byte H0 descriptor')
# Descriptor header is unchanged. Unit number is its path option DRV;
# the final character of its name retains the OS-9 high-bit terminator.
name_offset=int.from_bytes(h0[4:6],'big')
h0[0x13]=1;h0[name_offset+1]=ord('1')|128;h0[-3:]=crc(h0[:-3])
prepared=b''.join(modules)+h0
if len(prepared)>capacity:raise ValueError('No unused allocated boot-file space')
b[start:start+len(prepared)]=prepared;put(fd+9,len(prepared),4)
if u(base+24,2)==size:put(base+24,len(prepared),2)
return size,len(prepared)-size
# Keep both the OS-9 root boot file and the RGBDOS volume-255 boot file
# consistent. New bytes stay in their already allocated final sectors.
add_h1(0)
old,added=add_h1((0x5a000+255*630)*256)
if u(24,2)==old:put(24,old+added,2)
add_drivewire_startup(b)
return bytes(b)
if __name__=='__main__':
if len(sys.argv)!=3:raise SystemExit('Usage: prepare-nitros9.py original.vhd prepared.vhd')
source,target=map(Path,sys.argv[1:])
if source.resolve()==target.resolve():raise SystemExit('Input and output must differ')
if target.exists() and source.samefile(target):
raise SystemExit('Input and output must refer to different files')
prepared = prepare(source.read_bytes())
target.write_bytes(prepared)