use crate::asm::*; use crate::battery::{Info, Status}; use crate::resource::Resource; use crate::{Error, Host, Namespace, Path, Space, Value}; use alloc::collections::BTreeMap; use alloc::string::{String, ToString}; use alloc::vec; use alloc::vec::Vec; /// A machine: an embedded controller's 256 bytes, I/O ports, notes taken. #[derive(Default)] struct Fake { ec: Vec, io: BTreeMap, notified: Vec<(String, u64)>, reads: usize, } impl Fake { fn new() -> Fake { Fake { ec: vec![0; 256], ..Fake::default() } } } impl Host for Fake { fn read(&mut self, space: Space, address: u64, bits: u8) -> u64 { self.reads += 1; match space { Space::EmbeddedControl => u64::from(self.ec[address as usize & 0xff]), _ => self.io.get(&address).copied().unwrap_or(0) & (u64::MAX >> (64 - bits)), } } fn write(&mut self, space: Space, address: u64, bits: u8, value: u64) { match space { Space::EmbeddedControl => self.ec[address as usize & 0xff] = value as u8, _ => { self.io.insert(address, value & (u64::MAX >> (64 - bits))); } } } fn notify(&mut self, object: &Path, value: u64) { self.notified.push((object.to_string(), value)); } } fn load(body: &[Vec]) -> (Namespace, Fake) { let mut ns = Namespace::new(); let mut host = Fake::new(); ns.load(&table(b"DSDT", &body.concat()), &mut host).unwrap(); (ns, host) } fn eval(ns: &mut Namespace, host: &mut Fake, path: &str, args: Vec) -> Value { ns.evaluate(&Path::parse(path), args, host).unwrap() } const LEQUAL: u8 = 0x93; const LLESS: u8 = 0x95; /// A laptop's battery as firmware writes one: its numbers in the embedded /// controller, read once `_REG` said the controller is there, put into /// `_BIF`'s and `_BST`'s packages. fn laptop() -> Vec> { vec![scope( "\\_SB", &[ name("ECOK", &int(0)), device( "EC0", &[ name("_HID", &eisa("PNP0C09")), region("ERAM", 3, 0, 0xff), field( "ERAM", 0x01, &[ ("", 0x80), ("BDC0", 16), ("BFC0", 16), ("BRC0", 16), ("BST0", 8), ("ACIN", 1), ("LIDS", 1), ], ), method( "_REG", 2, &[if_( &compare(LEQUAL, &arg(0), &int(3)), &[store(&arg(1), &path("ECOK"))], )], ), method("_Q66", 0, &[notify(&path("\\_SB.BAT0"), &int(0x80))]), ], ), device( "BAT0", &[ name("_HID", &eisa("PNP0C0A")), name("_UID", &int(1)), name( "PBIF", &package(&[ int(0), int(0xffff_ffff), int(0xffff_ffff), int(1), int(11_400), int(0), int(0), int(1), int(1), string("5B10W13930"), string("123"), string("LION"), string("LGC"), ]), ), name("PBST", &package(&[int(0), int(0), int(0), int(0)])), method( "_STA", 0, &[if_(&path("ECOK"), &[ret(&int(0x1f))]), ret(&int(0x0f))], ), method( "_BIF", 0, &[ store( &op2(MULTIPLY, &path("^^EC0.BDC0"), &int(10), &[0]), &index(&path("PBIF"), &int(1)), ), store( &op2(MULTIPLY, &path("^^EC0.BFC0"), &int(10), &[0]), &index(&path("PBIF"), &int(2)), ), ret(&path("PBIF")), ], ), method( "_BST", 0, &[ store(&path("^^EC0.BST0"), &index(&path("PBST"), &int(0))), store( &op2(MULTIPLY, &path("^^EC0.BRC0"), &int(10), &[0]), &index(&path("PBST"), &int(2)), ), ret(&path("PBST")), ], ), ], ), device( "LID0", &[ name("_HID", &eisa("PNP0C0D")), method("_LID", 0, &[ret(&path("^^EC0.LIDS"))]), ], ), ], )] } #[test] fn a_laptops_battery_and_lid_read_from_its_embedded_controller() { let (mut ns, mut host) = load(&laptop()); assert!(ns.errors.is_empty(), "{:?}", ns.errors); // 5000 mWh designed, 4500 last full, 2250 left, discharging; lid open. host.ec[0x10..0x12].copy_from_slice(&500u16.to_le_bytes()); host.ec[0x12..0x14].copy_from_slice(&450u16.to_le_bytes()); host.ec[0x14..0x16].copy_from_slice(&225u16.to_le_bytes()); host.ec[0x16] = 1; host.ec[0x17] = 0b10; let bat = ns.find("PNP0C0A", &mut host); assert_eq!(bat, vec![Path::parse("_SB.BAT0")]); assert_eq!( ns.status(&bat[0], &mut host), 0x0f, "not yet told the EC is there" ); ns.connect(3, &mut host); assert_eq!(ns.status(&bat[0], &mut host), 0x1f); let info = Info::from_bif(&eval(&mut ns, &mut host, "_SB.BAT0._BIF", vec![])).unwrap(); assert!(info.milliwatts); assert_eq!((info.design_capacity, info.full_capacity), (5000, 4500)); assert_eq!(info.model, "5B10W13930"); assert_eq!(info.maker, "LGC"); let status = Status::from_bst(&eval(&mut ns, &mut host, "_SB.BAT0._BST", vec![])).unwrap(); assert!(status.discharging && !status.charging); assert_eq!(status.remaining, 2250); assert_eq!(status.percent(&info), Some(50)); let lid = ns.find("PNP0C0D", &mut host); assert_eq!( eval(&mut ns, &mut host, "_SB.LID0._LID", vec![]), Value::Integer(1) ); host.ec[0x17] = 0; assert_eq!( ns.evaluate(&lid[0].child(*b"_LID"), vec![], &mut host), Ok(Value::Integer(0)) ); eval(&mut ns, &mut host, "_SB.EC0._Q66", vec![]); assert_eq!(host.notified, vec![("\\_SB.BAT0".into(), 0x80)]); } #[test] fn loops_conditions_and_calls() { let (mut ns, mut host) = load(&[ // Sum(n): 1 + 2 + … + n, by While. method( "SUM", 1, &[ store(&int(0), &local(0)), store(&int(1), &local(1)), while_( &[vec![0x92], compare(0x94, &local(1), &arg(0))].concat(), &[op2(ADD, &local(0), &local(1), &local(0)), increment(&local(1))], ), ret(&local(0)), ], ), // Fact(n), recursively, through If and Else. method( "FACT", 1, &[ if_(&compare(LLESS, &arg(0), &int(2)), &[ret(&int(1))]), else_(&[ret(&op2( MULTIPLY, &arg(0), &call("FACT", &[op2(SUBTRACT, &arg(0), &int(1), &[0])]), &[0], ))]), ], ), method("FOREVER", 0, &[while_(&int(1), &[])]), method("DEEP", 0, &[ret(&call("DEEP", &[]))]), ]); assert_eq!( eval(&mut ns, &mut host, "SUM", vec![Value::Integer(10)]), Value::Integer(55) ); assert_eq!( eval(&mut ns, &mut host, "FACT", vec![Value::Integer(10)]), Value::Integer(3_628_800) ); assert_eq!( ns.evaluate(&Path::parse("FOREVER"), vec![], &mut host), Err(Error::Loop) ); assert_eq!( ns.evaluate(&Path::parse("DEEP"), vec![], &mut host), Err(Error::Depth) ); } #[test] fn a_name_is_found_in_the_scopes_above() { let (mut ns, mut host) = load(&[ name("TOP", &int(7)), scope( "\\_SB", &[device( "PCI0", &[device("LPCB", &[method("GET", 0, &[ret(&path("TOP"))])])], )], ), ]); assert_eq!( eval(&mut ns, &mut host, "_SB.PCI0.LPCB.GET", vec![]), Value::Integer(7) ); } #[test] fn osc_writes_through_a_field_of_its_argument() { // _OSC's pattern: fields made over Arg3's buffer, written, the buffer // returned changed. let create_dword = |source: &[u8], byte: u64, n: &str| [&[0x8a][..], source, &int(byte), &path(n)].concat(); let (mut ns, mut host) = load(&[method( "_OSC", 4, &[ create_dword(&arg(3), 0, "CDW1"), create_dword(&arg(3), 4, "CDW2"), store(&op2(OR, &path("CDW1"), &int(0x10), &[0]), &path("CDW1")), store(&op2(AND, &path("CDW2"), &int(0x0f), &[0]), &path("CDW2")), ret(&arg(3)), ], )]); let args = vec![ Value::Buffer(vec![]), Value::Integer(1), Value::Integer(2), Value::Buffer(vec![1, 0, 0, 0, 0xff, 0, 0, 0]), ]; assert_eq!( eval(&mut ns, &mut host, "_OSC", args), Value::Buffer(vec![0x11, 0, 0, 0, 0x0f, 0, 0, 0]) ); assert!( ns.get(&Path::parse("_OSC.CDW1")).is_none(), "a method's own objects go with it" ); } #[test] fn strings_buffers_packages() { let (mut ns, mut host) = load(&[ name("PKG", &package(&[int(1), string("two"), buffer(&[3, 3, 3])])), method("LEN", 0, &[ret(&[&[0x87][..], &path("PKG")].concat())]), method("TWO", 0, &[ret(&deref(&index(&path("PKG"), &int(1))))]), method( "CAT", 0, &[ret(&[&[0x73][..], &string("bat"), &string("tery"), &[0]].concat())], ), method("OSI", 0, &[ret(&call("\\_OSI", &[string("Windows 2015")]))]), ]); assert_eq!(eval(&mut ns, &mut host, "LEN", vec![]), Value::Integer(3)); assert_eq!( eval(&mut ns, &mut host, "TWO", vec![]), Value::String("two".into()) ); assert_eq!( eval(&mut ns, &mut host, "CAT", vec![]), Value::String("battery".into()) ); assert_eq!(eval(&mut ns, &mut host, "OSI", vec![]), Value::Integer(u64::MAX)); } #[test] fn a_fields_bits_are_read_and_written_in_its_access_width() { let (mut ns, mut host) = load(&[ region("PORT", 1, 0x80, 4), // Word access, preserve: bits 4..12 of the word at 0x80. field("PORT", 0x02, &[("", 4), ("MID", 8), ("", 4), ("HIGH", 16)]), ]); host.io.insert(0x80, 0xabcd); assert_eq!(eval(&mut ns, &mut host, "MID", vec![]), Value::Integer(0xbc)); let (mut ns2, mut host2) = load(&[ region("PORT", 1, 0x80, 4), field("PORT", 0x02, &[("", 4), ("MID", 8), ("", 4), ("HIGH", 16)]), method("SET", 1, &[store(&arg(0), &path("MID"))]), ]); host2.io.insert(0x80, 0xabcd); eval(&mut ns2, &mut host2, "SET", vec![Value::Integer(0x12)]); assert_eq!(host2.io[&0x80], 0xa12d, "the bits around it kept"); } #[test] fn a_failing_device_loses_only_itself() { let (mut ns, mut host) = load(&[scope( "\\_SB", &[ device("BAD", &[name("_HID", &string("BAD0001")), vec![0x5b, 0xee]]), device("GOOD", &[name("_HID", &string("PNP0C0D"))]), ], )]); assert_eq!(ns.errors.len(), 1); assert_eq!(ns.find("PNP0C0D", &mut host), vec![Path::parse("_SB.GOOD")]); } #[test] fn a_touchpads_resources() { // What iasl makes of // I2cSerialBusV2 (0x2C, ControllerInitiated, 400000, AddressingMode7Bit, // "\\_SB.PC00.I2C1", 0x00, ResourceConsumer, , Exclusive, ) // GpioInt (Level, ActiveLow, ExclusiveAndWake, PullDefault, 0x0000, // "\\_SB.GPI0", 0x00, ResourceConsumer, ) { 0x0012 } // Interrupt (ResourceConsumer, Level, ActiveLow, Shared) { 0x0000001B } let source = b"\\_SB.PC00.I2C1\0"; let mut i2c = vec![0x8e, 0, 0, 2, 0, 1, 0x02, 0, 0, 1, 6, 0]; i2c.extend_from_slice(&400_000u32.to_le_bytes()); i2c.extend_from_slice(&0x2cu16.to_le_bytes()); i2c.extend_from_slice(source); let len = (i2c.len() - 3) as u16; i2c[1..3].copy_from_slice(&len.to_le_bytes()); let gpio_source = b"\\_SB.GPI0\0"; let mut gpio = vec![0x8c, 0, 0, 1, 0, 0x01, 0]; // Interrupt flags: level (bit 0 clear), active low (polarity 1), wake. gpio.extend_from_slice(&(1u16 << 1 | 1 << 4).to_le_bytes()); gpio.push(0); // pull default gpio.extend_from_slice(&0u16.to_le_bytes()); // drive strength gpio.extend_from_slice(&0u16.to_le_bytes()); // debounce gpio.extend_from_slice(&23u16.to_le_bytes()); // pin table gpio.push(0); gpio.extend_from_slice(&25u16.to_le_bytes()); // source name gpio.extend_from_slice(&(25 + gpio_source.len() as u16).to_le_bytes()); // vendor data gpio.extend_from_slice(&0u16.to_le_bytes()); gpio.extend_from_slice(&0x12u16.to_le_bytes()); gpio.extend_from_slice(gpio_source); let len = (gpio.len() - 3) as u16; gpio[1..3].copy_from_slice(&len.to_le_bytes()); let mut interrupt = vec![0x89, 6, 0, 0b1101, 1]; interrupt.extend_from_slice(&0x1bu32.to_le_bytes()); let template = [i2c, gpio, interrupt, vec![0x79, 0]].concat(); let (mut ns, mut host) = load(&[scope( "\\_SB", &[device( "TPD0", &[ name("_HID", &string("ELAN0001")), name("_CID", &string("PNP0C50")), method("_CRS", 0, &[ret(&buffer(&template))]), ], )], )]); let tpd = ns.find("PNP0C50", &mut host); assert_eq!(tpd, vec![Path::parse("_SB.TPD0")]); assert_eq!(ns.ids(&tpd[0], &mut host), vec!["ELAN0001", "PNP0C50"]); let r = ns.resources(&tpd[0], &mut host).unwrap(); assert_eq!( r[0], Resource::I2c { address: 0x2c, speed: 400_000, ten_bit: false, source: "\\_SB.PC00.I2C1".into() } ); match &r[1] { Resource::Gpio { interrupt, pins, source, edge, active_low, wake, .. } => { assert!(*interrupt && !*edge && *active_low && *wake); assert_eq!(pins, &vec![0x12]); assert_eq!(source, "\\_SB.GPI0"); } other => panic!("{other:?}"), } assert_eq!( r[2], Resource::Interrupt { gsis: vec![0x1b], edge: false, active_low: true, shared: true, wake: false } ); } #[test] fn eisa_ids_decode() { for id in ["PNP0C0A", "PNP0C0D", "PNP0A08", "ACP0003"] { let b = eisa(id); let v = u64::from(u32::from_le_bytes(b[1..5].try_into().unwrap())); assert_eq!(crate::eisa_id(v), id); } }