parser.rs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531
  1. use super::stream::AmlStream;
  2. use super::value::{AmlValue, FieldFlags, RegionSpace};
  3. use super::{opcodes, AmlError};
  4. use crate::{Acpi, AcpiHandler};
  5. use alloc::string::String;
  6. use bit_field::BitField;
  7. use core::str;
  8. /// This is used internally by the parser to keep track of what we know about a field before we can
  9. /// add it to the namespace.
  10. struct FieldInfo {
  11. pub name: String,
  12. pub length: u64,
  13. }
  14. /// This is used internally by the parser. Often, we're only interested in offset of the end of the
  15. /// current explicit-length structure, so we know when to stop parsing it. However, various constants
  16. /// (e.g. the size of fields) are also encoded as PkgLengths, and so sometimes we want to access
  17. /// the raw data as well.
  18. struct PkgLength {
  19. pub raw_length: u32,
  20. pub end_offset: u32,
  21. }
  22. pub(crate) struct AmlParser<'s, 'a, 'h, H>
  23. where
  24. H: AcpiHandler + 'h,
  25. {
  26. acpi: &'a mut Acpi,
  27. handler: &'h mut H,
  28. scope: String,
  29. stream: AmlStream<'s>,
  30. }
  31. /// This macro takes a parser and one or more parsing functions and tries to parse the next part of
  32. /// the stream with each one. If a parsing function fails, it rolls back the stream and tries the
  33. /// next one. If none of the functions can parse the next part of the stream, we error on the
  34. /// unexpected byte.
  35. macro_rules! try_parse {
  36. ($parser: expr, $($function: path),+) => {{
  37. $(if let Some(value) = $parser.try_parse($function)? {
  38. Ok(value)
  39. } else)+ {
  40. Err(AmlError::UnexpectedByte($parser.stream.peek()?))
  41. }
  42. }}
  43. }
  44. impl<'s, 'a, 'h, H> AmlParser<'s, 'a, 'h, H>
  45. where
  46. H: AcpiHandler,
  47. {
  48. pub(crate) fn parse(
  49. acpi: &'a mut Acpi,
  50. handler: &'h mut H,
  51. scope: &str,
  52. stream: AmlStream<'s>,
  53. ) -> Result<(), AmlError> {
  54. let mut parser = AmlParser {
  55. acpi,
  56. handler,
  57. scope: String::from(scope),
  58. stream,
  59. };
  60. let end_offset = parser.stream.len() as u32;
  61. parser.parse_term_list(end_offset)
  62. }
  63. /// Consume the next byte in the stream and check if it fulfils the given predicate. If it
  64. /// does, returns `Ok(the consumed char)`. If it doesn't, returns
  65. /// `Err(AmlError::UnexpectedByte(the consumed char)`. If there's an error consuming the char,
  66. /// it will forward the error on from that.
  67. fn consume_byte<F>(&mut self, predicate: F) -> Result<u8, AmlError>
  68. where
  69. F: Fn(u8) -> bool,
  70. {
  71. let byte = self.stream.next()?;
  72. match predicate(byte) {
  73. true => Ok(byte),
  74. false => Err(AmlError::UnexpectedByte(byte)),
  75. }
  76. }
  77. fn consume_opcode(&mut self, opcode: u8) -> Result<(), AmlError> {
  78. self.consume_byte(matches_byte(opcode))?;
  79. Ok(())
  80. }
  81. fn consume_ext_opcode(&mut self, ext_opcode: u8) -> Result<(), AmlError> {
  82. self.consume_byte(matches_byte(opcodes::EXT_OPCODE_PREFIX))?;
  83. self.consume_byte(matches_byte(ext_opcode))?;
  84. Ok(())
  85. }
  86. /// Try to parse the next part of the stream with the given parsing function. This returns any
  87. /// `AmlError` as an `Err`, except `AmlError::UnexpectedByte`, to which it will return
  88. /// `Ok(None)`. A successful parse gives `Ok(Some(...))`. On failure, this also reverts any
  89. /// changes made to the stream, so it's as if the parsing function never run.
  90. fn try_parse<T, F>(&mut self, parsing_function: F) -> Result<Option<T>, AmlError>
  91. where
  92. F: Fn(&mut Self) -> Result<T, AmlError>,
  93. {
  94. let stream = self.stream.clone();
  95. match parsing_function(self) {
  96. Ok(result) => Ok(Some(result)),
  97. Err(AmlError::UnexpectedByte(_)) => {
  98. self.stream = stream;
  99. Ok(None)
  100. }
  101. Err(error) => Err(error),
  102. }
  103. }
  104. fn parse_term_list(&mut self, end_offset: u32) -> Result<(), AmlError> {
  105. /*
  106. * TermList := Nothing | <TermObj TermList>
  107. *
  108. * Because TermLists don't have PkgLengths, we pass the offset to stop at from whatever
  109. * explicit-length object we were parsing before.
  110. */
  111. while self.stream.offset() <= end_offset {
  112. self.parse_term_object()?;
  113. }
  114. Ok(())
  115. }
  116. fn parse_term_object(&mut self) -> Result<(), AmlError> {
  117. /*
  118. * TermObj := NameSpaceModifierObj | NamedObj | Type1Opcode | Type2Opcode
  119. * NameSpaceModifierObj := DefAlias | DefName | DefScope
  120. * NamedObj := DefBankField | DefCreateBitField | DefCreateByteField | DefCreateDWordField |
  121. * DefCreateField | DefCreateQWordField | DefCreateWordField | DefDataRegion |
  122. * DefExternal | DefOpRegion | DefPowerRes | DefProcessor | DefThermalZone
  123. */
  124. try_parse!(
  125. self,
  126. AmlParser::parse_def_scope,
  127. AmlParser::parse_def_op_region,
  128. AmlParser::parse_def_field //,
  129. // AmlParser::parse_type1_opcode TODO: reenable when we can parse them
  130. )
  131. }
  132. fn parse_def_scope(&mut self) -> Result<(), AmlError> {
  133. /*
  134. * DefScope := 0x10 PkgLength NameString TermList
  135. */
  136. self.consume_opcode(opcodes::SCOPE_OP)?;
  137. trace!("Parsing scope op");
  138. let scope_end_offset = self.parse_pkg_length()?.end_offset;
  139. let name_string = self.parse_name_string()?;
  140. let containing_scope = self.scope.clone();
  141. self.scope = name_string;
  142. let _term_list = self.parse_term_list(scope_end_offset)?;
  143. self.scope = containing_scope;
  144. Ok(())
  145. }
  146. fn parse_def_op_region(&mut self) -> Result<(), AmlError> {
  147. /*
  148. * DefOpRegion := ExtOpPrefix 0x80 NameString RegionSpace RegionOffset RegionLen
  149. * RegionSpace := ByteData (where 0x00 = SystemMemory
  150. * 0x01 = SystemIO
  151. * 0x02 = PciConfig
  152. * 0x03 = EmbeddedControl
  153. * 0x04 = SMBus
  154. * 0x05 = SystemCMOS
  155. * 0x06 = PciBarTarget
  156. * 0x07 = IPMI
  157. * 0x08 = GeneralPurposeIO
  158. * 0x09 = GenericSerialBus
  159. * 0x80-0xff = OEM Defined)
  160. * ByteData := 0x00 - 0xff
  161. * RegionOffset := TermArg => Integer
  162. * RegionLen := TermArg => Integer
  163. */
  164. self.consume_ext_opcode(opcodes::EXT_OP_REGION_OP)?;
  165. info!("Parsing op region");
  166. let name = self.parse_name_string()?;
  167. info!("name: {}", name);
  168. let region_space = match self.stream.next()? {
  169. 0x00 => RegionSpace::SystemMemory,
  170. 0x01 => RegionSpace::SystemIo,
  171. 0x02 => RegionSpace::PciConfig,
  172. 0x03 => RegionSpace::EmbeddedControl,
  173. 0x04 => RegionSpace::SMBus,
  174. 0x05 => RegionSpace::SystemCmos,
  175. 0x06 => RegionSpace::PciBarTarget,
  176. 0x07 => RegionSpace::IPMI,
  177. 0x08 => RegionSpace::GeneralPurposeIo,
  178. 0x09 => RegionSpace::GenericSerialBus,
  179. space @ 0x80..0xff => RegionSpace::OemDefined(space),
  180. byte => return Err(AmlError::UnexpectedByte(byte)),
  181. };
  182. info!("region space: {:?}", region_space);
  183. let offset = self.parse_term_arg()?.as_integer()?;
  184. info!("region offset: {}", offset);
  185. let length = self.parse_term_arg()?.as_integer()?;
  186. info!("region len: {}", length);
  187. // Insert it into the namespace
  188. let namespace_path = self.resolve_path(&name)?;
  189. self.acpi.namespace.insert(
  190. // self.resolve_path(name)?, TODO: I thought this would work with nll?
  191. namespace_path,
  192. AmlValue::OpRegion {
  193. region: region_space,
  194. offset,
  195. length,
  196. },
  197. );
  198. Ok(())
  199. }
  200. fn parse_def_field(&mut self) -> Result<(), AmlError> {
  201. /*
  202. * DefField = ExtOpPrefix 0x81 PkgLength NameString FieldFlags FieldList
  203. * FieldList := Nothing | <FieldElement FieldList>
  204. * FieldElement := NamedField | ReservedField | AccessField | ExtendedAccessField |
  205. * ConnectField
  206. * ReservedField := 0x00 PkgLength
  207. * AccessField := 0x01 AccessType AccessAttrib
  208. * AccessType := ByteData
  209. * AccessAttrib := ByteData
  210. * ConnectField := <0x02 NameString> | <0x02 BufferData>
  211. */
  212. self.consume_ext_opcode(opcodes::EXT_FIELD_OP)?;
  213. trace!("Parsing DefField");
  214. let end_offset = self.parse_pkg_length()?.end_offset;
  215. trace!("end offset: {}", end_offset);
  216. let name = self.parse_name_string()?;
  217. trace!("name: {}", name);
  218. let flags = FieldFlags::new(self.stream.next()?);
  219. trace!("Field flags: {:?}", flags);
  220. while self.stream.offset() < end_offset {
  221. // TODO: parse other field types
  222. let info = try_parse!(self, AmlParser::parse_named_field)?;
  223. // TODO: add field name to this (info.name)?
  224. let namespace_path = self.resolve_path(&name)?;
  225. self.acpi.namespace.insert(
  226. namespace_path,
  227. AmlValue::Field {
  228. flags,
  229. offset: 0, // TODO: calculate offset
  230. length: info.length,
  231. },
  232. );
  233. }
  234. Ok(())
  235. }
  236. fn parse_named_field(&mut self) -> Result<FieldInfo, AmlError> {
  237. /*
  238. * NamedField := NameSeg PkgLength
  239. *
  240. * This encodes the size of the field using a PkgLength - it doesn't mark the length of an
  241. * explicit-length structure!
  242. */
  243. let name = String::from(name_seg_to_string(&self.parse_name_seg()?)?);
  244. let length = self.parse_pkg_length()?.raw_length as u64;
  245. info!("Adding named field called {:?} with size {}", name, length);
  246. Ok(FieldInfo { name, length })
  247. }
  248. fn parse_def_buffer(&mut self) -> Result<AmlValue, AmlError> {
  249. unimplemented!(); // TODO
  250. }
  251. fn parse_term_arg(&mut self) -> Result<AmlValue, AmlError> {
  252. /*
  253. * TermArg := Type2Opcode | DataObject | ArgObj | LocalObj
  254. * DataObject := ComputationalData | DefPackage | DefVarPackage
  255. */
  256. if let Some(result) = self.try_parse(AmlParser::parse_computational_data)? {
  257. Ok(result)
  258. } else {
  259. Err(AmlError::UnexpectedByte(self.stream.next()?))
  260. }
  261. }
  262. fn parse_computational_data(&mut self) -> Result<AmlValue, AmlError> {
  263. /*
  264. * ComputationalData := ByteConst | WordConst | DWordConst | QWordConst | String |
  265. * ConstObj | RevisionOp | DefBuffer
  266. * ByteConst := 0x0a ByteData
  267. * WordConst := 0x0b WordData
  268. * DWordConst := 0x0c DWordData
  269. * QWordConst := 0x0e QWordData
  270. * String := 0x0d AsciiCharList NullChar
  271. * ConstObj := ZeroOp(0x00) | OneOp(0x01) | OnesOp(0xff)
  272. * RevisionOp := ExtOpPrefix(0x5B) 0x30
  273. */
  274. match self.stream.peek()? {
  275. opcodes::BYTE_CONST => {
  276. self.consume_opcode(opcodes::BYTE_CONST)?;
  277. Ok(AmlValue::Integer(self.stream.next()? as u64))
  278. }
  279. opcodes::WORD_CONST => {
  280. self.consume_opcode(opcodes::WORD_CONST)?;
  281. Ok(AmlValue::Integer(self.stream.next_u16()? as u64))
  282. }
  283. opcodes::DWORD_CONST => {
  284. self.consume_opcode(opcodes::DWORD_CONST)?;
  285. Ok(AmlValue::Integer(self.stream.next_u16()? as u64))
  286. }
  287. opcodes::QWORD_CONST => {
  288. self.consume_opcode(opcodes::QWORD_CONST)?;
  289. Ok(AmlValue::Integer(self.stream.next_u16()? as u64))
  290. }
  291. opcodes::STRING_PREFIX => {
  292. self.consume_opcode(opcodes::STRING_PREFIX)?;
  293. unimplemented!(); // TODO
  294. }
  295. opcodes::ZERO_OP => {
  296. self.consume_opcode(opcodes::ZERO_OP)?;
  297. Ok(AmlValue::Integer(0))
  298. }
  299. opcodes::ONE_OP => {
  300. self.consume_opcode(opcodes::ONE_OP)?;
  301. Ok(AmlValue::Integer(1))
  302. }
  303. opcodes::ONES_OP => {
  304. self.consume_opcode(opcodes::ONES_OP)?;
  305. Ok(AmlValue::Integer(u64::max_value()))
  306. }
  307. opcodes::EXT_OPCODE_PREFIX if self.stream.lookahead(1)? == opcodes::EXT_REVISION_OP => {
  308. unimplemented!(); // TODO
  309. }
  310. _ => self.parse_def_buffer(),
  311. }
  312. }
  313. fn parse_type1_opcode(&mut self) -> Result<(), AmlError> {
  314. /*
  315. * Type1Opcode := DefBreak | DefBreakPoint | DefContinue | DefFatal | DefIfElse | DefLoad |
  316. * DefNoop | DefNotify | DefRelease | DefReset | DefReturn | DefSignal |
  317. * DefSleep | DefStall | DefUnload | DefWhile
  318. */
  319. unimplemented!(); // TODO
  320. }
  321. /// Parse a PkgLength. Returns the offset into the stream to stop parsing whatever object the
  322. /// PkgLength describes at.
  323. // TODO: think hard about whether we actually need to minus the length now because we use
  324. // `next()`? Isn't this already handled?
  325. fn parse_pkg_length(&mut self) -> Result<PkgLength, AmlError> {
  326. /*
  327. * PkgLength := PkgLeadByte |
  328. * <PkgLeadByte ByteData> |
  329. * <PkgLeadByte ByteData ByteData> |
  330. * <PkgLeadByte ByteData ByteData ByteData>
  331. */
  332. let lead_byte = self.stream.next()?;
  333. let byte_data_count = lead_byte.get_bits(6..8);
  334. if byte_data_count == 0 {
  335. let length = u32::from(lead_byte.get_bits(0..6));
  336. let end_offset = self.stream.offset() + length - 1; // Minus 1 to remove the PkgLength byte
  337. trace!(
  338. "Parsed 1-byte PkgLength with length {}, so ends at {}(current offset={}",
  339. length,
  340. end_offset,
  341. self.stream.offset()
  342. );
  343. return Ok(PkgLength {
  344. raw_length: length,
  345. end_offset,
  346. });
  347. }
  348. let mut length = u32::from(lead_byte.get_bits(0..4));
  349. for i in 0..byte_data_count {
  350. length += u32::from(self.stream.next()?) << (4 + i * 8);
  351. }
  352. // Minus `byte_data_count + 1` to not include the PkgLength in the remaining bytes
  353. let end_offset = self.stream.offset() + length - byte_data_count as u32 - 1;
  354. trace!(
  355. "Parsed PkgLength with length {}, so ends at {}(current offset={})",
  356. length,
  357. end_offset,
  358. self.stream.offset()
  359. );
  360. Ok(PkgLength {
  361. raw_length: length,
  362. end_offset,
  363. })
  364. }
  365. fn parse_name_string(&mut self) -> Result<String, AmlError> {
  366. /*
  367. * NameString := <RootChar('\') NamePath> | <PrefixPath NamePath>
  368. * PrefixPath := Nothing | <'^' PrefixPath>
  369. */
  370. match self.stream.peek()? {
  371. b'\\' => {
  372. /*
  373. * NameString := RootChar NamePath
  374. */
  375. self.stream.next()?;
  376. Ok(String::from("\\") + &self.parse_name_path()?)
  377. }
  378. b'^' => {
  379. unimplemented!();
  380. }
  381. _ => self.parse_name_path(),
  382. }
  383. }
  384. fn parse_name_path(&mut self) -> Result<String, AmlError> {
  385. /*
  386. * NamePath := NameSeg | DualNamePath | MultiNamePath | NullPath
  387. * DualNamePath := DualNamePrefix NameSeg NameSeg
  388. * MultiNamePath := MultiNamePrefix SegCount{ByteData} NameSeg(..SegCount)
  389. */
  390. match self.stream.peek()? {
  391. opcodes::NULL_NAME => {
  392. self.stream.next()?;
  393. Ok(String::from(""))
  394. }
  395. opcodes::DUAL_NAME_PREFIX => {
  396. self.stream.next()?;
  397. let first = self.parse_name_seg()?;
  398. let second = self.parse_name_seg()?;
  399. Ok(
  400. String::from(str::from_utf8(&first).unwrap())
  401. + str::from_utf8(&second).unwrap(),
  402. )
  403. }
  404. opcodes::MULTI_NAME_PREFIX => {
  405. // TODO
  406. unimplemented!();
  407. }
  408. _ => Ok(String::from(
  409. str::from_utf8(&self.parse_name_seg()?).unwrap(),
  410. )),
  411. }
  412. }
  413. fn parse_name_seg(&mut self) -> Result<[u8; 4], AmlError> {
  414. /*
  415. * NameSeg := <LeadNameChar NameChar NameChar NameChar>
  416. */
  417. Ok([
  418. self.consume_byte(is_lead_name_char)?,
  419. self.consume_byte(is_name_char)?,
  420. self.consume_byte(is_name_char)?,
  421. self.consume_byte(is_name_char)?,
  422. ])
  423. }
  424. /// Resolve a given path and the current scope to an absolute path in the namespace.
  425. fn resolve_path(&mut self, mut path: &str) -> Result<String, AmlError> {
  426. /*
  427. * TODO: how should we handle '.' as they appear in paths?
  428. */
  429. let original_path = path.clone();
  430. // If the scope to resolve is from the root of the namespace, or the current scope is
  431. // nothing, just return the given scope
  432. if self.scope == "" || path.starts_with("\\") {
  433. return Ok(String::from(path));
  434. }
  435. // "^"s at the start of a path specify to go up one level from the current scope, to its
  436. // parent object
  437. let mut namespace_object = self.scope.clone();
  438. while path.starts_with("^") {
  439. path = &path[1..];
  440. if namespace_object.pop() == None {
  441. return Err(AmlError::InvalidPath(String::from(original_path)));
  442. }
  443. }
  444. Ok(namespace_object + &path)
  445. }
  446. }
  447. fn matches_byte(byte: u8) -> impl Fn(u8) -> bool {
  448. move |x| x == byte
  449. }
  450. fn is_lead_name_char(byte: u8) -> bool {
  451. (byte >= b'A' && byte <= b'Z') || byte == b'_'
  452. }
  453. fn is_digit_char(byte: u8) -> bool {
  454. byte >= b'0' && byte <= b'9'
  455. }
  456. fn is_name_char(byte: u8) -> bool {
  457. is_lead_name_char(byte) || is_digit_char(byte)
  458. }
  459. fn name_seg_to_string<'a>(seg: &'a [u8; 4]) -> Result<&'a str, AmlError> {
  460. match str::from_utf8(seg) {
  461. Ok(seg_str) => Ok(seg_str),
  462. Err(_) => Err(AmlError::InvalidNameSeg(*seg)),
  463. }
  464. }