namespace.rs 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701
  1. use crate::{name_object::NameSeg, value::AmlValue, AmlError};
  2. use alloc::{
  3. collections::BTreeMap,
  4. string::{String, ToString},
  5. vec::Vec,
  6. };
  7. use core::fmt;
  8. /// A handle is used to refer to an AML value without actually borrowing it until you need to
  9. /// access it (this makes borrowing situation much easier as you only have to consider who's
  10. /// borrowing the namespace). They can also be cached to avoid expensive namespace lookups.
  11. ///
  12. /// Handles are never reused (the handle to a removed object will never be reused to point to a new
  13. /// object). This ensures handles cached by the library consumer will never point to an object they
  14. /// did not originally point to, but also means that, in theory, we can run out of handles on a
  15. /// very-long-running system (we are yet to see if this is a problem, practically).
  16. #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Debug)]
  17. pub struct AmlHandle(u32);
  18. impl AmlHandle {
  19. pub(self) fn increment(&mut self) {
  20. self.0 += 1;
  21. }
  22. }
  23. #[derive(Clone, Copy, PartialEq, Eq, Debug)]
  24. pub enum LevelType {
  25. Scope,
  26. Device,
  27. /// A legacy `Processor` object's sub-objects are stored in a level of this type. Modern tables define
  28. /// processors as `Device`s.
  29. Processor,
  30. /// A level of this type is created at the same path as the name of a method when it is invoked. It can be
  31. /// used by the method to store local variables.
  32. MethodLocals,
  33. }
  34. #[derive(Clone, Debug)]
  35. pub struct NamespaceLevel {
  36. pub typ: LevelType,
  37. pub children: BTreeMap<NameSeg, NamespaceLevel>,
  38. pub values: BTreeMap<NameSeg, AmlHandle>,
  39. }
  40. impl NamespaceLevel {
  41. pub(crate) fn new(typ: LevelType) -> NamespaceLevel {
  42. NamespaceLevel { typ, children: BTreeMap::new(), values: BTreeMap::new() }
  43. }
  44. }
  45. #[derive(Clone)]
  46. pub struct Namespace {
  47. /// This is a running count of ids, which are never reused. This is incremented every time we
  48. /// add a new object to the namespace. We can then remove objects, freeing their memory, without
  49. /// risking using the same id for two objects.
  50. next_handle: AmlHandle,
  51. /// This maps handles to actual values, and is used to access the actual AML values. When removing a value
  52. /// from the object map, care must be taken to also remove references to its handle in the level data
  53. /// structure, as invalid handles will cause panics.
  54. object_map: BTreeMap<AmlHandle, AmlValue>,
  55. /// Holds the first level of the namespace - containing items such as `\_SB`. Subsequent levels are held
  56. /// recursively inside this structure. It holds handles to references, which need to be indexed into
  57. /// `object_map` to acctually access the object.
  58. root: NamespaceLevel,
  59. }
  60. impl Namespace {
  61. pub fn new() -> Namespace {
  62. Namespace {
  63. next_handle: AmlHandle(0),
  64. object_map: BTreeMap::new(),
  65. root: NamespaceLevel::new(LevelType::Scope),
  66. }
  67. }
  68. /// Add a new level to the namespace. A "level" is named by a single `NameSeg`, and can contain values, and
  69. /// also other further sub-levels. Once a level has been created, AML values can be added to it with
  70. /// `add_value`.
  71. ///
  72. /// ### Note
  73. /// At first glance, you might expect `DefDevice` to add a value of type `Device`. However, because all
  74. /// `Devices` do is hold other values, we model them as namespace levels, and so they must be created
  75. /// accordingly.
  76. pub fn add_level(&mut self, path: AmlName, typ: LevelType) -> Result<(), AmlError> {
  77. assert!(path.is_absolute());
  78. let path = path.normalize()?;
  79. /*
  80. * We need to handle a special case here: if a `Scope(\) { ... }` appears in the AML, the parser will
  81. * try and recreate the root scope. Instead of handling this specially in the parser, we just
  82. * return nicely here.
  83. */
  84. if path != AmlName::root() {
  85. let (level, last_seg) = self.get_level_for_path_mut(&path)?;
  86. /*
  87. * If the level has already been added, we don't need to add it again. The parser can try to add it
  88. * multiple times if the ASL contains multiple blocks that add to the same scope/device.
  89. */
  90. if !level.children.contains_key(&last_seg) {
  91. level.children.insert(last_seg, NamespaceLevel::new(typ));
  92. }
  93. }
  94. Ok(())
  95. }
  96. pub fn remove_level(&mut self, path: AmlName) -> Result<(), AmlError> {
  97. assert!(path.is_absolute());
  98. let path = path.normalize()?;
  99. if path != AmlName::root() {
  100. let (level, last_seg) = self.get_level_for_path_mut(&path)?;
  101. match level.children.remove(&last_seg) {
  102. Some(_) => Ok(()),
  103. None => Err(AmlError::LevelDoesNotExist(path)),
  104. }
  105. } else {
  106. Err(AmlError::TriedToRemoveRootNamespace)
  107. }
  108. }
  109. /// Add a value to the namespace at the given path, which must be a normalized, absolute AML
  110. /// name. If you want to add at a path relative to a given scope, use `add_at_resolved_path`
  111. /// instead.
  112. pub fn add_value(&mut self, path: AmlName, value: AmlValue) -> Result<AmlHandle, AmlError> {
  113. assert!(path.is_absolute());
  114. let path = path.normalize()?;
  115. let handle = self.next_handle;
  116. self.next_handle.increment();
  117. self.object_map.insert(handle, value);
  118. let (level, last_seg) = self.get_level_for_path_mut(&path)?;
  119. match level.values.insert(last_seg, handle) {
  120. None => Ok(handle),
  121. Some(_) => Err(AmlError::NameCollision(path)),
  122. }
  123. }
  124. /// Helper method for adding a value to the namespace at a path that is relative to the given
  125. /// scope. This operation involves a lot of error handling in parts of the parser, so is
  126. /// encapsulated here.
  127. pub fn add_value_at_resolved_path(
  128. &mut self,
  129. path: AmlName,
  130. scope: &AmlName,
  131. value: AmlValue,
  132. ) -> Result<AmlHandle, AmlError> {
  133. self.add_value(path.resolve(scope)?, value)
  134. }
  135. pub fn get(&self, handle: AmlHandle) -> Result<&AmlValue, AmlError> {
  136. Ok(self.object_map.get(&handle).unwrap())
  137. }
  138. pub fn get_mut(&mut self, handle: AmlHandle) -> Result<&mut AmlValue, AmlError> {
  139. Ok(self.object_map.get_mut(&handle).unwrap())
  140. }
  141. pub fn get_handle(&self, path: &AmlName) -> Result<AmlHandle, AmlError> {
  142. let (level, last_seg) = self.get_level_for_path(path)?;
  143. Ok(*level.values.get(&last_seg).ok_or(AmlError::ValueDoesNotExist(path.clone()))?)
  144. }
  145. pub fn get_by_path(&self, path: &AmlName) -> Result<&AmlValue, AmlError> {
  146. let handle = self.get_handle(path)?;
  147. Ok(self.get(handle).unwrap())
  148. }
  149. pub fn get_by_path_mut(&mut self, path: &AmlName) -> Result<&mut AmlValue, AmlError> {
  150. let handle = self.get_handle(path)?;
  151. Ok(self.get_mut(handle).unwrap())
  152. }
  153. /// Search for an object at the given path of the namespace, applying the search rules described in §5.3 of the
  154. /// ACPI specification, if they are applicable. Returns the resolved name, and the handle of the first valid
  155. /// object, if found.
  156. pub fn search(&self, path: &AmlName, starting_scope: &AmlName) -> Result<(AmlName, AmlHandle), AmlError> {
  157. if path.search_rules_apply() {
  158. /*
  159. * If search rules apply, we need to recursively look through the namespace. If the
  160. * given name does not occur in the current scope, we look at the parent scope, until
  161. * we either find the name, or reach the root of the namespace.
  162. */
  163. let mut scope = starting_scope.clone();
  164. assert!(scope.is_absolute());
  165. loop {
  166. // Search for the name at this namespace level. If we find it, we're done.
  167. let name = path.resolve(&scope)?;
  168. match self.get_level_for_path(&name) {
  169. Ok((level, last_seg)) => {
  170. if let Some(&handle) = level.values.get(&last_seg) {
  171. return Ok((name, handle));
  172. }
  173. }
  174. /*
  175. * This error is caught specially to avoid a case that seems bizzare but is quite useful - when
  176. * the passed starting scope doesn't exist. Certain methods return values that reference names
  177. * from the point of view of the method, so it makes sense for the starting scope to be inside
  178. * the method. However, because we have destroyed all the objects created by the method
  179. * dynamically, the level no longer exists.
  180. *
  181. * To avoid erroring here, we simply continue to the parent scope. If the whole scope doesn't
  182. * exist, this will error when we get to the root, so this seems unlikely to introduce bugs.
  183. */
  184. Err(AmlError::LevelDoesNotExist(_)) => (),
  185. Err(err) => return Err(err),
  186. }
  187. // If we don't find it, go up a level in the namespace and search for it there recursively
  188. match scope.parent() {
  189. Ok(parent) => scope = parent,
  190. // If we still haven't found the value and have run out of parents, return `None`.
  191. Err(AmlError::RootHasNoParent) => return Err(AmlError::ValueDoesNotExist(path.clone())),
  192. Err(err) => return Err(err),
  193. }
  194. }
  195. } else {
  196. // If search rules don't apply, simply resolve it against the starting scope
  197. let name = path.resolve(starting_scope)?;
  198. let (level, last_seg) = self.get_level_for_path(&path.resolve(starting_scope)?)?;
  199. if let Some(&handle) = level.values.get(&last_seg) {
  200. Ok((name, handle))
  201. } else {
  202. Err(AmlError::ValueDoesNotExist(path.clone()))
  203. }
  204. }
  205. }
  206. pub fn search_for_level(&self, level_name: &AmlName, starting_scope: &AmlName) -> Result<AmlName, AmlError> {
  207. if level_name.search_rules_apply() {
  208. let mut scope = starting_scope.clone().normalize()?;
  209. assert!(scope.is_absolute());
  210. loop {
  211. let name = level_name.resolve(&scope)?;
  212. if let Ok((level, last_seg)) = self.get_level_for_path(&name) {
  213. if let Some(_) = level.children.get(&last_seg) {
  214. return Ok(name);
  215. }
  216. }
  217. // If we don't find it, move the scope up a level and search for it there recursively
  218. match scope.parent() {
  219. Ok(parent) => scope = parent,
  220. Err(AmlError::RootHasNoParent) => return Err(AmlError::LevelDoesNotExist(level_name.clone())),
  221. Err(err) => return Err(err),
  222. }
  223. }
  224. } else {
  225. Ok(level_name.clone())
  226. }
  227. }
  228. fn get_level_for_path(&self, path: &AmlName) -> Result<(&NamespaceLevel, NameSeg), AmlError> {
  229. let (last_seg, levels) = path.0[1..].split_last().unwrap();
  230. let last_seg = last_seg.as_segment().unwrap();
  231. // TODO: this helps with diagnostics, but requires a heap allocation just in case we need to error.
  232. let mut traversed_path = AmlName::root();
  233. let mut current_level = &self.root;
  234. for level in levels {
  235. traversed_path.0.push(*level);
  236. current_level = current_level
  237. .children
  238. .get(&level.as_segment().unwrap())
  239. .ok_or(AmlError::LevelDoesNotExist(traversed_path.clone()))?;
  240. }
  241. Ok((current_level, last_seg))
  242. }
  243. /// Split an absolute path into a bunch of level segments (used to traverse the level data structure), and a
  244. /// last segment to index into that level. This must not be called on `\\`.
  245. fn get_level_for_path_mut(&mut self, path: &AmlName) -> Result<(&mut NamespaceLevel, NameSeg), AmlError> {
  246. let (last_seg, levels) = path.0[1..].split_last().unwrap();
  247. let last_seg = last_seg.as_segment().unwrap();
  248. // TODO: this helps with diagnostics, but requires a heap allocation just in case we need to error. We can
  249. // improve this by changing the `levels` interation into an `enumerate()`, and then using the index to
  250. // create the correct path on the error path
  251. let mut traversed_path = AmlName::root();
  252. let mut current_level = &mut self.root;
  253. for level in levels {
  254. traversed_path.0.push(*level);
  255. current_level = current_level
  256. .children
  257. .get_mut(&level.as_segment().unwrap())
  258. .ok_or(AmlError::LevelDoesNotExist(traversed_path.clone()))?;
  259. }
  260. Ok((current_level, last_seg))
  261. }
  262. /// Traverse the namespace, calling `f` on each namespace level. `f` returns a `Result<bool, AmlError>` -
  263. /// errors terminate the traversal and are propagated, and the `bool` on the successful path marks whether the
  264. /// children of the level should also be traversed.
  265. pub fn traverse<F>(&mut self, mut f: F) -> Result<(), AmlError>
  266. where
  267. F: FnMut(&AmlName, &NamespaceLevel) -> Result<bool, AmlError>,
  268. {
  269. fn traverse_level<F>(level: &NamespaceLevel, scope: &AmlName, f: &mut F) -> Result<(), AmlError>
  270. where
  271. F: FnMut(&AmlName, &NamespaceLevel) -> Result<bool, AmlError>,
  272. {
  273. for (name, ref child) in level.children.iter() {
  274. let name = AmlName::from_name_seg(*name).resolve(scope)?;
  275. if f(&name, child)? {
  276. traverse_level(child, &name, f)?;
  277. }
  278. }
  279. Ok(())
  280. }
  281. if f(&AmlName::root(), &self.root)? {
  282. traverse_level(&self.root, &AmlName::root(), &mut f)?;
  283. }
  284. Ok(())
  285. }
  286. }
  287. impl fmt::Debug for Namespace {
  288. fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
  289. const INDENT_PER_LEVEL: usize = 4;
  290. fn print_level(
  291. namespace: &Namespace,
  292. f: &mut fmt::Formatter<'_>,
  293. level_name: &str,
  294. level: &NamespaceLevel,
  295. indent: usize,
  296. ) -> fmt::Result {
  297. writeln!(f, "{:indent$}{}:", "", level_name, indent = indent)?;
  298. for (name, handle) in level.values.iter() {
  299. writeln!(
  300. f,
  301. "{:indent$}{}: {:?}",
  302. "",
  303. name.as_str(),
  304. namespace.object_map.get(handle).unwrap(),
  305. indent = indent + INDENT_PER_LEVEL
  306. )?;
  307. }
  308. for (name, sub_level) in level.children.iter() {
  309. print_level(namespace, f, name.as_str(), sub_level, indent + INDENT_PER_LEVEL)?;
  310. }
  311. Ok(())
  312. };
  313. print_level(self, f, "\\", &self.root, 0)
  314. }
  315. }
  316. #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Debug)]
  317. pub struct AmlName(pub(crate) Vec<NameComponent>);
  318. impl AmlName {
  319. pub fn root() -> AmlName {
  320. AmlName(alloc::vec![NameComponent::Root])
  321. }
  322. pub fn from_name_seg(seg: NameSeg) -> AmlName {
  323. AmlName(alloc::vec![NameComponent::Segment(seg)])
  324. }
  325. /// Convert a string representation of an AML name into an `AmlName`.
  326. pub fn from_str(mut string: &str) -> Result<AmlName, AmlError> {
  327. if string.len() == 0 {
  328. return Err(AmlError::EmptyNamesAreInvalid);
  329. }
  330. let mut components = Vec::new();
  331. // If it starts with a \, make it an absolute name
  332. if string.starts_with('\\') {
  333. components.push(NameComponent::Root);
  334. string = &string[1..];
  335. }
  336. if string.len() > 0 {
  337. // Divide the rest of it into segments, and parse those
  338. for mut part in string.split('.') {
  339. // Handle prefix chars
  340. while part.starts_with('^') {
  341. components.push(NameComponent::Prefix);
  342. part = &part[1..];
  343. }
  344. components.push(NameComponent::Segment(NameSeg::from_str(part)?));
  345. }
  346. }
  347. Ok(AmlName(components))
  348. }
  349. pub fn as_string(&self) -> String {
  350. self.0
  351. .iter()
  352. .fold(String::new(), |name, component| match component {
  353. NameComponent::Root => name + "\\",
  354. NameComponent::Prefix => name + "^",
  355. NameComponent::Segment(seg) => name + seg.as_str() + ".",
  356. })
  357. .trim_end_matches('.')
  358. .to_string()
  359. }
  360. /// An AML path is normal if it does not contain any prefix elements ("^" characters, when
  361. /// expressed as a string).
  362. pub fn is_normal(&self) -> bool {
  363. !self.0.contains(&NameComponent::Prefix)
  364. }
  365. pub fn is_absolute(&self) -> bool {
  366. self.0.first() == Some(&NameComponent::Root)
  367. }
  368. /// Special rules apply when searching for certain paths (specifically, those that are made up
  369. /// of a single name segment). Returns `true` if those rules apply.
  370. pub fn search_rules_apply(&self) -> bool {
  371. if self.0.len() != 1 {
  372. return false;
  373. }
  374. match self.0[0] {
  375. NameComponent::Segment(_) => true,
  376. _ => false,
  377. }
  378. }
  379. /// Normalize an AML path, resolving prefix chars. Returns `AmlError::InvalidNormalizedName` if the path
  380. /// normalizes to an invalid path (e.g. `\^_FOO`)
  381. pub fn normalize(self) -> Result<AmlName, AmlError> {
  382. /*
  383. * If the path is already normal, just return it as-is. This avoids an unneccessary heap allocation and
  384. * free.
  385. */
  386. if self.is_normal() {
  387. return Ok(self);
  388. }
  389. Ok(AmlName(self.0.iter().try_fold(Vec::new(), |mut name, &component| match component {
  390. seg @ NameComponent::Segment(_) => {
  391. name.push(seg);
  392. Ok(name)
  393. }
  394. NameComponent::Root => {
  395. name.push(NameComponent::Root);
  396. Ok(name)
  397. }
  398. NameComponent::Prefix => {
  399. if let Some(NameComponent::Segment(_)) = name.iter().last() {
  400. name.pop().unwrap();
  401. Ok(name)
  402. } else {
  403. Err(AmlError::InvalidNormalizedName(self.clone()))
  404. }
  405. }
  406. })?))
  407. }
  408. /// Get the parent of this `AmlName`. For example, the parent of `\_SB.PCI0._PRT` is `\_SB.PCI0`. The root
  409. /// path has no parent, and so returns `None`.
  410. pub fn parent(&self) -> Result<AmlName, AmlError> {
  411. // Firstly, normalize the path so we don't have to deal with prefix chars
  412. let mut normalized_self = self.clone().normalize()?;
  413. match normalized_self.0.last() {
  414. None | Some(NameComponent::Root) => Err(AmlError::RootHasNoParent),
  415. Some(NameComponent::Segment(_)) => {
  416. normalized_self.0.pop();
  417. Ok(normalized_self)
  418. }
  419. Some(NameComponent::Prefix) => unreachable!(), // Prefix chars are removed by normalization
  420. }
  421. }
  422. /// Resolve this path against a given scope, making it absolute. If the path is absolute, it is
  423. /// returned directly. The path is also normalized.
  424. pub fn resolve(&self, scope: &AmlName) -> Result<AmlName, AmlError> {
  425. assert!(scope.is_absolute());
  426. if self.is_absolute() {
  427. return Ok(self.clone());
  428. }
  429. let mut resolved_path = scope.clone();
  430. resolved_path.0.extend_from_slice(&(self.0));
  431. resolved_path.normalize()
  432. }
  433. }
  434. impl fmt::Display for AmlName {
  435. fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
  436. write!(f, "{}", self.as_string())
  437. }
  438. }
  439. #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Debug)]
  440. pub enum NameComponent {
  441. Root,
  442. Prefix,
  443. Segment(NameSeg),
  444. }
  445. impl NameComponent {
  446. pub fn as_segment(self) -> Result<NameSeg, ()> {
  447. match self {
  448. NameComponent::Segment(seg) => Ok(seg),
  449. NameComponent::Root | NameComponent::Prefix => Err(()),
  450. }
  451. }
  452. }
  453. #[cfg(test)]
  454. mod tests {
  455. use super::*;
  456. #[test]
  457. fn test_aml_name_from_str() {
  458. assert_eq!(AmlName::from_str(""), Err(AmlError::EmptyNamesAreInvalid));
  459. assert_eq!(AmlName::from_str("\\"), Ok(AmlName::root()));
  460. assert_eq!(
  461. AmlName::from_str("\\_SB.PCI0"),
  462. Ok(AmlName(alloc::vec![
  463. NameComponent::Root,
  464. NameComponent::Segment(NameSeg([b'_', b'S', b'B', b'_'])),
  465. NameComponent::Segment(NameSeg([b'P', b'C', b'I', b'0']))
  466. ]))
  467. );
  468. assert_eq!(
  469. AmlName::from_str("\\_SB.^^^PCI0"),
  470. Ok(AmlName(alloc::vec![
  471. NameComponent::Root,
  472. NameComponent::Segment(NameSeg([b'_', b'S', b'B', b'_'])),
  473. NameComponent::Prefix,
  474. NameComponent::Prefix,
  475. NameComponent::Prefix,
  476. NameComponent::Segment(NameSeg([b'P', b'C', b'I', b'0']))
  477. ]))
  478. );
  479. }
  480. #[test]
  481. fn test_is_normal() {
  482. assert_eq!(AmlName::root().is_normal(), true);
  483. assert_eq!(AmlName::from_str("\\_SB.PCI0.VGA").unwrap().is_normal(), true);
  484. assert_eq!(AmlName::from_str("\\_SB.^PCI0.VGA").unwrap().is_normal(), false);
  485. assert_eq!(AmlName::from_str("\\^_SB.^^PCI0.VGA").unwrap().is_normal(), false);
  486. assert_eq!(AmlName::from_str("_SB.^^PCI0.VGA").unwrap().is_normal(), false);
  487. assert_eq!(AmlName::from_str("_SB.PCI0.VGA").unwrap().is_normal(), true);
  488. }
  489. #[test]
  490. fn test_normalization() {
  491. assert_eq!(
  492. AmlName::from_str("\\_SB.PCI0").unwrap().normalize(),
  493. Ok(AmlName::from_str("\\_SB.PCI0").unwrap())
  494. );
  495. assert_eq!(
  496. AmlName::from_str("\\_SB.^PCI0").unwrap().normalize(),
  497. Ok(AmlName::from_str("\\PCI0").unwrap())
  498. );
  499. assert_eq!(
  500. AmlName::from_str("\\_SB.PCI0.^^FOO").unwrap().normalize(),
  501. Ok(AmlName::from_str("\\FOO").unwrap())
  502. );
  503. assert_eq!(
  504. AmlName::from_str("_SB.PCI0.^FOO.BAR").unwrap().normalize(),
  505. Ok(AmlName::from_str("_SB.FOO.BAR").unwrap())
  506. );
  507. assert_eq!(
  508. AmlName::from_str("\\^_SB").unwrap().normalize(),
  509. Err(AmlError::InvalidNormalizedName(AmlName::from_str("\\^_SB").unwrap()))
  510. );
  511. assert_eq!(
  512. AmlName::from_str("\\_SB.PCI0.FOO.^^^^BAR").unwrap().normalize(),
  513. Err(AmlError::InvalidNormalizedName(AmlName::from_str("\\_SB.PCI0.FOO.^^^^BAR").unwrap()))
  514. );
  515. }
  516. #[test]
  517. fn test_is_absolute() {
  518. assert_eq!(AmlName::root().is_absolute(), true);
  519. assert_eq!(AmlName::from_str("\\_SB.PCI0.VGA").unwrap().is_absolute(), true);
  520. assert_eq!(AmlName::from_str("\\_SB.^PCI0.VGA").unwrap().is_absolute(), true);
  521. assert_eq!(AmlName::from_str("\\^_SB.^^PCI0.VGA").unwrap().is_absolute(), true);
  522. assert_eq!(AmlName::from_str("_SB.^^PCI0.VGA").unwrap().is_absolute(), false);
  523. assert_eq!(AmlName::from_str("_SB.PCI0.VGA").unwrap().is_absolute(), false);
  524. }
  525. #[test]
  526. fn test_search_rules_apply() {
  527. assert_eq!(AmlName::root().search_rules_apply(), false);
  528. assert_eq!(AmlName::from_str("\\_SB").unwrap().search_rules_apply(), false);
  529. assert_eq!(AmlName::from_str("^VGA").unwrap().search_rules_apply(), false);
  530. assert_eq!(AmlName::from_str("_SB.PCI0.VGA").unwrap().search_rules_apply(), false);
  531. assert_eq!(AmlName::from_str("VGA").unwrap().search_rules_apply(), true);
  532. assert_eq!(AmlName::from_str("_SB").unwrap().search_rules_apply(), true);
  533. }
  534. #[test]
  535. fn test_aml_name_parent() {
  536. assert_eq!(AmlName::from_str("\\").unwrap().parent(), Err(AmlError::RootHasNoParent));
  537. assert_eq!(AmlName::from_str("\\_SB").unwrap().parent(), Ok(AmlName::root()));
  538. assert_eq!(AmlName::from_str("\\_SB.PCI0").unwrap().parent(), Ok(AmlName::from_str("\\_SB").unwrap()));
  539. assert_eq!(AmlName::from_str("\\_SB.PCI0").unwrap().parent().unwrap().parent(), Ok(AmlName::root()));
  540. }
  541. #[test]
  542. fn test_namespace() {
  543. let mut namespace = Namespace::new();
  544. /*
  545. * This should succeed but do nothing.
  546. */
  547. assert_eq!(namespace.add_level(AmlName::from_str("\\").unwrap(), LevelType::Scope), Ok(()));
  548. /*
  549. * Add `\_SB`, also testing that adding a level twice succeeds.
  550. */
  551. assert_eq!(namespace.add_level(AmlName::from_str("\\_SB").unwrap(), LevelType::Scope), Ok(()));
  552. assert_eq!(namespace.add_level(AmlName::from_str("\\_SB").unwrap(), LevelType::Scope), Ok(()));
  553. /*
  554. * Add a device under a level that already exists.
  555. */
  556. assert_eq!(namespace.add_level(AmlName::from_str("\\_SB.PCI0").unwrap(), LevelType::Device), Ok(()));
  557. /*
  558. * Add some deeper scopes.
  559. */
  560. assert_eq!(namespace.add_level(AmlName::from_str("\\FOO").unwrap(), LevelType::Scope), Ok(()));
  561. assert_eq!(namespace.add_level(AmlName::from_str("\\FOO.BAR").unwrap(), LevelType::Scope), Ok(()));
  562. assert_eq!(namespace.add_level(AmlName::from_str("\\FOO.BAR.BAZ").unwrap(), LevelType::Scope), Ok(()));
  563. assert_eq!(namespace.add_level(AmlName::from_str("\\FOO.BAR.BAZ").unwrap(), LevelType::Scope), Ok(()));
  564. assert_eq!(namespace.add_level(AmlName::from_str("\\FOO.BAR.BAZ.QUX").unwrap(), LevelType::Scope), Ok(()));
  565. /*
  566. * Add some things to the scopes to query later.
  567. */
  568. assert!(namespace.add_value(AmlName::from_str("\\MOO").unwrap(), AmlValue::Boolean(true)).is_ok());
  569. assert!(namespace.add_value(AmlName::from_str("\\FOO.BAR.A").unwrap(), AmlValue::Integer(12345)).is_ok());
  570. assert!(namespace.add_value(AmlName::from_str("\\FOO.BAR.B").unwrap(), AmlValue::Integer(6)).is_ok());
  571. assert!(namespace
  572. .add_value(AmlName::from_str("\\FOO.BAR.C").unwrap(), AmlValue::String(String::from("hello, world!")))
  573. .is_ok());
  574. /*
  575. * Get objects using their absolute paths.
  576. */
  577. assert_eq!(namespace.get_by_path(&AmlName::from_str("\\MOO").unwrap()), Ok(&AmlValue::Boolean(true)));
  578. assert_eq!(
  579. namespace.get_by_path(&AmlName::from_str("\\FOO.BAR.A").unwrap()),
  580. Ok(&AmlValue::Integer(12345))
  581. );
  582. assert_eq!(namespace.get_by_path(&AmlName::from_str("\\FOO.BAR.B").unwrap()), Ok(&AmlValue::Integer(6)));
  583. assert_eq!(
  584. namespace.get_by_path(&AmlName::from_str("\\FOO.BAR.C").unwrap()),
  585. Ok(&AmlValue::String(String::from("hello, world!")))
  586. );
  587. /*
  588. * Search for some objects that should use search rules.
  589. */
  590. {
  591. let (name, _) = namespace
  592. .search(&AmlName::from_str("MOO").unwrap(), &AmlName::from_str("\\FOO.BAR.BAZ").unwrap())
  593. .unwrap();
  594. assert_eq!(name, AmlName::from_str("\\MOO").unwrap());
  595. }
  596. {
  597. let (name, _) = namespace
  598. .search(&AmlName::from_str("A").unwrap(), &AmlName::from_str("\\FOO.BAR").unwrap())
  599. .unwrap();
  600. assert_eq!(name, AmlName::from_str("\\FOO.BAR.A").unwrap());
  601. }
  602. {
  603. let (name, _) = namespace
  604. .search(&AmlName::from_str("A").unwrap(), &AmlName::from_str("\\FOO.BAR.BAZ.QUX").unwrap())
  605. .unwrap();
  606. assert_eq!(name, AmlName::from_str("\\FOO.BAR.A").unwrap());
  607. }
  608. }
  609. }