feat(boot): carry the loader's host facts over the handoff, trim SMBIOS strings, add board model and firmware version, and name the translator's compile target in StelaHost

This commit is contained in:
Tyler Smith committed 2026-11-11 03:58:59 +00:00
1 parent 704381aba4
commit 2c2850b390
16 files changed
+314 -40

No files matched your search

+6 -4
View File
@@ -1,7 +1,7 @@
{
"StelaVersion": "0.1.0",
"TranslatorID": "3f9a1c2e7b5d4a60",
"TranslatorTarget": "x86_64-baseline+ssse3+sse4.1+sse4.2+pclmulqdq+fma+f16c+popcnt+bmi1+aes+sha+avx+avx2+avx512f",
"TranslatorTarget": "x86_64-baseline+ssse3+sse4.1+sse4.2+pclmulqdq+fma+f16c+popcnt+bmi1+aes+sha+atomic-load16+cx8+cx16+avx2+lzcnt+bmi2+fast-pdep+movbe+gfni",
"CPUBrand": "AMD Ryzen 9 9950X 16-Core Processor",
"CPUVendor": "AuthenticAMD",
"CPUFamily": 26,
@@ -10,12 +10,14 @@
"HostCores": 16,
"HostThreads": 32,
"HostMemoryBytes": 68406829056,
"FirmwareVendor": "American Megatrends",
"FirmwareVendor": "American Megatrends International, LLC.",
"FirmwareRevision": 327712,
"SystemVendor": "ASUS",
"SystemModel": "ROG STRIX X870E-E GAMING WIFI",
"SystemModel": "System Product Name",
"BoardVendor": "ASUSTeK COMPUTER INC.",
"GPU0Chip": "GB203",
"GPU0PCIID": "10de:2c02",
"GPU0VRAMBytes": 17179869184
"GPU0VRAMBytes": 17179869184,
"BoardModel": "ROG STRIX X870E-E GAMING WIFI",
"FirmwareVersion": "1001"
}
@@ -15,6 +15,8 @@
static let value = Font.system(size: 13, weight: .medium)
static let caption = Font.system(size: 11)
static let fill = Color.primary.opacity(0.05)
/// The main window's first size: This PC's five cards without scrolling.
static let window = CGSize(width: 760, height: 820)
}
enum DisplayFormat {
@@ -57,6 +59,8 @@
Text(detail).font(Style.caption).foregroundStyle(.secondary)
}
}
// Long names wrap rather than truncate.
.fixedSize(horizontal: false, vertical: true)
// Fills a grid row's height, so cards side by side end together.
.frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .topLeading)
.padding(Style.padding)
@@ -27,6 +27,8 @@
guard let main = NSApp.windows.first(where: { $0.isVisible && $0 !== about }) else {
throw RenderError.noWindow
}
// At the size a first launch gets, so a cut-off page shows.
main.setContentSize(Style.window)
for (theme, appearance) in [("light", NSAppearance.Name.aqua), ("dark", .darkAqua)] {
NSApp.appearance = NSAppearance(named: appearance)
for window in [main, about] { window.appearance = NSAppearance(named: appearance) }
@@ -22,7 +22,7 @@
await PreviewRenderer.renderIfRequested(model: model)
}
}
.defaultSize(width: 760, height: 720)
.defaultSize(Style.window)
.windowResizability(.contentMinSize)
Window("About This PC", id: AboutThisPC.window) {
ThisPCView(model: model).frame(width: 340).fixedSize()
@@ -65,11 +65,17 @@
label: "Memory", value: HostInventory.bytes(memory),
detail: DisplayFormat.bytes(model.snapshot?.memoryBytes).map { "\($0) for macOS" })
}
if let system = host.system {
Card(label: "System", value: system, detail: host.firmwareVendor.map { "\($0) firmware" })
if let level = host.translationLevel {
let extensions = host.notableExtensions
// A no-break space keeps each dot after its name when the line wraps.
Card(
label: "Translation", value: level,
detail: extensions.isEmpty ? nil : extensions.joined(separator: "\u{00A0}· ")
)
.help(host.translatorTarget ?? "")
}
if let tier = host.instructionTier {
Card(label: "Translation", value: tier)
if let system = host.system {
Card(label: "System", value: system, detail: host.firmware.map { "Firmware \($0)" })
}
}
}
@@ -27,9 +27,11 @@ public struct HostInventory: Codable, Equatable, Sendable {
public var hostThreads: UInt64?
public var hostMemoryBytes: UInt64?
public var firmwareVendor: String?
public var firmwareVersion: String?
public var systemVendor: String?
public var systemModel: String?
public var boardVendor: String?
public var boardModel: String?
public var gpus: [HostGPU] = []
/// Reads the registry dictionary, whose values are strings and numbers.
@@ -55,9 +57,11 @@ public struct HostInventory: Codable, Equatable, Sendable {
hostThreads = number("HostThreads")
hostMemoryBytes = number("HostMemoryBytes")
firmwareVendor = text("FirmwareVendor")
firmwareVersion = text("FirmwareVersion")
systemVendor = text("SystemVendor")
systemModel = text("SystemModel")
boardVendor = text("BoardVendor")
boardModel = text("BoardModel")
var index = 0
while text("GPU\(index)Chip") != nil || text("GPU\(index)PCIID") != nil {
gpus.append(
@@ -76,22 +80,51 @@ public struct HostInventory: Codable, Equatable, Sendable {
return HostInventory(properties: properties)
}
private var targetFeatures: Set<String> {
Set((translatorTarget ?? "").split(separator: "+").map(String.init))
}
/// The widest vector extension the translator emits, from its target id
/// (`x86_64-baseline+ssse3+…+avx2+…`).
public var instructionTier: String? {
guard let translatorTarget else { return nil }
let features = Set(translatorTarget.split(separator: "+").map(String.init))
guard translatorTarget != nil else { return nil }
let tiers: [(String, String)] = [
("avx512f", "AVX-512"), ("avx2", "AVX2"), ("avx", "AVX"), ("sse4.2", "SSE4.2"),
("sse4.1", "SSE4.1"), ("ssse3", "SSSE3"),
]
return tiers.first { features.contains($0.0) }?.1 ?? "SSE2"
return tiers.first { targetFeatures.contains($0.0) }?.1 ?? "SSE2"
}
/// The system's maker and model, falling back to the board's maker.
/// The translator's level in the words x86 users know: the widest vector
/// tier, with FMA when fused multiply-add is in use (`AVX2, FMA`).
public var translationLevel: String? {
guard let instructionTier else { return nil }
return targetFeatures.contains("fma") ? "\(instructionTier), FMA" : instructionTier
}
/// The other notable extensions the translator emits, by their usual names.
public var notableExtensions: [String] {
let features = targetFeatures
let names: [(String, String)] = [
("f16c", "F16C"), ("aes", "AES-NI"), ("sha", "SHA"), ("pclmulqdq", "PCLMUL"),
("bmi2", "BMI2"), ("lzcnt", "LZCNT"), ("popcnt", "POPCNT"), ("movbe", "MOVBE"),
("gfni", "GFNI"),
]
var found = names.filter { features.contains($0.0) }.map(\.1)
if !features.contains("bmi2") && features.contains("bmi1") {
found.insert("BMI1", at: found.firstIndex(of: "LZCNT") ?? found.firstIndex(of: "POPCNT") ?? found.count)
}
return found
}
/// The system's maker and model; a board model when the system's is a
/// placeholder, as on most self-built PCs.
public var system: String? {
let maker = systemVendor ?? boardVendor
switch (maker, systemModel) {
let (maker, model) =
systemModel != nil
? (systemVendor ?? boardVendor, systemModel)
: (systemVendor ?? boardVendor, boardModel)
switch (maker.map(Self.brand), model) {
case let (maker?, model?): return model.hasPrefix(maker) ? model : "\(maker) \(model)"
case let (maker?, nil): return maker
case let (nil, model?): return model
@@ -99,6 +132,25 @@ public struct HostInventory: Codable, Equatable, Sendable {
}
}
/// A maker's brand without its company form (`ASUSTeK COMPUTER INC.`
/// becomes `ASUSTeK`).
static func brand(_ maker: String) -> String {
let forms = [
" computer inc.", " computer inc", " corporation", " corp.", ", inc.", " inc.", " inc",
" co., ltd.", " co.,ltd.", " co., ltd", " ltd.", " gmbh",
]
for form in forms where maker.lowercased().hasSuffix(form) && maker.count > form.count {
return String(maker.dropLast(form.count)).trimmingCharacters(in: .whitespaces)
}
return maker
}
/// The firmware's vendor and version, as far as reported.
public var firmware: String? {
let parts = [firmwareVendor, firmwareVersion].compactMap { $0 }
return parts.isEmpty ? nil : parts.joined(separator: " ")
}
/// Firmware tables often hold placeholders instead of names.
static func meaningful(_ value: String) -> String? {
let trimmed = value.trimmingCharacters(in: .whitespaces)
@@ -144,8 +196,14 @@ public struct HostInventory: Codable, Equatable, Sendable {
lines.append("Memory: \(Self.bytes(hostMemoryBytes))\(guest)")
}
if let system { lines.append("System: \(system)") }
if let firmwareVendor { lines.append("Firmware: \(firmwareVendor)") }
if let instructionTier { lines.append("Translation: \(instructionTier)") }
if let firmware { lines.append("Firmware: \(firmware)") }
if let translationLevel {
lines.append("Translation: \(translationLevel)")
if !notableExtensions.isEmpty {
lines.append("Extensions: \(notableExtensions.joined(separator: ", "))")
}
}
if let translatorTarget { lines.append("Target: \(translatorTarget)") }
if let stelaVersion { lines.append("Stela \(stelaVersion)") }
let presented = [presentedModel, presentedChip].compactMap { $0 }
if !presented.isEmpty { lines.append("Presented as \(presented.joined(separator: ", "))") }
@@ -8,9 +8,12 @@ final class HostInventoryTests: XCTestCase {
"StelaVersion": "0.1.0", "CPUBrand": "AMD Ryzen 9 9950X 16-Core Processor",
"CPUVendor": "AuthenticAMD", "HostCores": 16, "HostThreads": NSNumber(value: 32),
"HostMemoryBytes": UInt64(68_406_829_056), "FirmwareVendor": "American Megatrends",
"SystemVendor": "ASUS", "SystemModel": "System Product Name", "BoardVendor": "ASUSTeK",
"FirmwareVersion": "1001", "SystemVendor": "ASUS", "SystemModel": "System Product Name",
"BoardVendor": "ASUSTeK", "BoardModel": "ROG STRIX X870E-E GAMING WIFI",
"GPU0Chip": "GB203", "GPU0PCIID": "10de:2c02", "GPU0VRAMBytes": UInt64(17_179_869_184),
"TranslatorTarget": "x86_64-baseline+ssse3+sse4.1+sse4.2+popcnt+avx+avx2+avx512f",
"TranslatorTarget":
"x86_64-baseline+ssse3+sse4.1+sse4.2+pclmulqdq+fma+f16c+popcnt+bmi1+aes+sha+atomic-load16"
+ "+cx8+cx16+avx2+lzcnt+bmi2+fast-pdep+movbe+gfni",
"Unknown": "ignored",
]
@@ -20,9 +23,17 @@ final class HostInventoryTests: XCTestCase {
XCTAssertEqual(host.hostCores, 16)
XCTAssertEqual(host.hostThreads, 32)
XCTAssertEqual(host.gpus.first?.name, "NVIDIA GeForce RTX 5080")
XCTAssertEqual(host.instructionTier, "AVX-512")
// A placeholder model leaves the maker alone.
XCTAssertEqual(host.system, "ASUS")
XCTAssertEqual(host.instructionTier, "AVX2")
XCTAssertEqual(host.translationLevel, "AVX2, FMA")
XCTAssertEqual(
host.notableExtensions,
["F16C", "AES-NI", "SHA", "PCLMUL", "BMI2", "LZCNT", "POPCNT", "MOVBE", "GFNI"])
// A placeholder system model gives way to the board's.
XCTAssertEqual(host.system, "ASUS ROG STRIX X870E-E GAMING WIFI")
XCTAssertEqual(HostInventory.brand("ASUSTeK COMPUTER INC."), "ASUSTeK")
XCTAssertEqual(HostInventory.brand("Micro-Star International Co., Ltd."), "Micro-Star International")
XCTAssertEqual(HostInventory.brand("Inc."), "Inc.")
XCTAssertEqual(host.firmware, "American Megatrends 1001")
XCTAssertEqual(HostInventory.bytes(68_406_829_056), "64 GB")
XCTAssertEqual(HostInventory.bytes(17_179_869_184), "16 GB")
}
@@ -31,12 +42,22 @@ final class HostInventoryTests: XCTestCase {
let host = HostInventory(properties: ["GPU0Chip": "AD102", "GPU0PCIID": "10de:ffff"])
XCTAssertNil(host.cpuBrand)
XCTAssertNil(host.instructionTier)
XCTAssertNil(host.translationLevel)
XCTAssertNil(host.system)
XCTAssertNil(host.firmware)
XCTAssertEqual(host.gpus.first?.name, "NVIDIA AD102")
XCTAssertNil(host.gpus.first?.vramBytes)
XCTAssertEqual(
HostInventory(properties: ["TranslatorTarget": "x86_64-baseline+ssse3+sse4.1+sse4.2+avx2"])
.instructionTier, "AVX2")
.translationLevel, "AVX2")
let legacy = HostInventory(properties: [
"TranslatorTarget": "x86_64-baseline+ssse3+sse4.1+sse4.2+popcnt+bmi1+cx16"
])
XCTAssertEqual(legacy.translationLevel, "SSE4.2")
XCTAssertEqual(legacy.notableExtensions, ["BMI1", "POPCNT"])
XCTAssertEqual(
HostInventory(properties: ["TranslatorTarget": "x86_64-baseline+avx512f+avx2+fma"])
.translationLevel, "AVX-512, FMA")
XCTAssertEqual(
HostInventory(properties: ["SystemVendor": "Framework", "SystemModel": "Framework Desktop"])
.system, "Framework Desktop")
@@ -54,9 +75,11 @@ final class HostInventoryTests: XCTestCase {
Processor: AMD Ryzen 9 9950X 16-Core Processor, 16 cores, 32 threads
Graphics: NVIDIA GeForce RTX 5080, 16 GB
Memory: 64 GB (12 GB for macOS)
System: ASUS
Firmware: American Megatrends
Translation: AVX-512
System: ASUS ROG STRIX X870E-E GAMING WIFI
Firmware: American Megatrends 1001
Translation: AVX2, FMA
Extensions: F16C, AES-NI, SHA, PCLMUL, BMI2, LZCNT, POPCNT, MOVBE, GFNI
Target: x86_64-baseline+ssse3+sse4.1+sse4.2+pclmulqdq+fma+f16c+popcnt+bmi1+aes+sha+atomic-load16+cx8+cx16+avx2+lzcnt+bmi2+fast-pdep+movbe+gfni
Stela 0.1.0
Presented as Mac14,3, Apple M2
""")
@@ -51,6 +51,45 @@ pub fn vendor(words: [u32; 3]) -> String {
.into()
}
/// An SMBIOS string as text: without the NUL terminator the table walk keeps
/// and without padding spaces, or `None` when nothing is left.
pub fn smbios_text(value: &[u8]) -> Option<&[u8]> {
let end = value
.iter()
.rposition(|&byte| byte != 0 && !byte.is_ascii_whitespace())?
+ 1;
let start = value
.iter()
.position(|&byte| byte != 0 && !byte.is_ascii_whitespace())?;
Some(&value[start..end])
}
/// The string at byte `offset` of the first SMBIOS structure of type `kind`
/// in `table` (DSP0134 §6.1.3), or `None` when there is none or the table
/// ends early. Callers name only model and version fields: type 0's BIOS
/// version (offset 5), type 2's product (offset 5); never serial numbers,
/// UUIDs or asset tags.
pub fn smbios_string(table: &[u8], kind: u8, offset: usize) -> Option<&[u8]> {
let mut at = 0usize;
while let Some(head) = table.get(at..at + 4) {
let length = usize::from(head[1]);
let strings = table.get(at + length..)?;
let end = strings.windows(2).position(|pair| pair == [0, 0])?;
if head[0] == kind {
let index = usize::from(*table.get(at + offset).filter(|_| offset < length)?);
return strings[..end]
.split(|&byte| byte == 0)
.nth(index.checked_sub(1)?)
.filter(|value| !value.is_empty());
}
if head[0] == 127 {
return None;
}
at += length + end + 2;
}
None
}
/// `HOST version=… cpu="…" family=… model=… stepping=… ram=… firmware="…"`.
pub fn line(identity: &Identity<'_>) -> String {
let (family, model, _) = signature_parts(identity.signature);
@@ -115,4 +154,36 @@ mod tests {
});
assert!(zen.contains("family=0x19 model=0x61 stepping=2"), "{zen}");
}
#[test]
fn smbios_strings_are_read_by_structure_type_and_offset() {
// Type 0 with vendor and version strings, type 2 with a product but no
// version, then the end structure.
let mut table = alloc::vec![0, 0x18, 0, 0, 1, 2, 0, 0];
table.resize(0x18, 0);
table.extend(b"AMI\x002.02\x00\x00");
table.extend([2, 8, 1, 0, 1, 2, 0, 0]);
table.extend(b"ASUSTeK\x00ROG STRIX\x00\x00");
table.extend([127, 4, 2, 0, 0, 0]);
assert_eq!(smbios_string(&table, 0, 5), Some(&b"2.02"[..]));
assert_eq!(smbios_string(&table, 2, 5), Some(&b"ROG STRIX"[..]));
assert_eq!(smbios_string(&table, 2, 6), None);
assert_eq!(smbios_string(&table, 2, 9), None);
assert_eq!(smbios_string(&table, 3, 4), None);
assert_eq!(smbios_string(&table[..20], 2, 5), None);
}
#[test]
fn smbios_text_drops_the_terminator_and_padding() {
// The table walk keeps each string's NUL (QEMU's type 1 gave
// "QEMU?" in build-54's record).
assert_eq!(smbios_text(b"QEMU\0"), Some(&b"QEMU"[..]));
assert_eq!(
smbios_text(b"Standard PC (Q35 + ICH9, 2009)\0"),
Some(&b"Standard PC (Q35 + ICH9, 2009)"[..])
);
assert_eq!(smbios_text(b" ASUS \0\0"), Some(&b"ASUS"[..]));
assert_eq!(smbios_text(b" \0"), None);
assert_eq!(smbios_text(b""), None);
}
}
+8 -1
View File
@@ -211,6 +211,7 @@ fn start(handoff: u64) -> Started {
.map(|screen| screen.relocated(layout::physical(screen.base as u64) as usize)),
);
crate::status::replay(&handoff.history[..handoff.history_bytes]);
crate::host_inventory::restore(&handoff.host[..handoff.host_bytes.min(handoff.host.len())]);
output::arguments(format_args!(
"STELA SYSTEM ENGINE window={:#x} placement={:?} tsc_hz={} guest_ranges={} \
heap={}M code={}M pool={}M\n",
@@ -814,7 +815,6 @@ fn run_guest(boot: Boot<'_>, mut host: OpenedHost, mut storage: Storage) -> ! {
if !gates.is_empty() {
hidden_devices.extend(stela_loader::devices::hide_agx(&mut assigned.tree));
}
describe_host(&mut assigned.tree, gates.len(), target);
gates
})
.unwrap_or_default();
@@ -830,6 +830,13 @@ fn run_guest(boot: Boot<'_>, mut host: OpenedHost, mut storage: Storage) -> ! {
)
}
.unwrap_or_else(|error| output::fatal(error));
// The translator compiles for the canonical RAM's target (the BSP's live
// features under the common worker ceiling), not the board profile's
// ID-register list in `target`.
#[cfg(feature = "nvk")]
if let Some(assigned) = &mut assigned {
describe_host(&mut assigned.tree, gpu_gates.len(), canonical_ram.target());
}
if let Some(assigned) = &assigned {
board = Some(assigned_board(
handoff,
+4
View File
@@ -40,6 +40,10 @@ pub struct Handoff {
/// with (`status::replay`).
pub history: [u8; crate::status::HISTORY_BYTES],
pub history_bytes: usize,
/// The loader's facts about the PC, as a host record, which the engine
/// takes up (`host_inventory::restore`).
pub host: [u8; crate::host_inventory::HANDOFF_BYTES],
pub host_bytes: usize,
/// The partition holding the USB's boot log the loader keeps
/// (`log_file`), which the engine writes on to.
pub log_partition: Option<[u8; 16]>,
+12 -4
View File
@@ -110,12 +110,20 @@ fn record_board(capture: &Capture) {
let Ok(system) = identity(parsed, &bytes[length..]) else {
return;
};
let table = &bytes[length..];
let observed = |value| match value {
Observation::Value(value) => Some(value),
_ => None,
};
use stela_boot_core::host_identity::{smbios_string, smbios_text};
for (key, value) in [
("SystemVendor", system.system_vendor),
("SystemModel", system.product_name),
("BoardVendor", system.board_vendor),
("SystemVendor", observed(system.system_vendor)),
("SystemModel", observed(system.product_name)),
("BoardVendor", observed(system.board_vendor)),
("BoardModel", smbios_string(table, 2, 5)),
("FirmwareVersion", smbios_string(table, 0, 5)),
] {
if let Observation::Value(value) = value {
if let Some(value) = value.and_then(smbios_text) {
crate::host_inventory::text(key, alloc::string::String::from_utf8_lossy(value));
}
}
+37 -4
View File
@@ -3,6 +3,10 @@
//! writes them into the StelaGPU gate nodes' `stela-host` property
//! (`stela_loader::stela_gpu::encode_host`). Only model-level facts: no
//! serial numbers, addresses or other identifiers of the machine or person.
//!
//! The engine runs from a relocated copy of the image, whose statics start
//! afresh, so the loader's facts (CPU, RAM, firmware, SMBIOS) cross in the
//! handoff ([`save`], [`restore`]) as the status history does.
use alloc::{string::String, vec::Vec};
use core::cell::RefCell;
use stela_loader::stela_gpu::HostValue;
@@ -35,10 +39,6 @@ pub fn number(key: impl Into<String>, value: u64) {
}
/// Every fact recorded so far, in recording order.
#[cfg_attr(
not(feature = "nvk"),
expect(dead_code, reason = "only the StelaGPU gate nodes carry the record")
)]
pub fn entries() -> Vec<(String, HostValue)> {
ENTRIES
.0
@@ -46,3 +46,36 @@ pub fn entries() -> Vec<(String, HostValue)> {
.map(|entries| entries.clone())
.unwrap_or_default()
}
/// The handoff's room for the loader's facts.
pub const HANDOFF_BYTES: usize = 2048;
/// Writes the facts so far into `into` as a host record, whole lines only,
/// answering its length; facts past the room are left out.
pub fn save(into: &mut [u8; HANDOFF_BYTES]) -> usize {
let Ok(record) = stela_loader::stela_gpu::encode_host(&entries()) else {
return 0;
};
let mut bytes = record.len().min(HANDOFF_BYTES);
while bytes > 0 && bytes < record.len() && record[bytes - 1] != b'\n' {
bytes -= 1;
}
into[..bytes].copy_from_slice(&record[..bytes]);
bytes
}
/// Records the facts a loader [`save`]d, keeping any recorded since.
pub fn restore(saved: &[u8]) {
let Ok(restored) = stela_loader::stela_gpu::decode_host(saved) else {
return;
};
for (key, value) in restored {
let known = ENTRIES
.0
.try_borrow()
.is_ok_and(|entries| entries.iter().any(|(entry, _)| *entry == key));
if !known {
record(key, value);
}
}
}
+4
View File
@@ -862,6 +862,8 @@ fn load(
// Keep this post-EBS boundary when the relocated engine replays status.
let mut history = [0; crate::status::HISTORY_BYTES];
let history_bytes = crate::status::history(&mut history);
let mut host = [0; crate::host_inventory::HANDOFF_BYTES];
let host_bytes = crate::host_inventory::save(&mut host);
let handoff_phase::GuestMemory {
ranges: guest,
count,
@@ -886,6 +888,8 @@ fn load(
screen,
history,
history_bytes,
host,
host_bytes,
log_partition: log.map(|guid| guid.0),
tsc_hz,
tsc_source: crate::firmware::tsc_source(),
+54 -2
View File
@@ -147,7 +147,7 @@ pub const HOST_PROPERTY: &str = "stela-host";
/// only the versions it knows; a new field is a new line, not a new version.
pub const HOST_FORMAT: &str = "stela-host 1";
/// The longest text value; a longer one is cut there.
pub const HOST_TEXT_BYTES: usize = 120;
pub const HOST_TEXT_BYTES: usize = 255;
/// One value of the host record.
#[derive(Debug, Clone, PartialEq, Eq)]
@@ -170,8 +170,9 @@ pub fn encode_host(entries: &[(String, HostValue)]) -> Result<Vec<u8>> {
match value {
HostValue::Number(number) => record.push_str(&format!("n {key}={number}\n")),
HostValue::Text(text) => {
// C strings keep their terminator; it is not part of the text.
let text: String = text
.trim()
.trim_matches(|c: char| c.is_whitespace() || c == '\0')
.chars()
.map(|c| {
if c == ' ' || c.is_ascii_graphic() {
@@ -189,6 +190,32 @@ pub fn encode_host(entries: &[(String, HostValue)]) -> Result<Vec<u8>> {
Ok(record.into_bytes())
}
/// The entries of a record [`encode_host`] wrote, in order. A record of
/// another version is refused; a malformed line is skipped.
pub fn decode_host(record: &[u8]) -> Result<Vec<(String, HostValue)>> {
let text = core::str::from_utf8(record).map_err(|_| refuse!("a host record is not text"))?;
let mut lines = text.lines();
require!(
lines.next() == Some(HOST_FORMAT),
"a host record is not version 1"
);
Ok(lines
.filter_map(|line| {
let (kind, rest) = line.split_at_checked(2)?;
let (key, value) = rest.split_once('=')?;
if key.is_empty() || !key.bytes().all(|b| b.is_ascii_alphanumeric()) {
return None;
}
let value = match kind {
"n " => HostValue::Number(value.parse().ok()?),
"s " => HostValue::Text(value.into()),
_ => return None,
};
Some((key.into(), value))
})
.collect())
}
/// Sets GPU `index`'s gate node's [`HOST_PROPERTY`] to `record`.
pub fn set_host(tree: &mut DeviceTree, index: usize, record: Vec<u8>) -> Result<()> {
tree.set_property(&format!("{ARM_IO}/stela-gpu{index}"), HOST_PROPERTY, record)
@@ -341,12 +368,37 @@ mod tests {
core::str::from_utf8(&record).unwrap(),
"stela-host 1\ns CPUBrand=AMD Ryzen 9 9950X?16-Core?\nn HostThreads=32\n"
);
// A kept C terminator is dropped, not shown as a replacement mark.
assert_eq!(
encode_host(&[("SystemVendor".into(), HostValue::Text("QEMU\0".into()))]).unwrap(),
b"stela-host 1\ns SystemVendor=QEMU\n"
);
// A full translator target fits whole.
let target = "x86_64-baseline+ssse3+sse4.1+sse4.2+pclmulqdq+fma+f16c+popcnt+bmi1+aes+sha\
+atomic-load16+cx8+cx16+avx2+lzcnt+bmi2+fast-pdep+movbe+gfni+avx512f+avx512bw";
let entry = [("TranslatorTarget".into(), HostValue::Text(target.into()))];
assert_eq!(decode_host(&encode_host(&entry).unwrap()).unwrap(), entry);
let long = [("A".into(), HostValue::Text("x".repeat(500)))];
assert_eq!(
encode_host(&long).unwrap().len(),
13 + 4 + HOST_TEXT_BYTES + 1
);
assert!(encode_host(&[("Bad key".into(), HostValue::Number(1))]).is_err());
assert_eq!(
decode_host(&record).unwrap(),
[
(
"CPUBrand".into(),
HostValue::Text("AMD Ryzen 9 9950X?16-Core?".into())
),
("HostThreads".into(), HostValue::Number(32)),
]
);
assert!(decode_host(b"stela-host 2\nn A=1\n").is_err());
assert_eq!(
decode_host(b"stela-host 1\nn A=x\nq B=1\ns =1\ns C=ok\n").unwrap(),
[("C".into(), HostValue::Text("ok".into()))]
);
let mut tree = tree(vec![]);
place_gpu_gate(&mut tree, 0, WINDOW).unwrap();
set_host(&mut tree, 0, record.clone()).unwrap();
+1 -1
View File
@@ -10,7 +10,7 @@
#pragma once
#define STELA_HOST_PROPERTY "stela-host"
#define STELA_HOST_TEXT_BYTES 120
#define STELA_HOST_TEXT_BYTES 255
#define STELA_HOST_KEY_BYTES 40
/* One entry: its key, and its number or its text, neither NUL-terminated. */
+2 -2
View File
@@ -335,7 +335,7 @@ fn the_kext_reads_the_records_stela_efi_writes() {
),
("HostThreads".into(), HostValue::Number(32)),
("HostMemoryBytes".into(), HostValue::Number(u64::MAX)),
("SystemModel".into(), HostValue::Text("x".repeat(300))),
("SystemModel".into(), HostValue::Text("x".repeat(400))),
])
.unwrap();
let file = built.path().join("record");
@@ -347,7 +347,7 @@ fn the_kext_reads_the_records_stela_efi_writes() {
format!(
"CPUBrand|s|AMD Ryzen 9 9950X 16-Core Processor\nHostThreads|n|32\n\
HostMemoryBytes|n|18446744073709551615\nSystemModel|s|{}\n",
"x".repeat(120)
"x".repeat(stela_loader::stela_gpu::HOST_TEXT_BYTES)
)
);
}