fix(monitors): 限制外部报告输出并可靠终止超时子进程

This commit is contained in:
2026-11-03 23:28:19 +08:00
parent def3b1e130
commit a96d188abe
9 changed files with 171 additions and 39 deletions
+5 -20
View File
@@ -2,25 +2,10 @@ import Foundation
nonisolated enum DiskSMARTReader {
static func readReport() async -> DiskHealthMetrics? {
await withCheckedContinuation { continuation in
DispatchQueue.global(qos: .utility).async {
guard let values = try? URL(fileURLWithPath: NSHomeDirectory()).resourceValues(forKeys: [.volumeURLKey]),
let volume = values.volume else { continuation.resume(returning: nil); return }
let process = Process()
process.executableURL = URL(fileURLWithPath: "/usr/sbin/diskutil")
process.arguments = ["info", "-plist", volume.path]
let pipe = Pipe()
process.standardOutput = pipe
process.standardError = FileHandle.nullDevice
do { try process.run() }
catch { continuation.resume(returning: nil); return }
let deadline = DispatchWorkItem { if process.isRunning { process.terminate() } }
DispatchQueue.global(qos: .utility).asyncAfter(deadline: .now() + 10, execute: deadline)
let data = pipe.fileHandleForReading.readDataToEndOfFile()
process.waitUntilExit()
deadline.cancel()
continuation.resume(returning: process.terminationStatus == 0 && data.count <= 262_144 ? DiskHealthReport.parse(data) : nil)
}
}
guard let values = try? URL(fileURLWithPath: NSHomeDirectory()).resourceValues(forKeys: [.volumeURLKey]),
let volume = values.volume,
let data = await BoundedProcess.read(executable: URL(fileURLWithPath: "/usr/sbin/diskutil"),
arguments: ["info", "-plist", volume.path]) else { return nil }
return DiskHealthReport.parse(data)
}
}
+2
View File
@@ -69,3 +69,5 @@ CPU / GPU / 风扇合并为一次只读 XPC 请求,按到期类别选择读取
资源显示默认采用静态数字、曲线和进度条;风扇不创建 TimelineView。移除曲线追加过渡任务,保持原有缺失值、断点和悬浮语义。此措施不代表面板内存预算已通过;剩余峰值见效率实施记录。
`PanelResourceAudit` 仅在 `KYMO_RESOURCE_AUDIT=1` 时驱动真实面板测试生命周期,App 只装配调用。正常启动不创建测试任务;该入口不是鼠标 / AX 交互验证。诊断日志仍需 `KYMO_DIAGNOSTICS=1` 显式开启。
外部 `system_profiler` / `diskutil` 报告共用 Core 的 `BoundedProcess`(同时编入 XPC Target)。utility 队列阻塞于输出 / 取消 / 退出事件,累计保留输出不超过 256 KiB,最多多读 1 字节判断溢出;10 秒截止、输出超限或调用 Task 取消时 SIGKILL 本轮直接子进程并等待回收。子进程关闭 stdout 后不退出也受截止约束。取消管道唤醒 poll,无周期检查计时器;不杀进程组或其他进程。此取消能力不代表 XPC 连接断开已传播到服务内部 Task,暂停后已启动慢报告的上层取消仍需完善。
+2
View File
@@ -50,3 +50,5 @@
## 兼容性边界
AppleSMC 和 GPU 驱动字段不是稳定公开的跨机型指标接口,缺失时应降级。磁盘报告、电池报告与进程读取受系统版本、硬件和沙盒权限影响。新增支持必须有实际采样和合理性核对,不从核心数、总利用率或其他传感器推导不存在的读数。
慢报告输出通过共享 `BoundedProcess` 流式限制为 256 KiB(检测溢出多读至多 1 字节),截止 10 秒;超限、超时和直接调用 Task 取消会强制终止并回收本轮子进程,失败按原缓存周期退避。不会先无限读完再判大小。
+2
View File
@@ -275,3 +275,5 @@ swiftc -parse-as-library kymo/Core/Services/LanguagePreferences.swift kymo/UI/Co
显式开启的真实面板入口、组件隔离参数与首批证据见[轻量化实施记录](efficiency-first-batch.md)。`SensorScheduleChecks` 核对分能力失败退避、封顶与恢复;`SamplingIntervalChecks` 同时核对隐藏无消费者零采样、旧偏好迁移、显式开关与重开断点。它们不替代真实签名 XPC 故障注入、完整面板输入或长期功耗验收。
Release 配置由各 Target 在签名前 strip,保留包外 dSYM;测量必须对最终签名包统计文件逻辑大小、相同格式 ZIP 与资源 rendition,不能使用只改 DerivedData 的手工 strip 结果。首次局部结果低于包大小预算,不代表内存 / CPU / W / 8 小时已经通过。
`BoundedProcessChecks` 实际启动本检查程序的子模式,验证精确上限 / 超限、大输出、非零退出、关闭 stdout 后挂起、忽略 SIGTERM 的静默挂起、截止时间、启动前与启动后取消,以及直接子进程全部回收。独立运行不需要 GUI、网络或管理员权限;禁止以真实系统进程充当终止测试对象。
+4
View File
@@ -7,6 +7,7 @@
objects = {
/* Begin PBXBuildFile section */
CC1000000000000000000001 /* BoundedProcess.swift in Sources */ = {isa = PBXBuildFile; fileRef = CC1000000000000000000002 /* BoundedProcess.swift */; };
BB000000000000000000001E /* main.swift in Sources */ = {isa = PBXBuildFile; fileRef = BB000000000000000000000A /* main.swift */; };
BB000000000000000000001F /* DiskSMARTReader.swift in Sources */ = {isa = PBXBuildFile; fileRef = BB000000000000000000000B /* DiskSMARTReader.swift */; };
BB0000000000000000000020 /* SMARTServiceProtocol.swift in Sources */ = {isa = PBXBuildFile; fileRef = BB000000000000000000000C /* SMARTServiceProtocol.swift */; };
@@ -40,6 +41,7 @@
/* End PBXCopyFilesBuildPhase section */
/* Begin PBXFileReference section */
CC1000000000000000000002 /* BoundedProcess.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; name = BoundedProcess.swift; path = kymo/Core/Services/BoundedProcess.swift; sourceTree = SOURCE_ROOT; };
BB0000000000000000000002 /* SMARTService.xpc */ = {isa = PBXFileReference; explicitFileType = "wrapper.xpc-service"; includeInIndex = 0; path = SMARTService.xpc; sourceTree = BUILT_PRODUCTS_DIR; };
BB000000000000000000000A /* main.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; name = main.swift; path = SMARTService/main.swift; sourceTree = SOURCE_ROOT; };
BB000000000000000000000B /* DiskSMARTReader.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; name = DiskSMARTReader.swift; path = SMARTService/DiskSMARTReader.swift; sourceTree = SOURCE_ROOT; };
@@ -105,6 +107,7 @@
BB000000000000000000000B /* DiskSMARTReader.swift */,
BB000000000000000000000C /* SMARTServiceProtocol.swift */,
BB000000000000000000000D /* CodeIdentity.swift */,
CC1000000000000000000002 /* BoundedProcess.swift */,
BB000000000000000000000E /* DiskHealthMetrics.swift */,
BB000000000000000000000F /* DiskHealthReport.swift */,
BB0000000000000000000010 /* CPUTemperatureMonitor.swift */,
@@ -222,6 +225,7 @@
BB000000000000000000001F /* DiskSMARTReader.swift in Sources */,
BB0000000000000000000020 /* SMARTServiceProtocol.swift in Sources */,
BB0000000000000000000021 /* CodeIdentity.swift in Sources */,
CC1000000000000000000001 /* BoundedProcess.swift in Sources */,
BB0000000000000000000022 /* DiskHealthMetrics.swift in Sources */,
BB0000000000000000000023 /* DiskHealthReport.swift in Sources */,
BB0000000000000000000025 /* CPUTemperatureMonitor.swift in Sources */,
@@ -33,24 +33,8 @@ actor SystemBatteryHealthMonitor {
}
nonisolated private static func readReport() async -> Double? {
await withCheckedContinuation { continuation in
// Process/pipe waits use a utility queue rather than the cooperative executor.
DispatchQueue.global(qos: .utility).async {
let process = Process()
process.executableURL = URL(fileURLWithPath: "/usr/sbin/system_profiler")
process.arguments = ["SPPowerDataType", "-json", "-detailLevel", "mini", "-timeout", "5"]
let pipe = Pipe()
process.standardOutput = pipe
process.standardError = FileHandle.nullDevice
do { try process.run() }
catch { continuation.resume(returning: nil); return }
let deadline = DispatchWorkItem { if process.isRunning { process.terminate() } }
DispatchQueue.global(qos: .utility).asyncAfter(deadline: .now() + 10, execute: deadline)
let data = pipe.fileHandleForReading.readDataToEndOfFile()
process.waitUntilExit()
deadline.cancel()
continuation.resume(returning: process.terminationStatus == 0 && data.count <= 262_144 ? parse(data) : nil)
}
}
guard let data = await BoundedProcess.read(executable: URL(fileURLWithPath: "/usr/sbin/system_profiler"),
arguments: ["SPPowerDataType", "-json", "-detailLevel", "mini", "-timeout", "5"]) else { return nil }
return parse(data)
}
}
+96
View File
@@ -0,0 +1,96 @@
import Foundation
import Darwin
/// Short read-only reports. Both retained output and the child lifetime are bounded.
nonisolated enum BoundedProcess {
static func read(executable: URL, arguments: [String], limit: Int = 262_144,
timeout: TimeInterval = 10) async -> Data? {
guard limit >= 0, limit < Int.max, timeout.isFinite, timeout > 0 else { return nil }
let wake = Wakeup()
return await withTaskCancellationHandler {
await withCheckedContinuation { continuation in
DispatchQueue.global(qos: .utility).async {
defer { wake.close() }
continuation.resume(returning: collect(executable: executable, arguments: arguments,
limit: limit, timeout: timeout, wake: wake))
}
}
} onCancel: { wake.cancel() }
}
private static func collect(executable: URL, arguments: [String], limit: Int,
timeout: TimeInterval, wake: Wakeup) -> Data? {
guard !wake.cancelled else { return nil }
let process = Process()
let output = Pipe()
process.executableURL = executable
process.arguments = arguments
process.standardOutput = output
process.standardError = FileHandle.nullDevice
process.terminationHandler = { _ in wake.signal() }
do { try process.run() } catch { return nil }
try? output.fileHandleForWriting.close()
defer {
// Only the direct child we launched; never signal a process group or unrelated PID.
if process.isRunning { Darwin.kill(process.processIdentifier, SIGKILL) }
process.waitUntilExit()
process.terminationHandler = nil
try? output.fileHandleForReading.close()
}
let deadline = ProcessInfo.processInfo.systemUptime + timeout
var data = Data()
var buffer = [UInt8](repeating: 0, count: min(8192, limit + 1))
var eof = false
while true {
guard !wake.cancelled else { return nil }
if eof && !process.isRunning { return process.terminationStatus == 0 ? data : nil }
let remaining = deadline - ProcessInfo.processInfo.systemUptime
guard remaining > 0 else { return nil }
var fds = [pollfd(fd: eof ? -1 : output.fileHandleForReading.fileDescriptor, events: Int16(POLLIN), revents: 0),
pollfd(fd: wake.reader, events: Int16(POLLIN), revents: 0)]
let ready = poll(&fds, nfds_t(fds.count), Int32(min(Double(Int32.max), ceil(remaining * 1000))))
if ready < 0 { if errno == EINTR { continue }; return nil }
if ready == 0 { return nil }
if fds[1].revents != 0 { wake.drain() }
guard !wake.cancelled else { return nil }
if fds[0].revents & Int16(POLLERR | POLLNVAL) != 0 { return nil }
if fds[0].revents & Int16(POLLIN | POLLHUP) != 0 {
// One extra byte detects overflow without ever retaining oversized output.
let count = Darwin.read(output.fileHandleForReading.fileDescriptor, &buffer, min(buffer.count, limit - data.count + 1))
if count < 0 { if errno == EINTR { continue }; return nil }
if count == 0 { eof = true; continue }
guard count <= limit - data.count else { return nil }
data.append(contentsOf: buffer.prefix(count))
}
}
}
/// A pipe wakes blocking poll on cancellation or exit; no periodic polling timer.
private final class Wakeup: @unchecked Sendable {
private let lock = NSLock()
private let pipe = Pipe()
private var didCancel = false
private var closed = false
var reader: Int32 { pipe.fileHandleForReading.fileDescriptor }
var cancelled: Bool { lock.lock(); defer { lock.unlock() }; return didCancel }
func cancel() { notify(cancel: true) }
func signal() { notify(cancel: false) }
private func notify(cancel: Bool) {
lock.lock(); defer { lock.unlock() }
guard !closed else { return }
if cancel { didCancel = true }
var byte: UInt8 = 1
_ = Darwin.write(pipe.fileHandleForWriting.fileDescriptor, &byte, 1)
}
func drain() {
var bytes = [UInt8](repeating: 0, count: 16)
_ = Darwin.read(reader, &bytes, bytes.count)
}
func close() {
lock.lock(); defer { lock.unlock() }
closed = true
try? pipe.fileHandleForReading.close()
try? pipe.fileHandleForWriting.close()
}
}
}
+56
View File
@@ -0,0 +1,56 @@
import Foundation
import Darwin
@main struct BoundedProcessChecks {
static func main() async throws {
if CommandLine.arguments.count > 1 {
switch CommandLine.arguments[1] {
case "valid": FileHandle.standardOutput.write(Data("report".utf8)); return
case "large":
let bytes = [UInt8](repeating: 42, count: 8192)
for _ in 0..<1024 { _ = bytes.withUnsafeBytes { Darwin.write(1, $0.baseAddress, $0.count) } }
return
case "fail": exit(7)
case "closed": Darwin.close(1); fallthrough
default:
signal(SIGTERM, SIG_IGN)
while true { pause() }
}
}
let executable = URL(fileURLWithPath: CommandLine.arguments[0])
func run(_ mode: String, limit: Int = 262_144, timeout: Double = 2) async -> Data? {
await BoundedProcess.read(executable: executable, arguments: [mode], limit: limit, timeout: timeout)
}
let valid = await run("valid")
precondition(valid == Data("report".utf8))
let exact = await run("valid", limit: 6)
precondition(exact == valid)
let tooSmall = await run("valid", limit: 5)
precondition(tooSmall == nil)
let large = await run("large", limit: 4096)
precondition(large == nil)
let failed = await run("fail")
precondition(failed == nil)
for mode in ["hang", "closed"] {
let start = ContinuousClock.now
let result = await run(mode, timeout: 0.2)
precondition(result == nil && start.duration(to: .now) < .seconds(2))
}
let cancelStart = ContinuousClock.now
let task = Task { await run("hang", timeout: 20) }
try await Task.sleep(for: .milliseconds(100))
task.cancel()
let cancelled = await task.value
precondition(cancelled == nil && cancelStart.duration(to: .now) < .seconds(2))
let beforeStart = Task { await run("hang", timeout: 20) }
beforeStart.cancel()
let early = await beforeStart.value
precondition(early == nil)
let missing = await BoundedProcess.read(executable: URL(fileURLWithPath: "/not/a/kymo/executable"), arguments: [])
precondition(missing == nil)
var status: Int32 = 0
precondition(waitpid(-1, &status, WNOHANG) == -1 && errno == ECHILD,
"Every direct test child must be reaped before the request completes")
print("PASS: bounded/exact output, overflow, failure, missing executable, closed-output hang, hard deadline, early/active cancellation and child reaping")
}
}
+1
View File
@@ -18,6 +18,7 @@ CHECKS = {name: list(CORE) for name in (
"SamplingChecks", "SamplingIntervalChecks", "UnifiedPanelChecks", "MemoryChecks",
"GPUStatisticsChecks", "StageCChecks", "MachPortChecks")}
CHECKS.update({
"BoundedProcessChecks": ["kymo/Core/Services/BoundedProcess.swift"],
"SensorScheduleChecks": ["kymo/Core/Services/SensorSchedule.swift"],
"TrendScrollChecks": CORE + ["kymo/UI/Charts/TrendScroll.swift"],
"CPUCoreGridChecks": ["kymo/Features/MenuBar/CPUCoreGrid.swift", "kymo/Core/Services/CPUCoreTopology.swift",