Fix candidate build metadata and runtime safeguards
Offline project checks / check (push) Canceled after 0s

Repair kernel patch formatting and refresh kernel/camera package revisions and checksums. Integrate battery guard into generated images, correct charging controls and emergency shutdown handling, and reject invalid camera authentication configuration.

Extend recipe validation and regression coverage, and update build and installation documentation. Kernel, camera and image compilation remain pending on the build server.
This commit is contained in:
shenlei
2026-11-09 10:49:22 +09:00
parent 23989f4a18
commit 4f3fe1f94b
19 changed files with 298 additions and 100 deletions
+1 -1
View File
@@ -31,7 +31,7 @@ for package in device-xiaomi-platina firmware-xiaomi-platina linux-postmarketos-
grep -q "^$package=" /etc/apk/world
done
python3 /usr/local/libexec/platina-image-runtime audit
for service in sshd dbus networkmanager usb-moded chronyd local avahi-daemon platina-power-chord; do
for service in sshd dbus networkmanager usb-moded chronyd local avahi-daemon platina-power-chord platina-battery-guard; do
test -L "/etc/runlevels/default/$service"
done
for key in /etc/ssh/ssh_host_*_key; do
+1 -1
View File
@@ -55,7 +55,7 @@ for package in device-xiaomi-platina firmware-xiaomi-platina linux-postmarketos-
set -- "$@" "$package=$version"
done
apk add --no-network "$@"
for service in sshd dbus networkmanager usb-moded chronyd local avahi-daemon platina-power-chord; do
for service in sshd dbus networkmanager usb-moded chronyd local avahi-daemon platina-power-chord platina-battery-guard; do
rc-update add "$service" default
done
printf 'Image configured for SSH keys and passwordless sudo for the dedicated administrator.\n'
+6 -2
View File
@@ -21,6 +21,8 @@ HELPERS = {
'scripts/phone-poweroff.py': 'usr/local/sbin/platina-poweroff',
'scripts/phone-power-chord.py': 'usr/local/sbin/platina-power-chord',
'scripts/phone-power-chord.openrc': 'etc/init.d/platina-power-chord',
'scripts/phone-battery-guard.py': 'usr/local/sbin/platina-battery-guard',
'scripts/phone-battery-guard.openrc': 'etc/init.d/platina-battery-guard',
'scripts/phone-headless.start': 'etc/local.d/platina-headless.start',
'scripts/phone-usb-power.py': 'usr/local/sbin/platina-usb-power',
'scripts/phone-usb-power-dispatcher.sh': 'etc/NetworkManager/dispatcher.d/90-platina-usb-power',
@@ -40,7 +42,8 @@ def layout(version):
modes[base + '/' + sub + name] = 0o644
links = {'usr/local/share/platina/current': 'releases/' + version,
'etc/platina-release': '../usr/local/share/platina/current/version',
'etc/runlevels/default/platina-power-chord': '../../init.d/platina-power-chord'}
'etc/runlevels/default/platina-power-chord': '../../init.d/platina-power-chord',
'etc/runlevels/default/platina-battery-guard': '../../init.d/platina-battery-guard'}
return base, modes, links
@@ -88,7 +91,8 @@ def audit_contents(manifest, read):
if len(raw) != display['raw_bytes'] or hashlib.sha256(raw).hexdigest() != display['raw_sha256']:
raise ValueError('Screen decoded checksum mismatch')
return {'version': version, 'runtime_files': len(modes), 'screens_verified': 2,
'power_chord_active': True, 'usb_poweroff_requires_unplug': True}
'power_chord_active': True, 'battery_guard_active': True,
'usb_poweroff_requires_unplug': True}
def audit(root):
+4 -1
View File
@@ -3,7 +3,10 @@ description="Platina battery health and emergency shutdown daemon (50-65% SoC, a
command="/usr/local/sbin/platina-battery-guard"
command_user="root:root"
command_args="--low ${low:-50} --high ${high:-65} --max-temp ${max_temp:-45} --shutdown-at ${shutdown_at:-5} --interval ${interval:-60}"
command_background="yes"
supervisor="supervise-daemon"
respawn_delay=5
respawn_max=5
respawn_period=1800
pidfile="/run/platina-battery-guard.pid"
output_log="/var/log/platina-battery-guard.log"
error_log="/var/log/platina-battery-guard.log"
+48 -60
View File
@@ -49,9 +49,9 @@ class BatteryPolicy:
if current_state is not None:
self.charging_state = current_state
# Temperature safety cutoff: prevent thermal runaway and pouch swelling
# Power-supply sysfs reports temperature in tenths of a degree Celsius.
if temp is not None:
deg_c = temp / 10.0 if temp > 150 else float(temp)
deg_c = temp / 10.0
if deg_c >= self.max_temp:
self.thermal_throttled = True
self.charging_state = False
@@ -62,6 +62,9 @@ class BatteryPolicy:
self.thermal_throttled = False
else:
return False
elif self.thermal_throttled:
self.charging_state = False
return False
if capacity >= self.high:
self.charging_state = False
@@ -126,66 +129,46 @@ def is_battery_discharging(battery_dir, charger_dir=None):
def trigger_shutdown(executor=subprocess.run):
"""Sync filesystem and execute safe poweroff."""
print('platina-battery-guard: CRITICAL: battery <= 5% and discharging; emergency poweroff to protect filesystem', flush=True)
"""Request orderly init shutdown without relying on a display or suspend helper."""
print('platina-battery-guard: CRITICAL: battery below shutdown threshold and discharging; emergency poweroff', flush=True)
try:
os.sync()
except Exception:
pass
bin_candidates = [
shutil.which('platina-poweroff'),
'/usr/local/sbin/platina-poweroff',
shutil.which('poweroff'),
'/usr/sbin/poweroff',
]
target_bin = next((b for b in bin_candidates if b and (Path(b).exists() or shutil.which(b))), '/usr/sbin/poweroff')
return executor([target_bin], check=True)
candidates = ['/usr/sbin/poweroff', '/sbin/poweroff', shutil.which('poweroff')]
attempted = set()
for command in candidates:
if not command or command in attempted:
continue
attempted.add(command)
try:
return executor([command], check=True, timeout=10)
except (OSError, subprocess.SubprocessError):
continue
raise RuntimeError('No orderly poweroff command succeeded')
def set_charging(battery_dir, charger_dir, enable):
applied = False
val = '1' if enable else '0'
# 1. Try battery charging_enabled
if battery_dir:
for node in ('charging_enabled', 'charge_control_limit_max'):
target = battery_dir / node
if target.exists():
try:
target.write_text(val + '\n')
applied = True
except OSError:
pass
# 2. Try charger module charging_enabled
if charger_dir:
for node in ('charging_enabled',):
target = charger_dir / node
if target.exists():
try:
target.write_text(val + '\n')
applied = True
except OSError:
pass
# 3. Fallback: throttle charger current to 0 on disable
if not enable:
cur_target = charger_dir / 'current_max'
if cur_target.exists():
try:
cur_target.write_text('0\n')
applied = True
except OSError:
pass
else:
cur_target = charger_dir / 'current_max'
if cur_target.exists():
try:
cur_target.write_text('1500000\n')
applied = True
except OSError:
pass
return applied
"""Use charging switches only; USB input-current policy belongs to the driver/USB helper."""
for supply in (battery_dir, charger_dir):
if supply is None:
continue
behaviour = supply / 'charge_behaviour'
try:
supported = behaviour.read_text().replace('[', '').replace(']', '').split()
if {'auto', 'inhibit-charge'} <= set(supported):
behaviour.write_text(('auto' if enable else 'inhibit-charge') + '\n')
return True
except OSError:
pass
target = supply / 'charging_enabled'
if target.exists():
try:
target.write_text(('1' if enable else '0') + '\n')
return True
except OSError:
pass
return False
def main():
@@ -219,16 +202,21 @@ def main():
if capacity is not None:
# Emergency low-battery safety shutdown: prevent brownout filesystem corruption
if policy.should_shutdown(capacity, is_discharging=discharging):
trigger_shutdown()
break
try:
trigger_shutdown()
except RuntimeError as error:
print(f'platina-battery-guard: {error}; retrying next poll', file=sys.stderr, flush=True)
# Keep monitoring until init actually terminates the daemon.
action = policy.evaluate(capacity, temp=temp)
set_charging(battery_dir, charger_dir, action)
if policy.thermal_throttled:
applied = set_charging(battery_dir, charger_dir, action)
if not applied:
status_str = 'Charging control unavailable (no writable charging switch); input limit unchanged'
elif policy.thermal_throttled:
status_str = 'Charging paused (thermal limit exceeded)'
else:
status_str = 'Charging enabled' if action else 'Charging paused (protective threshold reached)'
temp_str = f', temp={temp/10:.1f}°C' if temp is not None and temp > 150 else (f', temp={temp}°C' if temp is not None else '')
temp_str = f', temp={temp/10:.1f}°C' if temp is not None else ''
power_mode = 'discharging' if discharging else 'external-power'
print(f'platina-battery-guard: capacity={capacity}%{temp_str}, power={power_mode}, threshold=[{args.low}%-{args.high}%], state={status_str}', flush=True)
+10 -2
View File
@@ -17,6 +17,7 @@ ROOT = Path(__file__).resolve().parents[1]
RECIPES = ('device-xiaomi-platina', 'firmware-xiaomi-platina', 'linux-postmarketos-qcom-sdm660')
ARCHIVES = {'linux-v6.19.10-sdm660.tar.gz',
'linux-dd1ed52c8ceef4f16715118ed0252fe75adbe71d.tar.gz'}
CAMERA_ARCHIVES = {'libcamera-v0.7.1.tar.gz', 'mesa-26.1.6.tar.xz'}
def run(command, **kwargs):
@@ -77,9 +78,9 @@ def checksums(recipe):
return {name.strip(): value for value, name in rows}
def recipe_checks(directory, external):
def recipe_checks(directory, external, packages=RECIPES):
# Parse only: never evaluate arbitrary APKBUILD shell code on the host.
for name in RECIPES:
for name in packages:
recipe = directory / name / 'APKBUILD'
for filename, expected in checksums(recipe).items():
if filename in external:
@@ -92,6 +93,11 @@ def recipe_checks(directory, external):
install = re.search(r'^install="\$pkgname([^"\n]+)"$', recipe.read_text(), re.M)
if install and not (recipe.parent / (name + install[1])).is_file():
raise ValueError('Missing package install hook: ' + name)
for source in sorted(recipe.parent.glob('*.patch')):
result = subprocess.run(['git', 'apply', '--numstat', str(source.resolve())],
capture_output=True, text=True)
if result.returncode:
raise ValueError('Invalid patch format: ' + name + '/' + source.name)
def check():
@@ -126,6 +132,8 @@ def check():
if digest(branding / 'platina-linux-logo.png') != provenance['sha256']:
raise ValueError('Logo changed without updating provenance')
data = lock()
recipe_checks(ROOT / 'project/camera', CAMERA_ARCHIVES,
packages=('libcamera-headless', 'mesa-freedreno'))
for profile in data['profiles'].values():
recipe_checks(ROOT / profile['ports'], set(data['local_firmware']) | ARCHIVES)
for package, field in zip(RECIPES, ('device_package', 'firmware_package', 'kernel_package')):