-
-
Notifications
You must be signed in to change notification settings - Fork 81
Expand file tree
/
Copy pathmod.rs
More file actions
3392 lines (3139 loc) · 147 KB
/
mod.rs
File metadata and controls
3392 lines (3139 loc) · 147 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* TODO:
* - Field reads supporting custom handlers
* - Locked fields
* - Bank and index fields
* - Run `_REG` on supported op region handlers
* - Count operations performed and time
* - Correct DefStore / DefCopyObject behaviour
* - Load and LoadTable
* - DefDataRegion
* - Notify
* - DefMatch
*
* - Method recursion depth?
* - Loop timeouts
* - Fuzzing and guarantee panic-free interpretation
*/
pub mod namespace;
pub mod object;
pub mod op_region;
pub mod pci_routing;
pub mod resource;
use crate::{
AcpiError,
AmlTable,
Handle,
Handler,
PhysicalMapping,
platform::AcpiPlatform,
registers::{FixedRegisters, Pm1ControlBit},
sdt::{SdtHeader, facs::Facs, fadt::Fadt},
};
use alloc::{
boxed::Box,
collections::btree_map::BTreeMap,
string::{String, ToString},
sync::Arc,
vec,
vec::Vec,
};
use bit_field::BitField;
use core::{
mem,
slice,
str::FromStr,
sync::atomic::{AtomicU64, Ordering},
};
use log::{info, trace, warn};
use namespace::{AmlName, Namespace, NamespaceLevelKind};
use object::{
DeviceStatus,
FieldFlags,
FieldUnit,
FieldUnitKind,
FieldUpdateRule,
MethodFlags,
Object,
ObjectToken,
ObjectType,
ReferenceKind,
WrappedObject,
};
use op_region::{OpRegion, RegionHandler, RegionSpace};
use pci_types::PciAddress;
use spinning_top::Spinlock;
/// `Interpreter` implements a virtual machine for the dynamic AML bytecode. It can be used by a
/// host operating system to load tables containing AML bytecode (generally the DSDT and SSDTs) and
/// will then manage the AML namespace and all objects created during the life of the system.
pub struct Interpreter<H>
where
H: Handler,
{
handler: H,
pub namespace: Spinlock<Namespace>,
pub object_token: Spinlock<ObjectToken>,
context_stack: Spinlock<Vec<MethodContext>>,
dsdt_revision: u8,
region_handlers: Spinlock<BTreeMap<RegionSpace, Box<dyn RegionHandler>>>,
global_lock_mutex: Handle,
registers: Arc<FixedRegisters<H>>,
facs: Option<PhysicalMapping<H, Facs>>,
}
unsafe impl<H> Send for Interpreter<H> where H: Handler + Send {}
unsafe impl<H> Sync for Interpreter<H> where H: Handler + Send {}
/// The value returned by the `Revision` opcode.
const INTERPRETER_REVISION: u64 = 1;
impl<H> Interpreter<H>
where
H: Handler,
{
/// Construct a new [`Interpreter`]. This does not load any tables - if you have an
/// [`crate::AcpiTables`] already, construct an [`AcpiPlatform`] first and then use
/// [`Interpreter::new_from_platform`]
pub fn new(
handler: H,
dsdt_revision: u8,
registers: Arc<FixedRegisters<H>>,
facs: Option<PhysicalMapping<H, Facs>>,
) -> Interpreter<H> {
info!("Initializing AML interpreter v{}", env!("CARGO_PKG_VERSION"));
let global_lock_mutex = handler.create_mutex();
Interpreter {
handler,
namespace: Spinlock::new(Namespace::new(global_lock_mutex)),
object_token: Spinlock::new(unsafe { ObjectToken::create_interpreter_token() }),
context_stack: Spinlock::new(Vec::new()),
dsdt_revision,
region_handlers: Spinlock::new(BTreeMap::new()),
global_lock_mutex,
registers,
facs,
}
}
/// Construct a new [`Interpreter`] with the given [`AcpiPlatform`].
pub fn new_from_platform(platform: &AcpiPlatform<H>) -> Result<Interpreter<H>, AcpiError> {
fn load_table(interpreter: &Interpreter<impl Handler>, table: AmlTable) -> Result<(), AcpiError> {
let mapping = unsafe {
interpreter.handler.map_physical_region::<SdtHeader>(table.phys_address, table.length as usize)
};
let stream = unsafe {
slice::from_raw_parts(
mapping.virtual_start.as_ptr().byte_add(mem::size_of::<SdtHeader>()) as *const u8,
table.length as usize - mem::size_of::<SdtHeader>(),
)
};
interpreter.load_table(stream).map_err(AcpiError::Aml)?;
Ok(())
}
let registers = platform.registers.clone();
let facs = {
platform.tables.find_table::<Fadt>().and_then(|fadt| fadt.facs_address().ok()).map(
|facs_address| unsafe {
platform.handler.map_physical_region(facs_address, mem::size_of::<Facs>())
},
)
};
let dsdt = platform.tables.dsdt()?;
let interpreter = Interpreter::new(platform.handler.clone(), dsdt.revision, registers, facs);
load_table(&interpreter, dsdt)?;
for ssdt in platform.tables.ssdts() {
load_table(&interpreter, ssdt)?;
}
Ok(interpreter)
}
/// Load the supplied byte stream as an AML table. This should be only the encoded AML stream -
/// not the header at the start of a table. If you've used [`Interpreter::new_from_platform`],
/// you'll likely not need to load any tables manually.
pub fn load_table(&self, stream: &[u8]) -> Result<(), AmlError> {
let context = unsafe { MethodContext::new_from_table(stream) };
self.do_execute_method(context)?;
Ok(())
}
/// Evaluate an object at the given path in the namespace. If the object is a method, this
/// invokes the method with the given set of arguments.
pub fn evaluate(&self, path: AmlName, args: Vec<WrappedObject>) -> Result<WrappedObject, AmlError> {
trace!("Invoking AML method: {}", path);
let object = self.namespace.lock().get(path.clone())?.clone();
match &*object {
Object::Method { .. } => {
self.namespace.lock().add_level(path.clone(), NamespaceLevelKind::MethodLocals)?;
let context = MethodContext::new_from_method(object, args, path)?;
self.do_execute_method(context)
}
Object::NativeMethod { f, .. } => f(&args),
_ => Ok(object),
}
}
pub fn evaluate_if_present(
&self,
path: AmlName,
args: Vec<WrappedObject>,
) -> Result<Option<WrappedObject>, AmlError> {
match self.evaluate(path.clone(), args) {
Ok(result) => Ok(Some(result)),
Err(AmlError::ObjectDoesNotExist(not_present)) => {
if path == not_present {
Ok(None)
} else {
Err(AmlError::ObjectDoesNotExist(not_present))
}
}
Err(other) => Err(other),
}
}
pub fn install_region_handler<RH>(&self, space: RegionSpace, handler: RH)
where
RH: RegionHandler + 'static,
{
let mut handlers = self.region_handlers.lock();
assert!(handlers.get(&space).is_none(), "Tried to install handler for same space twice!");
handlers.insert(space, Box::new(handler));
}
/// Initialize the namespace - this should be called after all tables have been loaded and
/// operation region handlers registered. Specifically, it will call relevant `_STA`, `_INI`,
/// and `_REG` methods.
pub fn initialize_namespace(&self) {
/*
* This should match the initialization order of ACPICA and uACPI.
*/
if let Err(err) = self.evaluate_if_present(AmlName::from_str("\\_INI").unwrap(), vec![]) {
warn!("Invoking \\_INI failed: {:?}", err);
}
if let Err(err) = self.evaluate_if_present(AmlName::from_str("\\_SB._INI").unwrap(), vec![]) {
warn!("Invoking \\_SB._INI failed: {:?}", err);
}
// TODO: run all _REGs for globally-installed handlers (this might need more bookkeeping)
/*
* We can now initialize each device in the namespace. For each device, we evaluate `_STA`,
* which indicates if the device is present and functional. If this method does not exist,
* we assume the device should be initialized.
*
* We then evaluate `_INI` for the device. This can dynamically populate objects such as
* `_ADR`, `_CID`, `_HID`, `_SUN`, and `_UID`, and so is necessary before further
* operation.
*/
let mut num_devices_initialized = 0;
/*
* TODO
* We clone a copy of the namespace here to traverse while executing all the `_STA` and
* `_INI` objects. Avoiding this would be good, but is not easy, as we need
* potentially-mutable access while executing all of the methods.
*/
let mut namespace = self.namespace.lock().clone();
let init_status = namespace.traverse(|path, level| {
match level.kind {
NamespaceLevelKind::Device
| NamespaceLevelKind::Processor
| NamespaceLevelKind::ThermalZone
| NamespaceLevelKind::PowerResource => {
let should_initialize = match self
.evaluate_if_present(AmlName::from_str("_STA").unwrap().resolve(path)?, vec![])
{
Ok(Some(result)) => {
let Object::Integer(result) = *result else { panic!() };
let status = DeviceStatus(result);
status.present() && status.functioning()
}
Ok(None) => true,
Err(err) => {
warn!("Failed to evaluate _STA for device {}: {:?}", path, err);
false
}
};
if should_initialize {
num_devices_initialized += 1;
if let Err(err) =
self.evaluate_if_present(AmlName::from_str("_INI").unwrap().resolve(path)?, vec![])
{
warn!("Failed to evaluate _INI for device {}: {:?}", path, err);
}
Ok(true)
} else {
/*
* If this device should not be initialized, don't initialize it's children.
*/
Ok(false)
}
}
_ => Ok(true),
}
});
if let Err(err) = init_status {
warn!("Error while traversing namespace for devices: {:?}", err);
}
info!("Initialized {} devices", num_devices_initialized);
}
pub fn acquire_global_lock(&self, timeout: u16) -> Result<(), AmlError> {
self.handler.acquire(self.global_lock_mutex, timeout)?;
// Now we've acquired the AML-side mutex, acquire the hardware side
// TODO: count the number of times we have to go round this loop / enforce a timeout?
loop {
if self.try_do_acquire_firmware_lock() {
break Ok(());
} else {
/*
* The lock is owned by the firmware. We have set the pending bit - we now need to
* wait for the firmware to signal it has released the lock.
*
* TODO: this should wait for an interrupt from the firmware. That needs more infra
* so for now let's just spin round and try and acquire it again...
*/
self.handler.release(self.global_lock_mutex);
continue;
}
}
}
/// Attempt to acquire the firmware lock, setting the owned bit if the lock is free. If the
/// lock is not free, sets the pending bit to instruct the firmware to alert us when we can
/// attempt to take ownership of the lock again. Returns `true` if we now have ownership of the
/// lock, and `false` if we need to wait for firmware to release it.
fn try_do_acquire_firmware_lock(&self) -> bool {
let Some(facs) = &self.facs else { return true };
loop {
let global_lock = facs.global_lock.load(Ordering::Relaxed);
let is_owned = global_lock.get_bit(1);
/*
* Compute the new value: either the lock is already owned, and we need to set the
* pending bit and wait, or we can acquire ownership of the lock now. Either way, we
* unconditionally set the owned bit and set the pending bit if the lock is already
* owned.
*/
let mut new_value = global_lock;
new_value.set_bit(0, is_owned);
new_value.set_bit(1, true);
if facs
.global_lock
.compare_exchange(global_lock, new_value, Ordering::AcqRel, Ordering::Acquire)
.is_ok()
{
break !is_owned;
}
}
}
pub fn release_global_lock(&self) -> Result<(), AmlError> {
let is_pending = self.do_release_firmware_lock();
if is_pending {
self.registers.pm1_control_registers.set_bit(Pm1ControlBit::GlobalLockRelease, true).unwrap();
}
Ok(())
}
/// Atomically release the owned and pending bits of the global lock. Returns whether the
/// pending bit was set (this means the firmware is waiting to acquire the lock, and should be
/// informed we're finished with it).
fn do_release_firmware_lock(&self) -> bool {
let Some(facs) = &self.facs else { return false };
loop {
let global_lock = facs.global_lock.load(Ordering::Relaxed);
let is_pending = global_lock.get_bit(0);
let mut new_value = global_lock;
new_value.set_bit(0, false);
new_value.set_bit(1, false);
if facs
.global_lock
.compare_exchange(global_lock, new_value, Ordering::AcqRel, Ordering::Acquire)
.is_ok()
{
break is_pending;
}
}
}
fn do_execute_method(&self, mut context: MethodContext) -> Result<WrappedObject, AmlError> {
/*
* This is the main loop that executes operations. Every op is handled at the top-level of
* the loop to prevent pathological stack growth from nested operations.
*
* The loop has three main stages:
* 1) Check if any in-flight operations are ready to be executed (i.e. have collected all
* their arguments). An operation completing may contribute the last required argument
* of the one above, so this is repeated for as many operations as are ready to be
* retired.
* 2) Look at the next opcode in the stream. If we've run out of opcodes in the current
* block, run logic to determine where in the stream we should move to next. Special
* logic at this level handles things like moving in/out of package definitions, and
* performing control flow.
* 3) When the next opcode is determined, use it to interpret the next portion of the
* stream. If that is data, the correct number of bytes can be consumed and
* contributed to the current in-flight operation. If it's an opcode, a new in-flight
* operation is started, and we go round the loop again.
*
* This scheme is what allows the interpreter to use a loop that somewhat resembles a
* traditional fast bytecode VM, but also provides enough flexibility to handle the
* quirkier parts of the AML grammar, particularly the left-to-right encoding of operands.
*/
loop {
/*
* First, see if we've gathered enough arguments to complete some in-flight operations.
*/
while let Some(op) = context.in_flight.pop_if(|op| op.arguments.len() == op.expected_arguments) {
match op.op {
Opcode::Add
| Opcode::Subtract
| Opcode::Multiply
| Opcode::Divide
| Opcode::ShiftLeft
| Opcode::ShiftRight
| Opcode::Mod
| Opcode::Nand
| Opcode::And
| Opcode::Or
| Opcode::Nor
| Opcode::Xor => {
self.do_binary_maths(&mut context, op)?;
}
Opcode::Not | Opcode::FindSetLeftBit | Opcode::FindSetRightBit => {
self.do_unary_maths(&mut context, op)?;
}
Opcode::Increment | Opcode::Decrement => {
let [Argument::Object(operand)] = &op.arguments[..] else { panic!() };
let token = self.object_token.lock();
let Object::Integer(operand) = (unsafe { operand.gain_mut(&token) }) else {
Err(AmlError::ObjectNotOfExpectedType {
expected: ObjectType::Integer,
got: operand.typ(),
})?
};
let new_value = match op.op {
Opcode::Increment => operand.wrapping_add(1),
Opcode::Decrement => operand.wrapping_sub(1),
_ => unreachable!(),
};
*operand = new_value;
context.retire_op(op);
}
Opcode::LAnd
| Opcode::LOr
| Opcode::LNot
| Opcode::LNotEqual
| Opcode::LLessEqual
| Opcode::LGreaterEqual
| Opcode::LEqual
| Opcode::LGreater
| Opcode::LLess => {
self.do_logical_op(&mut context, op)?;
}
Opcode::ToBuffer => self.do_to_buffer(&mut context, op)?,
Opcode::ToInteger => self.do_to_integer(&mut context, op)?,
Opcode::ToString => self.do_to_string(&mut context, op)?,
Opcode::ToDecimalString | Opcode::ToHexString => {
self.do_to_dec_hex_string(&mut context, op)?
}
Opcode::Mid => self.do_mid(&mut context, op)?,
Opcode::Concat => self.do_concat(&mut context, op)?,
Opcode::ConcatRes => {
let [Argument::Object(source1), Argument::Object(source2), target] = &op.arguments[..]
else {
panic!()
};
let source1 = source1.as_buffer()?;
let source2 = source2.as_buffer()?;
let result = {
let mut buffer = Vec::from(source1);
buffer.extend_from_slice(source2);
// Add a new end-tag
buffer.push(0x78);
// Don't calculate the new real checksum - just use 0
buffer.push(0x00);
Object::Buffer(buffer).wrap()
};
// TODO: use potentially-updated result for return value here
self.do_store(target, result.clone())?;
context.contribute_arg(Argument::Object(result));
context.retire_op(op);
}
Opcode::Reset => {
let [Argument::Object(sync_object)] = &op.arguments[..] else {
panic!();
};
let sync_object = sync_object.clone().unwrap_reference();
if let Object::Event(ref counter) = *sync_object {
counter.store(0, Ordering::Release);
} else {
return Err(AmlError::InvalidOperationOnObject {
op: Operation::ResetEvent,
typ: sync_object.typ(),
});
}
}
Opcode::Signal => {
let [Argument::Object(sync_object)] = &op.arguments[..] else {
panic!();
};
let sync_object = sync_object.clone().unwrap_reference();
if let Object::Event(ref counter) = *sync_object {
counter.fetch_add(1, Ordering::AcqRel);
} else {
return Err(AmlError::InvalidOperationOnObject {
op: Operation::SignalEvent,
typ: sync_object.typ(),
});
}
}
Opcode::Wait => {
let [Argument::Object(sync_object), Argument::Object(timeout)] = &op.arguments[..] else {
panic!();
};
let sync_object = sync_object.clone().unwrap_reference();
let timeout = u64::min(timeout.as_integer()?, 0xffff);
if let Object::Event(ref counter) = *sync_object {
/*
* `Wait` returns a non-zero value if a timeout occurs and the event
* was not signaled, and zero if it was. Timeout is specified in
* milliseconds, should relinquish processor control (we use
* `Handler::sleep` to do so) and a value of `0xffff` specifies that
* the operation should wait indefinitely.
*/
let mut remaining_sleep = timeout;
let mut timed_out = true;
'signaled: while remaining_sleep > 0 {
loop {
/*
* Try to decrement the counter. If it's zero after a load, we
* haven't been signalled and should wait for a bit. If it's
* non-zero, we were signalled and should stop waiting.
*/
let value = counter.load(Ordering::Acquire);
if value == 0 {
break;
}
if counter
.compare_exchange(value, value - 1, Ordering::AcqRel, Ordering::Acquire)
.is_ok()
{
timed_out = false;
break 'signaled;
}
}
let to_sleep = u64::min(timeout, 10);
if timeout < 0xffff {
remaining_sleep -= to_sleep
}
self.handler.sleep(to_sleep);
}
context.contribute_arg(Argument::Object(
Object::Integer(if timed_out { u64::MAX } else { 0 }).wrap(),
));
} else {
return Err(AmlError::InvalidOperationOnObject {
op: Operation::WaitEvent,
typ: sync_object.typ(),
});
}
}
Opcode::FromBCD => self.do_from_bcd(&mut context, op)?,
Opcode::ToBCD => self.do_to_bcd(&mut context, op)?,
Opcode::Name => {
let [Argument::Namestring(name), Argument::Object(object)] = &op.arguments[..] else {
panic!()
};
let name = name.resolve(&context.current_scope)?;
self.namespace.lock().insert(name, object.clone())?;
context.retire_op(op);
}
Opcode::Fatal => {
let [Argument::ByteData(typ), Argument::DWordData(code), Argument::Object(arg)] =
&op.arguments[..]
else {
panic!()
};
let arg = arg.as_integer()?;
self.handler.handle_fatal_error(*typ, *code, arg);
context.retire_op(op);
}
Opcode::OpRegion => {
let [
Argument::Namestring(name),
Argument::ByteData(region_space),
Argument::Object(region_offset),
Argument::Object(region_length),
] = &op.arguments[..]
else {
panic!()
};
let region_offset = region_offset.clone().unwrap_transparent_reference();
let region_length = region_length.clone().unwrap_transparent_reference();
let region = Object::OpRegion(OpRegion {
space: RegionSpace::from(*region_space),
base: region_offset.as_integer()?,
length: region_length.as_integer()?,
parent_device_path: context.current_scope.clone(),
});
self.namespace.lock().insert(name.resolve(&context.current_scope)?, region.wrap())?;
context.retire_op(op);
}
Opcode::DataRegion => {
let [
Argument::Namestring(name),
Argument::Object(signature),
Argument::Object(oem_id),
Argument::Object(oem_table_id),
] = &op.arguments[..]
else {
panic!()
};
let _signature = signature.as_string()?;
let _oem_id = oem_id.as_string()?;
let _oem_table_id = oem_table_id.as_string()?;
// TODO: once this is integrated into the rest of the crate, load the table
log::warn!(
"DefDataRegion encountered in AML! We don't actually support these - produced region will be incorrect"
);
let region = Object::OpRegion(OpRegion {
space: RegionSpace::SystemMemory,
base: 0,
length: 0,
parent_device_path: context.current_scope.clone(),
});
self.namespace.lock().insert(name.resolve(&context.current_scope)?, region.wrap())?;
context.retire_op(op);
}
Opcode::Buffer => {
let [
Argument::TrackedPc(start_pc),
Argument::PkgLength(pkg_length),
Argument::Object(buffer_size),
] = &op.arguments[..]
else {
panic!()
};
let buffer_size = buffer_size.clone().unwrap_transparent_reference().as_integer()?;
let buffer_len = pkg_length - (context.current_block.pc - start_pc);
let mut buffer = vec![0; buffer_size as usize];
buffer[0..buffer_len].copy_from_slice(
&context.current_block.stream()
[context.current_block.pc..(context.current_block.pc + buffer_len)],
);
context.current_block.pc += buffer_len;
context.contribute_arg(Argument::Object(Object::Buffer(buffer).wrap()));
context.retire_op(op);
}
Opcode::Package => {
let mut elements = Vec::with_capacity(op.expected_arguments);
for arg in &op.arguments {
let Argument::Object(object) = arg else { panic!() };
elements.push(object.clone());
}
/*
* We can end up completing a package's in-flight op in two circumstances:
* - If the correct number of elements are supplied, we end up here
* first, and then later in the block's finishing logic.
* - If less elements are supplied, we end up in the block's finishing
* logic to add some `Uninitialized`s, then go round again to complete
* the in-flight operation.
*
* To make these consistent, we always remove the block here, making sure
* we've finished it as a sanity check.
*/
assert_eq!(context.current_block.kind, BlockKind::Package);
assert_eq!(context.peek(), Err(AmlError::RunOutOfStream));
context.current_block = context.block_stack.pop().unwrap();
context.contribute_arg(Argument::Object(Object::Package(elements).wrap()));
context.retire_op(op);
}
Opcode::VarPackage => {
let Argument::Object(total_elements) = &op.arguments[0] else { panic!() };
let total_elements =
total_elements.clone().unwrap_transparent_reference().as_integer()? as usize;
let mut elements = Vec::with_capacity(total_elements);
for arg in &op.arguments[1..] {
let Argument::Object(object) = arg else { panic!() };
elements.push(object.clone());
}
/*
* As above, we always remove the block here after the in-flight op has
* been retired.
*/
assert_eq!(context.current_block.kind, BlockKind::VarPackage);
assert_eq!(context.peek(), Err(AmlError::RunOutOfStream));
context.current_block = context.block_stack.pop().unwrap();
context.contribute_arg(Argument::Object(Object::Package(elements).wrap()));
context.retire_op(op);
}
Opcode::If => {
let [
Argument::TrackedPc(start_pc),
Argument::PkgLength(then_length),
Argument::Object(predicate),
] = &op.arguments[..]
else {
panic!()
};
let predicate = predicate.as_integer()?;
let remaining_then_length = then_length - (context.current_block.pc - start_pc);
if predicate > 0 {
context.start_new_block(BlockKind::IfThenBranch, remaining_then_length);
} else {
context.current_block.pc += remaining_then_length;
/*
* Skip over the prolog to the else branch if present. Also handle if
* there are no more bytes to peek - the `If` op could be the last op
* in a block.
*/
const DEF_ELSE_OP: u8 = 0xa1;
match context.peek() {
Ok(DEF_ELSE_OP) => {
context.next()?;
let _else_length = context.pkglength()?;
}
Ok(_) => (),
Err(AmlError::RunOutOfStream) => (),
Err(other) => Err(other)?,
}
}
context.retire_op(op);
}
opcode @ Opcode::CreateBitField
| opcode @ Opcode::CreateByteField
| opcode @ Opcode::CreateWordField
| opcode @ Opcode::CreateDWordField
| opcode @ Opcode::CreateQWordField => {
let [Argument::Object(buffer), Argument::Object(index)] = &op.arguments[..] else {
panic!()
};
let name = context.namestring()?;
let index = index.as_integer()?;
let (offset, length) = match opcode {
Opcode::CreateBitField => (index, 1),
Opcode::CreateByteField => (index * 8, 8),
Opcode::CreateWordField => (index * 8, 16),
Opcode::CreateDWordField => (index * 8, 32),
Opcode::CreateQWordField => (index * 8, 64),
_ => unreachable!(),
};
self.namespace.lock().insert(
name.resolve(&context.current_scope)?,
Object::BufferField { buffer: buffer.clone(), offset: offset as usize, length }.wrap(),
)?;
context.retire_op(op);
}
Opcode::CreateField => {
let [Argument::Object(buffer), Argument::Object(bit_index), Argument::Object(num_bits)] =
&op.arguments[..]
else {
panic!()
};
let name = context.namestring()?;
let bit_index = bit_index.as_integer()?;
let num_bits = num_bits.as_integer()?;
self.namespace.lock().insert(
name.resolve(&context.current_scope)?,
Object::BufferField {
buffer: buffer.clone(),
offset: bit_index as usize,
length: num_bits as usize,
}
.wrap(),
)?;
context.retire_op(op);
}
Opcode::Store => {
let [Argument::Object(object), target] = &op.arguments[..] else { panic!() };
self.do_store(target, object.clone())?;
context.retire_op(op);
}
Opcode::RefOf => {
let [Argument::Object(object)] = &op.arguments[..] else { panic!() };
let reference =
Object::Reference { kind: ReferenceKind::RefOf, inner: object.clone() }.wrap();
context.contribute_arg(Argument::Object(reference));
context.retire_op(op);
}
Opcode::CondRefOf => {
let [Argument::Object(object), target] = &op.arguments[..] else { panic!() };
let result = if let Object::Reference { kind: ReferenceKind::Unresolved, .. } = **object {
Object::Integer(0)
} else {
let reference =
Object::Reference { kind: ReferenceKind::RefOf, inner: object.clone() }.wrap();
self.do_store(target, reference)?;
Object::Integer(u64::MAX)
};
context.contribute_arg(Argument::Object(result.wrap()));
context.retire_op(op);
}
Opcode::DerefOf => {
let [Argument::Object(object)] = &op.arguments[..] else { panic!() };
let result = match **object {
Object::Reference { kind: _, inner: _ } => object.clone().unwrap_reference(),
Object::String(_) => {
let path = AmlName::from_str(&object.as_string().unwrap())?;
let (_, object) = self.namespace.lock().search(&path, &context.current_scope)?;
object.clone()
}
_ => {
return Err(AmlError::ObjectNotOfExpectedType {
expected: ObjectType::Reference,
got: object.typ(),
});
}
};
context.contribute_arg(Argument::Object(result));
context.retire_op(op);
}
Opcode::Sleep => {
let [Argument::Object(msec)] = &op.arguments[..] else { panic!() };
self.handler.sleep(msec.as_integer()?);
context.retire_op(op);
}
Opcode::Stall => {
let [Argument::Object(usec)] = &op.arguments[..] else { panic!() };
self.handler.stall(usec.as_integer()?);
context.retire_op(op);
}
Opcode::Acquire => {
let [Argument::Object(mutex)] = &op.arguments[..] else { panic!() };
let Object::Mutex { mutex, sync_level: _ } = **mutex else {
Err(AmlError::InvalidOperationOnObject { op: Operation::Acquire, typ: mutex.typ() })?
};
let timeout = context.next_u16()?;
// TODO: should we do something with the sync level??
if mutex == self.global_lock_mutex {
self.acquire_global_lock(timeout)?;
} else {
self.handler.acquire(mutex, timeout)?;
}
context.retire_op(op);
}
Opcode::Release => {
let [Argument::Object(mutex)] = &op.arguments[..] else { panic!() };
let Object::Mutex { mutex, sync_level: _ } = **mutex else {
Err(AmlError::InvalidOperationOnObject { op: Operation::Release, typ: mutex.typ() })?
};
// TODO: should we do something with the sync level??
if mutex == self.global_lock_mutex {
self.release_global_lock()?;
} else {
self.handler.release(mutex);
}
context.retire_op(op);
}
Opcode::InternalMethodCall => {
let [Argument::Object(method), Argument::Namestring(method_scope)] = &op.arguments[0..2]
else {
panic!()
};
let args = op.arguments[2..]
.iter()
.map(|arg| {
if let Argument::Object(arg) = arg {
arg.clone()
} else {
panic!();
}
})
.collect();
if let Object::Method { .. } = **method {
self.namespace
.lock()
.add_level(method_scope.clone(), NamespaceLevelKind::MethodLocals)?;
let new_context =
MethodContext::new_from_method(method.clone(), args, method_scope.clone())?;
let old_context = mem::replace(&mut context, new_context);
self.context_stack.lock().push(old_context);
context.retire_op(op);
} else if let Object::NativeMethod { ref f, .. } = **method {
let result = f(&args)?;
context.contribute_arg(Argument::Object(result));
} else {
panic!();
}
}
Opcode::Return => {
let [Argument::Object(object)] = &op.arguments[..] else { panic!() };
let object = object.clone().unwrap_transparent_reference();
if let Some(last) = self.context_stack.lock().pop() {
context = last;
context.contribute_arg(Argument::Object(object.clone()));
context.retire_op(op);
} else {
/*
* If this is the top-most context, this is a `Return` from the actual
* method.
*/
return Ok(object.clone());
}
}
Opcode::ObjectType => {
let [Argument::Object(object)] = &op.arguments[..] else { panic!() };
// TODO: this should technically support scopes as well - this is less easy
// (they should return `0`)
let typ = match object.typ() {
ObjectType::Uninitialized => 0,
ObjectType::Integer => 1,
ObjectType::String => 2,
ObjectType::Buffer => 3,
ObjectType::Package => 4,
ObjectType::FieldUnit => 5,
ObjectType::Device => 6,
ObjectType::Event => 7,
ObjectType::Method => 8,
ObjectType::Mutex => 9,
ObjectType::OpRegion => 10,
ObjectType::PowerResource => 11,
ObjectType::Processor => 12,
ObjectType::ThermalZone => 13,
ObjectType::BufferField => 14,
// XXX: 15 is reserved
ObjectType::Debug => 16,
ObjectType::Reference => panic!(),
ObjectType::RawDataBuffer => todo!(),
};
context.contribute_arg(Argument::Object(Object::Integer(typ).wrap()));
context.retire_op(op);
}
Opcode::SizeOf => self.do_size_of(&mut context, op)?,
Opcode::Index => self.do_index(&mut context, op)?,
Opcode::BankField => {
let [
Argument::TrackedPc(start_pc),
Argument::PkgLength(pkg_length),
Argument::Namestring(region_name),
Argument::Namestring(bank_name),
Argument::Object(bank_value),
] = &op.arguments[..]
else {
panic!()
};
let bank_value = bank_value.as_integer()?;
let field_flags = context.next()?;
let (region, bank) = {
let namespace = self.namespace.lock();
let (_, region) = namespace.search(region_name, &context.current_scope)?;
let (_, bank) = namespace.search(bank_name, &context.current_scope)?;
(region, bank)
};
let kind = FieldUnitKind::Bank { region, bank, bank_value };
self.parse_field_list(&mut context, kind, *start_pc, *pkg_length, field_flags)?;
context.retire_op(op);
}
Opcode::While => {
/*
* We've just evaluated the predicate for an iteration of a while loop. If
* false, skip over the rest of the loop, otherwise carry on.
*/
let [Argument::Object(predicate)] = &op.arguments[..] else { panic!() };
let predicate = predicate.as_integer()?;
if predicate == 0 {
// Exit from the while loop by skipping out of the current block
context.current_block = context.block_stack.pop().unwrap();
context.retire_op(op);
}
}
_ => panic!("Unexpected operation has created in-flight op!"),
}
}
/*
* Now that we've retired as many in-flight operations as we have arguments for, move
* forward in the AML stream.
*/
let opcode = match context.opcode() {
Ok(opcode) => opcode,
Err(AmlError::RunOutOfStream) => {
/*
* We've reached the end of the current block. What we should do about this