Handle stale root headers after verified online userdata shrink

This commit is contained in:
kanoqwq committed 2026-10-30 14:04:41 +08:00
1 parent 474e801808
commit dad8224ba5
5 files changed
+347 -7

No files matched your search

@@ -0,0 +1,49 @@
# 在线缩容后的再次安装衔接
## 已确认的问题
F50 已免擦卸载并扩回 Android,随后再次保数据缩容 8 GiB。F2FS ioctl、
GPT 提交、重启后的 userdata 和解密映射均已成功,但安装器报
`Reclaimed space is not free`。扩容不承诺清零所有空闲块,重新回收的尾部
还残留旧 OpenWrt ext4 主超级块。通用空闲区扫描正确识别出签名,但在线
缩容流程缺少“这是本次已确认回收的 userdata 尾部”的交接处理。
这不是缩容失败,不需要重复 ioctl、清空 Android 或关闭所有签名检查。
## 公共修复
- GPT 扫描返回发现的文件系统类型和绝对扇区,普通未登记文件系统保护保持不变。
- 只在原、新 GPT 精确匹配已校验快照、设备身份与 Android 槽一致、原 F2FS
UUID 保持、目标容量与重启后映射均通过验证后处理。
- 只有完整落在本次回收且用户已选择用于 OpenWrt 的范围内的签名允许清理。
原先已存在的其他空闲区、越界签名、未知布局不参与自动处理。
- 每处保存并校验 8 KiB 原始头到本次电脑事务的 `online-shrink/reclaimed-headers`。
写入前再次核对设备 boot ID、userdata 大小、两份 GPT 和原始头哈希,
仅清理该头并回读;不改 GPT、现有 userdata、Android boot 或 NV。
- 断线后复用已保存记录。已完成的清理不重复执行;部分写入只接受各扇区与
原备份相同或已清零,其他变化停止并保留现场。
- 完成后重新探测空闲区,再进入原有安装流程。不是通过忽略签名绕过检查。
两仓库使用同一实现,既有首次安装、明确格式化后备、TF、更新和卸载路径
不增加新的格式化步骤。
## 验证与边界
新增 `installer/tests/test_reclaimed_gap.py` 用真实 GPT 和稀疏普通文件执行
实际 shell 检查/清理命令,不操作测试主机的块设备:
1. eMMC 512-byte / UFS 4Kn、E5/MU300、ext4/F2FS 残留与多个签名。
2. 缩容后探测、清理、重新生成安装计划、协调器进入安装入口。
3. 写前断线、写后断线、部分写入、重新加载事务续接、不重复缩容。
4. 错误设备/槽/UUID/容量/GPT、越界签名、被修改备份及设备侧竞态拒绝。
5. 生产 Adapter 扫描器在清理前保护、清理后放行;通用保护仍生效。
全套后端测试:E5 452 项、MU300 415 项。Windows 分别跳过 84/88 项
POSIX 或环境限定项;Linux root 补跑后分别跳过 3/7 项平台限定项,适用项全部通过。
Linux 首次运行缺少 paramiko/lz4 并使用了无 chown 权限的用户,补齐依赖并
按所需权限重跑后通过;未把缺依赖的失败记为成功,也未修改测试来掩盖。
F50 当前失败事务已实机续接:原 UUID 保持,Android 16,395,534,336 字节,
回收 8,589,934,592 字节。仅在扇区 44,298,240 备份/清理旧 ext4 头;重新
规划与原确认计划一致,MU300 旧安装入口也确认该空间可用,事务恢复 ready。
本轮未执行后续完整系统写入,不能把这一结果称为全机型安装硬件验收。
+6 -3
View File
@@ -339,7 +339,7 @@ class Adapter:
last = self.adb.read(f'dd if={disk} bs=512 skip={tail} count={sectors-tail} 2>/dev/null')
space = gpt.gpt_space(first, last, sectors)
# Retain unlisted old filesystems rather than declaring their gap free.
safe = []
safe = []; signatures = []
for start, size in space['gaps']:
candidates = {start}
if self.kind == 'mu300':
@@ -353,10 +353,13 @@ class Adapter:
raw = self.adb.read(f'dd if={disk} bs=512 skip={offset} count=4 2>/dev/null')
if len(raw) != 2048:
raise ValueError('Incomplete free-space signature read')
occupied |= raw[1080:1082] == b'\x53\xef' or raw[1024:1028] == bytes.fromhex('1020f5f2')
kind = 'ext4' if raw[1080:1082] == b'\x53\xef' else 'f2fs' if raw[1024:1028] == bytes.fromhex('1020f5f2') else None
if kind:
signatures.append({'offset':offset,'kind':kind})
occupied = True
if not occupied:
safe.append((start, size))
space.update(first=first, last=last, safe_gaps=safe,
space.update(first=first, last=last, safe_gaps=safe, gap_signatures=signatures,
largest=max((size for _, size in safe), default=0) if space['empty'] else 0)
return space
+77
View File
@@ -234,6 +234,82 @@ class OnlineShrink:
self.ctx.stage('online_fallback','waiting_user')
raise OnlineDecision()
def prepare_reclaimed_gap(self, actual):
"""Erase stale headers only inside this transaction's proven F2FS tail.
GPT-free does not imply blank: growing userdata over an old OpenWrt
root and shrinking it again can leave its ext4 signature intact.
Keep normal untracked-filesystem protection everywhere else.
"""
j=self.r['online_shrink']; start=j['gap_start']
end=start+self.r['plan']['openwrt_bytes']//512
if any(actual.get(k)!=self.r['device'].get(k) for k in ('cid','slot','profile')):
raise RecoveryRequired('Reclaimed range belongs to a different device / 回收区域设备身份不符')
if not j.get('reclaimed_headers') and any(a<=start and end<=a+n for a,n in actual['gpt']['safe_gaps']):
return actual
files=self.files();s=self.r['device']['storage']
before=(files['old-first'],files['old-last']);after=(files['new-first'],files['new-last'])
if tuple(candidate(before,j['sectors'],s['NODE'],s['SIZE'],j['new_sectors']))!=after or self.pair()!=after:
raise RecoveryRequired('Reclaimed range does not match the original userdata shrink / 回收范围与原 userdata 缩容记录不符')
old=partition(gpt.gpt_space(*before,j['sectors']),'userdata')
new=partition(gpt.gpt_space(*after,j['sectors']),'userdata')
if (start!=new['end']+1 or end>old['end']+1 or
actual['storage']['START']!=new['start'] or actual['storage']['SIZE']!=j['new_sectors'] or
actual['boot_id']==j.get('commit_boot_id',j['boot_id'])):
raise RecoveryRequired('Reclaimed range is not outside the rebooted Android mapping / 回收范围尚未脱离重启后的 Android 映射')
gap=next(((a,n) for a,n in actual['gpt'].get('gaps',[]) if a<=start and end<=a+n),None)
signatures={row['offset']:row for row in actual['gpt'].get('gap_signatures',[])
if gap and gap[0]<=row['offset']<gap[0]+gap[1]}
for key,row in j.get('reclaimed_headers',{}).items():
if not re.fullmatch('[0-9]+',key):raise RecoveryRequired('Invalid reclaimed header record')
signatures.setdefault(int(key),{'offset':int(key),'kind':row['kind']})
signatures=list(signatures.values())
if not gap or not signatures or any(row['offset']%8 or not start<=row['offset'] or row['offset']+16>end for row in signatures):
raise RecoveryRequired('Untracked filesystem lies outside the confirmed reclaimed range / 未登记文件系统不在已确认的缩容回收范围内,不会清理')
folder=self.directory/'reclaimed-headers';folder.mkdir(exist_ok=True)
disk='/dev/block/'+storage.disk_node(s['NODE'])
ledger=j.setdefault('reclaimed_headers',{})
empty=hashlib.sha256(bytes(8192)).hexdigest()
for row in signatures:
offset=row['offset'];key=str(offset);path=folder/(key+'.bin')
raw=self.a.adb.read(f'dd if={disk} bs=512 skip={offset} count=16 2>/dev/null')
if len(raw)!=8192:raise RecoveryRequired('Incomplete reclaimed header read / 回收区域文件系统头读取不完整')
digest=hashlib.sha256(raw).hexdigest()
if key in ledger:
if not path.is_file() or sha(path)!=ledger[key]['sha256']:
raise RecoveryRequired('Reclaimed header backup changed / 回收区域文件系统头备份已变化')
saved=path.read_bytes()
# A disconnected zeroing write may have completed only some
# sectors. Resume only bytes explained by this saved write.
if len(saved)!=8192 or any(raw[n:n+512] not in (saved[n:n+512],bytes(512)) for n in range(0,8192,512)):
raise RecoveryRequired('Reclaimed header changed since backup / 回收区域文件系统头与备份不符')
else:
magic = raw[1080:1082] == b'\x53\xef' if row['kind']=='ext4' else raw[1024:1028] == bytes.fromhex('1020f5f2')
if row['kind'] not in ('ext4','f2fs') or not magic:
raise RecoveryRequired('Reclaimed header changed after probing / 回收区域文件系统头在探测后已变化')
with path.open('wb') as out:
out.write(raw);out.flush();os.fsync(out.fileno())
ledger[key]={'sha256':digest,'kind':row['kind'],'bytes':8192}
self.ctx.store.save(self.r)
if digest==empty:continue
checks=''.join('[ "$(dd if='+disk+' bs=512 skip='+str(at)+' count='+str(count)+
' 2>/dev/null | sha256sum | cut -d\' \''+' -f1)" = '+hashlib.sha256(data).hexdigest()+' ]; '
for at,count,data in ((0,j['front'],after[0]),(j['tail'],j['sectors']-j['tail'],after[1])))
script=('set -eu; set -o pipefail; [ "$(cat /proc/sys/kernel/random/boot_id)" = '+shlex.quote(actual['boot_id'])+' ]; '+
'[ "$(cat /sys/class/block/'+s['NODE']+'/size)" = '+str(j['new_sectors'])+' ]; '+checks+
'[ "$(dd if='+disk+' bs=512 skip='+key+' count=16 2>/dev/null | sha256sum | cut -d\' \''+' -f1)" = '+digest+' ]; '+
'dd if=/dev/zero of='+disk+' bs=4096 seek='+str(offset//8)+' count=2 conv=notrunc,fsync; '+
'[ "$(dd if='+disk+' bs=512 skip='+key+' count=16 2>/dev/null | sha256sum | cut -d\' \''+' -f1)" = '+empty+' ]')
self.r['unsafe']=True;self.ctx.store.save(self.r)
self.ctx.log('Preparing reclaimed '+row['kind']+' header at sector '+key+' / 清理已确认回收区的旧文件系统头',scope='online-shrink')
self.a.adb.shell(script,root=True,timeout=None)
verified=self.a.probe(self.r['device']['serial'],'part')
if (any(verified.get(k)!=actual.get(k) for k in ('cid','slot','profile','boot_id')) or
self.pair()!=after or not any(a<=start and end<=a+n for a,n in verified['gpt']['safe_gaps'])):
raise RecoveryRequired('Reclaimed range did not pass final checks / 回收区域清理后的复核未通过')
self.r['unsafe']=False;self.ctx.store.save(self.r)
return verified
def run(self):
self.a.bind(self.r['device']['serial'])
if 'online_shrink' not in self.r:
@@ -277,6 +353,7 @@ class OnlineShrink:
if actual['storage']['SIZE'] != j['new_sectors'] or info['volume']['mapped_bytes'] != j['new_sectors']*512:
raise RecoveryRequired('Android mapping did not adopt the resized partition / Android 未采用缩容后的映射容量')
actual = self.a.probe(self.r['device']['serial'],'part')
actual = self.prepare_reclaimed_gap(actual)
if not any(start <= j['gap_start'] and start+n >= j['gap_start']+self.r['plan']['openwrt_bytes']//512
for start,n in actual['gpt']['safe_gaps']):
raise RecoveryRequired('Reclaimed space is not free / 缩容回收范围不是可用空闲区')
+5 -4
View File
@@ -124,10 +124,11 @@ class OnlineTests(unittest.TestCase):
self.assertFalse(inspect(a,d)['available'])
self.assertFalse(any(' of=' in str(c) for c in a.adb.mock_calls))
def job(self,temp):
d,pair,total=device();store=Store(Path(temp));plan=plan_install({'adapter':'e5'},d,dict(method='part',size_gib=4))
r=store.create({'adapter':'e5'},d,dict(method='part',size_gib=4),plan)
ctx=Context(store,r,lambda *_:None);a=SimpleNamespace(ctx=ctx,kind='e5',bind=Mock(),adb=Mock(),probe=Mock(return_value=deepcopy(d)))
def job(self,temp,block=4096,kind='e5'):
d,pair,total=device(block);store=Store(Path(temp));plan=plan_install({'adapter':kind},d,dict(method='part',size_gib=4))
if block==512:d['storage']['NODE']='mmcblk0p2'
r=store.create({'adapter':kind},d,dict(method='part',size_gib=4),plan)
ctx=Context(store,r,lambda *_:None);a=SimpleNamespace(ctx=ctx,kind=kind,bind=Mock(),adb=Mock(),probe=Mock(return_value=deepcopy(d)))
a.adb.shell.return_value='busy=0'
job=OnlineShrink(a);job.directory.mkdir()
new=tuple(candidate(pair,total,d['storage']['NODE'],d['storage']['SIZE'],plan['new_sectors']))
+210
View File
@@ -0,0 +1,210 @@
"""Real GPT and shell writes against sparse regular files, never a device.
Replays uninstall/grow -> shrink -> stale root header -> install handoff,
including transport loss on either side of the bounded cleanup write.
"""
from copy import deepcopy
from contextlib import contextmanager
import io
import os
from pathlib import Path
import re
import shlex
import subprocess
import sys
import tempfile
import unittest
from unittest.mock import Mock, patch
import test_online_shrink as online_tests
from test_online_shrink import sb
from backend import gpt, storage
from backend.adapter import Adapter
from backend.online_shrink import OnlineShrink
from backend.service import Service
from backend.state import Context, RecoveryRequired
@unittest.skipUnless(sys.platform.startswith('linux'),'requires Linux dd/fsync and sha256sum for the actual Android shell recipe')
class ReclaimedGapTests(unittest.TestCase):
@contextmanager
def fixture(self,block=4096,kind='e5',fs='ext4',interior=False):
with tempfile.TemporaryDirectory() as temp:
root=Path(temp);job,r,a,old,new=online_tests.OnlineTests().job(temp,block,kind)
j=r['online_shrink'];j['state']='gpt-committed'
disk=root/'disk';boot=root/'boot';size=root/'size'
boot.write_text('after\n');size.write_text(str(j['new_sectors'])+'\n')
with disk.open('wb') as out:
out.truncate(j['sectors']*512)
out.seek(0);out.write(new[0]);out.seek(j['tail']*512);out.write(new[1])
start=j['gap_start'];offsets=[start]+([start+4096] if interior else [])
original=bytearray(b'\xa7'*8192)
if fs=='ext4':original[1080:1082]=b'\x53\xef'
else:original[:]=sb()
original=bytes(original)
def write(offset,data):
with disk.open('r+b') as out:out.seek(offset*512);out.write(data)
def read_at(offset,count):
with disk.open('rb') as src:src.seek(offset*512);return src.read(count)
for offset in offsets:write(offset,original)
actual=deepcopy(r['device']);actual['boot_id']='after'
actual['storage']['SIZE']=j['new_sectors'];actual['userdata_bytes']=j['new_sectors']*512
mutations=[]
def pair():return read_at(0,len(new[0])),read_at(j['tail'],len(new[1]))
def probe(*_):
result=deepcopy(actual);space=gpt.gpt_space(*pair(),j['sectors'])
signatures=[];safe=[]
for at,n in space['gaps']:
found=[]
for offset in set([at]+[i for i in offsets if at<=i<at+n]):
raw=read_at(offset,2048)
fs='ext4' if raw[1080:1082]==b'\x53\xef' else 'f2fs' if raw[1024:1028]==bytes.fromhex('1020f5f2') else None
if fs:found.append(dict(offset=offset,kind=fs))
signatures.extend(found)
if not found:safe.append((at,n))
result['gpt']=dict(space,safe_gaps=safe,gap_signatures=signatures)
return result
def read(command):
m=re.fullmatch(r'dd if=/dev/block/\w+ bs=512 skip=(\d+) count=16 2>/dev/null',command)
if not m:raise AssertionError(command)
return read_at(int(m[1]),8192)
rawdisk='/dev/block/'+storage.disk_node(actual['storage']['NODE'])
def shell(command,**kwargs):
self.assertTrue(command.startswith('set -eu; set -o pipefail;'))
script=command.replace(rawdisk,shlex.quote(str(disk)))
script=script.replace('/proc/sys/kernel/random/boot_id',shlex.quote(str(boot)))
script=script.replace('/sys/class/block/'+actual['storage']['NODE']+'/size',shlex.quote(str(size)))
self.assertNotIn('/dev/block/',script);self.assertNotIn('/sys/',script);self.assertNotIn('/proc/',script)
mutations.append(command)
result=subprocess.run(['bash','-c',script],capture_output=True,text=True)
if result.returncode:raise ConnectionError(result.stderr or 'guard refused write')
return result.stdout
a.probe.side_effect=probe;a.adb.read.side_effect=read;a.adb.shell.side_effect=shell
info=dict(available=True,uuid=j['uuid'],blocks=j['target_blocks'],volume=dict(mapped_bytes=j['new_sectors']*512))
with patch.object(OnlineShrink,'pair',side_effect=pair),patch('backend.online_shrink.inspect',return_value=info),patch('backend.service.inspect_online',return_value=info):
yield dict(job=job,r=r,a=a,j=j,start=start,offsets=offsets,original=original,actual=actual,
probe=probe,read=read_at,write=write,shell=shell,mutations=mutations,new=new,pair=pair,
info=info,boot=boot,size=size)
def test_emmc_ufs_both_repositories_install_handoff_with_old_headers(self):
for block in (512,4096):
for kind in ('e5','mu300'):
for fs in ('ext4','f2fs'):
with self.subTest(block=block,kind=kind,fs=fs),self.fixture(block,kind,fs,True) as f:
r,a,job=f['r'],f['a'],f['job'];a.password='';a.execute=Mock()
service=Service('.',job.ctx.store,io.StringIO())
service.openwrt_wait_stage=Mock();service.wait_openwrt=Mock()
service.run(job.ctx,a)
self.assertIsNone(r.get('error'),r.get('error'));self.assertEqual(f['j']['state'],'verified')
self.assertFalse(r['unsafe']);self.assertEqual(r['plan']['target'],'GPT unallocated space')
a.execute.assert_called_once();a.adb.call.assert_not_called()
self.assertEqual(f['pair'](),f['new'])
self.assertEqual(len(f['mutations']),2)
for offset in f['offsets']:
self.assertEqual(f['read'](offset,8192),bytes(8192))
self.assertEqual((job.directory/'reclaimed-headers'/f'{offset}.bin').read_bytes(),f['original'])
# Retry is a no-op: no resize, no extra writes or backup growth.
job.run();self.assertEqual(len(f['mutations']),2)
def test_disconnect_before_after_and_halfway_through_write_is_resumable(self):
for phase in ('before','after','half'):
with self.subTest(phase=phase),self.fixture(fs='f2fs',interior=True) as f:
def interrupted(command,**kw):
if phase=='after':f['shell'](command,**kw)
elif phase=='half':f['write'](f['start'],bytes(4096))
raise ConnectionError('fixture disconnected')
f['a'].adb.shell.side_effect=interrupted
with self.assertRaises(ConnectionError):f['job'].run()
self.assertTrue(f['r']['unsafe'])
saved=f['job'].ctx.store.load(f['r']['id'])
f['a'].ctx=Context(f['job'].ctx.store,saved,lambda *_:None)
f['a'].adb.shell.side_effect=f['shell']
OnlineShrink(f['a']).run()
self.assertEqual(saved['online_shrink']['state'],'verified');self.assertFalse(saved['unsafe'])
self.assertEqual(f['pair'](),f['new'])
for offset in f['offsets']:self.assertEqual(f['read'](offset,8192),bytes(8192))
def test_no_write_on_changed_device_gpt_geometry_or_filesystem(self):
for bad in ('cid','slot','profile','NODE','START','DISK_SIZE','uuid','blocks','mapping','gpt'):
with self.subTest(bad=bad),self.fixture() as f:
if bad in ('cid','slot','profile'):f['actual'][bad]='wrong'
elif bad in ('NODE','START','DISK_SIZE'):f['actual']['storage'][bad]='wrong'
elif bad=='mapping':f['info']['volume']['mapped_bytes']-=4096
elif bad=='gpt':f['write'](0,b'corrupt')
else:f['info'][bad]='wrong'
with self.assertRaises(RecoveryRequired):f['job'].run()
self.assertEqual(f['mutations'],[])
self.assertEqual(f['read'](f['start'],8192),f['original'])
def test_unrelated_or_cross_boundary_signature_is_never_cleared(self):
for position in ('old-gap','overlap'):
with self.subTest(position=position),self.fixture() as f:
end=f['start']+f['r']['plan']['openwrt_bytes']//512
offset=end+2048 if position=='old-gap' else end-8
f['offsets'].append(offset);f['write'](offset,f['original'])
with self.assertRaisesRegex(RecoveryRequired,'outside'):f['job'].run()
self.assertEqual(f['mutations'],[])
self.assertEqual(f['read'](f['start'],8192),f['original'])
def test_changed_header_since_probe_never_cleared(self):
with self.fixture() as f:
def changed(command):
f['write'](f['start'],b'changed'.ljust(8192,b'!'))
return f['read'](f['start'],8192)
f['a'].adb.read.side_effect=changed
with self.assertRaisesRegex(RecoveryRequired,'after probing'):f['job'].run()
self.assertEqual(f['mutations'],[])
def test_device_side_guards_prevent_write_after_host_read(self):
for bad in ('boot','size','gpt','header'):
with self.subTest(bad=bad),self.fixture() as f:
def changed(command,**kw):
if bad=='boot':f['boot'].write_text('new-boot\n')
elif bad=='size':f['size'].write_text('123\n')
elif bad=='gpt':f['write'](0,b'changed')
else:f['write'](f['start'],b'changed')
return f['shell'](command,**kw)
f['a'].adb.shell.side_effect=changed
with self.assertRaises(ConnectionError):f['job'].run()
self.assertNotEqual(f['read'](f['start'],8192),bytes(8192))
def test_tampered_backup_or_unexplained_partial_write_rejected_on_resume(self):
for bad in ('backup','header'):
with self.subTest(bad=bad),self.fixture() as f:
f['a'].adb.shell.side_effect=ConnectionError('before write')
with self.assertRaises(ConnectionError):f['job'].run()
if bad=='backup':(f['job'].directory/'reclaimed-headers'/f"{f['start']}.bin").write_bytes(b'tampered')
else:f['write'](f['start']+8,b'unknown'.ljust(4096,b'!'))
f['a'].adb.shell.side_effect=f['shell']
with self.assertRaises(RecoveryRequired):f['job'].run()
self.assertEqual(f['mutations'],[])
def test_guarded_cleanup_does_not_repeat_successful_resize(self):
with self.fixture() as f,patch.object(OnlineShrink,'stage') as stage:
f['job'].run();stage.assert_not_called();f['a'].adb.call.assert_not_called()
self.assertTrue(all('of=/dev/block/' in c and 'count=2 conv=notrunc,fsync' in c for c in f['mutations']))
def test_actual_adapter_gap_scanner_protects_then_accepts_reclaimed_header(self):
for block in (512,4096):
for kind in ('e5','mu300'):
with self.subTest(block=block,kind=kind),self.fixture(block,kind) as f:
scanner=Adapter.__new__(Adapter);scanner.kind=kind;scanner.adb=Mock()
def read(command):
m=re.fullmatch(r'dd if=/dev/block/\w+ bs=(\d+)(?: skip=(\d+))? count=(\d+) 2>/dev/null',command)
self.assertIsNotNone(m,command)
return f['read'](int(m[1])*int(m[2] or '0')//512,int(m[1])*int(m[3]))
scanner.adb.read.side_effect=read
s=dict(f['actual']['storage'],SECTOR_SIZE=block)
space=scanner.read_gpt(s)
self.assertIn({'offset':f['start'],'kind':'ext4'},space['gap_signatures'])
self.assertFalse(any(a<=f['start']<a+n for a,n in space['safe_gaps']))
f['job'].run()
clean=scanner.read_gpt(s)
self.assertTrue(any(a<=f['start']<a+n for a,n in clean['safe_gaps']))
# The generic scanner still rejects a new unrelated raw root.
f['write'](f['start'],f['original'])
protected=scanner.read_gpt(s)
self.assertFalse(any(a<=f['start']<a+n for a,n in protected['safe_gaps']))
if __name__=='__main__':unittest.main()