-
-
Notifications
You must be signed in to change notification settings - Fork 990
Expand file tree
/
Copy pathactivation.rs
More file actions
2989 lines (2367 loc) · 97.7 KB
/
activation.rs
File metadata and controls
2989 lines (2367 loc) · 97.7 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
//! Activation frames
use crate::avm2::Multiname;
use crate::avm2::Namespace;
use crate::avm2::array::ArrayStorage;
use crate::avm2::class::Class;
use crate::avm2::domain::Domain;
use crate::avm2::e4x::{escape_attribute_value, escape_element_value};
use crate::avm2::error::{
make_error_1016, make_error_1040, make_error_1041, make_error_1063, make_error_1065,
make_error_1108, make_error_1119, make_error_1123, make_error_1127, make_error_1506,
make_null_or_undefined_error,
};
use crate::avm2::function::FunctionArgs;
use crate::avm2::method::{Method, NativeMethodImpl, ResolvedParamConfig};
use crate::avm2::object::{
ArrayObject, ByteArrayObject, ClassObject, FunctionObject, NamespaceObject, ScriptObject,
XmlListObject,
};
use crate::avm2::object::{Object, TObject};
use crate::avm2::op::{LookupSwitch, Op};
use crate::avm2::scope::{Scope, ScopeChain, search_scope_stack};
use crate::avm2::script::Script;
use crate::avm2::stack::StackFrame;
use crate::avm2::value::Value;
use crate::avm2::{Avm2, Error};
use crate::context::UpdateContext;
use crate::string::{AvmAtom, AvmString, HasStringContext, StringContext};
use crate::tag_utils::SwfMovie;
use gc_arena::Gc;
use ruffle_macros::istr;
use std::cell::Cell;
use std::cmp::{Ordering, min};
use std::sync::Arc;
use swf::avm2::types::MethodFlags as AbcMethodFlags;
/// Represents a single activation of a given AVM2 function or keyframe.
pub struct Activation<'a, 'gc: 'a> {
/// The number of locals this method uses.
num_locals: usize,
/// This represents the outer scope of the method that is executing.
///
/// The outer scope gives an activation access to the "outer world", including
/// the current Domain.
outer: ScopeChain<'gc>,
/// The domain of the original AS3 caller.
///
/// This is intended exclusively for builtin methods to access the domain of the
/// bytecode method that called it.
///
/// If this activation was not made for a builtin method, this will be the
/// current domain instead.
caller_domain: Option<Domain<'gc>>,
/// The movie that called this builtin method.
/// This is intended to be used only for builtin methods- if this activation's method
/// is a bytecode method, the movie will instead be the movie that the bytecode method came from.
caller_movie: Option<Arc<SwfMovie>>,
/// The superclass of the class that yielded the currently executing method.
///
/// This is used to maintain continuity when multiple methods supercall
/// into one another. For example, if a class method supercalls a
/// grandparent class's method, then this value will be the grandparent's
/// class object. Then, if we supercall again, we look up supermethods from
/// the great-grandparent class, preventing us from accidentally calling
/// the same method again.
///
/// This will not be available outside of method, setter, or getter calls.
bound_superclass_object: Option<ClassObject<'gc>>,
/// The stack frame.
stack: StackFrame<'a, 'gc>,
/// The index where the scope frame starts.
scope_depth: usize,
/// In avmplus, some behavior differs slightly depending on whether the JIT
/// or the interpreter is used. Most methods are executed in "JIT mode", but
/// in some cases "interpreter mode" is used instead: for example, script
/// initializers always execute in "interpreter mode". We keep track of
/// whether the current method would be interpreted or JITted in this flag.
/// See `MethodData.is_interpreted` for more information.
is_interpreter: bool,
/// The default XML namespace for E4X operations within this activation.
///
/// Set by the `dxns`/`dxnslate` opcodes. Propagated to child activations:
/// native methods always inherit the caller's value, bytecode methods with
/// the `SET_DXNS` flag start with `None` (the opcode will set their own),
/// and bytecode methods without the flag inherit the caller's value.
///
/// NOTE: In avmplus this is more nuanced — the default namespace is a property
/// of MethodFrames/MethodEnvs/scopes, and closures capture the dxns value from
/// the scope at the time they are created (see `MethodFrame::findDxns`).
/// Our per-Activation approach doesn't handle that closure-capture behavior.
/// See <https://github.com/ruffle-rs/ruffle/pull/21014> for details.
default_xml_namespace: Option<AvmString<'gc>>,
pub context: &'a mut UpdateContext<'gc>,
}
impl<'gc> HasStringContext<'gc> for Activation<'_, 'gc> {
#[inline(always)]
fn strings_ref(&self) -> &StringContext<'gc> {
&self.context.strings
}
}
impl<'a, 'gc> Activation<'a, 'gc> {
/// Convenience method to retrieve the current GC context. Note that explicitly writing
/// `self.context.gc_context` can be sometimes necessary to satisfy the borrow checker.
#[inline(always)]
pub fn gc(&self) -> &'gc gc_arena::Mutation<'gc> {
self.context.gc()
}
#[inline(always)]
pub fn strings(&mut self) -> &mut StringContext<'gc> {
&mut self.context.strings
}
/// Construct an activation that does not represent any particular scope.
///
/// This exists primarily for non-AVM2 related manipulations of the
/// interpreter environment that require an activation. For example,
/// loading traits into an object, or running tests.
///
/// It is a logic error to attempt to run AVM2 code in a nothing
/// `Activation`.
pub fn from_nothing(context: &'a mut UpdateContext<'gc>) -> Self {
Self {
num_locals: 0,
outer: ScopeChain::new(context.avm2.stage_domain),
caller_domain: None,
caller_movie: None,
bound_superclass_object: None,
stack: StackFrame::empty(),
scope_depth: context.avm2.scope_stack.len(),
is_interpreter: false,
default_xml_namespace: None,
context,
}
}
/// Like `from_nothing`, but with a specified domain.
///
/// This should be used when you actually need to run AVM2 code, but
/// don't have a particular scope to run it in. For example, this is
/// used to run frame scripts for AVM2 movies.
///
/// The 'Domain' should come from the SwfMovie associated with whatever
/// action you're performing. When running frame scripts, this is the
/// `SwfMovie` associated with the `MovieClip` being processed.
pub fn from_domain(context: &'a mut UpdateContext<'gc>, domain: Domain<'gc>) -> Self {
Self {
num_locals: 0,
outer: ScopeChain::new(context.avm2.stage_domain),
caller_domain: Some(domain),
caller_movie: None,
bound_superclass_object: None,
stack: StackFrame::empty(),
scope_depth: context.avm2.scope_stack.len(),
is_interpreter: false,
default_xml_namespace: None,
context,
}
}
/// Finds an object on either the current or outer scope of this activation by definition.
pub fn find_definition(
&mut self,
name: &Multiname<'gc>,
) -> Result<Option<Value<'gc>>, Error<'gc>> {
let outer_scope = self.outer;
if let Some(obj) = search_scope_stack(self, name, outer_scope.is_empty()) {
Ok(Some(obj))
} else if let Some(obj) = outer_scope.find(name, self)? {
Ok(Some(obj))
} else {
let global = self.global_scope();
// Check global scope and its prototypes recursively
// NOTE: We still have to check prototypes if the global scope is
// a primitive
let mut proto = Some(global);
while let Some(current_proto) = proto {
if let Some(current_proto) = current_proto.as_object() {
if current_proto.base().has_own_dynamic_property(name) {
return Ok(Some(global));
}
}
proto = current_proto.proto(self).map(|o| o.into());
}
Ok(None)
}
}
/// Statically resolve all of the parameters for a native method.
///
/// This function makes no attempt to enforce a given method's parameter
/// count limits or to package variadic arguments.
///
/// The returned list of parameters will be coerced to the stated types in
/// the signature, with missing parameters filled in with defaults.
pub fn resolve_parameters(
&mut self,
method: Method<'gc>,
user_arguments: FunctionArgs<'_, 'gc>,
signature: &[ResolvedParamConfig<'gc>],
) -> Result<Vec<Value<'gc>>, Error<'gc>> {
let mut arguments_list = Vec::new();
for (arg, param_config) in user_arguments.iter().zip(signature.iter()) {
let coerced_arg = if let Some(param_class) = param_config.param_type {
arg.coerce_to_type(self, param_class)?
} else {
arg
};
arguments_list.push(coerced_arg);
}
match user_arguments.len().cmp(&signature.len()) {
Ordering::Greater => {
let user_arguments = &user_arguments.to_slice();
// Variadic parameters exist, just push them into the list
arguments_list.extend_from_slice(&user_arguments[signature.len()..])
}
Ordering::Less => {
// Apply remaining default parameters
for param_config in signature[user_arguments.len()..].iter() {
let arg = if let Some(default_value) = ¶m_config.default_value {
*default_value
} else {
return Err(make_error_1063(self, method, user_arguments.len()));
};
let coerced_arg = if let Some(param_class) = param_config.param_type {
arg.coerce_to_type(self, param_class)?
} else {
arg
};
arguments_list.push(coerced_arg);
}
}
_ => {}
}
Ok(arguments_list)
}
/// Create an `arguments` or `rest` object for a given method. This function
/// expects the rest of the arguments to already be on the AVM stack.
#[inline(never)]
fn create_varargs_object(
&mut self,
method: Method<'gc>,
signature: &[ResolvedParamConfig<'gc>],
user_arguments: FunctionArgs<'_, 'gc>,
callee: Option<FunctionObject<'gc>>,
) -> ArrayObject<'gc> {
let mut all_arguments = Vec::new();
// Unfortunately we need to allocate now: we need to put all the
// arguments we just processed into a Vec, so `arguments` or `rest`
// can put them into an ArrayObject. The missing argument check
// in `init_from_method` ensures that we have at least `signature.len()`
// arguments on the stack right now.
for i in 0..signature.len() {
let arg = self.stack.peek(signature.len() - i - 1);
all_arguments.push(arg);
}
// We put all the non-variadic arguments into the Vec, but there
// could have been more passed to the function. Add them now.
for i in signature.len()..user_arguments.len() {
let arg = user_arguments.get_at(i);
all_arguments.push(arg);
}
let args_array = if method.method().flags.contains(AbcMethodFlags::NEED_REST) {
if let Some(rest_args) = all_arguments.get(signature.len()..) {
ArrayStorage::from_args(rest_args)
} else {
ArrayStorage::new(0)
}
} else if method
.method()
.flags
.contains(AbcMethodFlags::NEED_ARGUMENTS)
{
ArrayStorage::from_args(&all_arguments[..user_arguments.len()])
} else {
unreachable!();
};
let args_object = ArrayObject::from_storage(self.context, args_array);
if method
.method()
.flags
.contains(AbcMethodFlags::NEED_ARGUMENTS)
{
let string_callee = istr!(self, "callee");
let callee = callee
.expect("Should have a callee if the method is NEED_ARGUMENTS")
.into();
args_object.set_dynamic_property(string_callee, callee, self.gc());
args_object.set_local_property_is_enumerable(self.gc(), string_callee, false);
}
args_object
}
/// Construct an activation for the execution of a particular bytecode
/// method.
/// NOTE: this is intended to be used immediately after from_nothing(),
/// as a more efficient replacement for direct `Activation::from_method()`
#[expect(clippy::too_many_arguments)]
pub fn init_from_method(
&mut self,
method: Method<'gc>,
outer: ScopeChain<'gc>,
this: Value<'gc>,
user_arguments: FunctionArgs<'_, 'gc>,
stack_frame: StackFrame<'a, 'gc>,
bound_superclass_object: Option<ClassObject<'gc>>,
callee: Option<FunctionObject<'gc>>,
caller_dxns: Option<AvmString<'gc>>,
) -> Result<(), Error<'gc>> {
let body = method
.body()
.expect("Cannot execute non-native method without body");
let num_locals = body.num_locals as usize;
let has_rest_or_args = method.is_variadic();
if let Some(bound_class) = method.bound_class() {
assert!(this.is_of_type(bound_class));
}
self.num_locals = num_locals;
self.outer = outer;
self.caller_domain = Some(outer.domain());
self.caller_movie = Some(method.owner_movie());
self.bound_superclass_object = bound_superclass_object;
self.stack = stack_frame;
self.scope_depth = self.context.avm2.scope_stack.len();
self.is_interpreter = method.is_interpreted();
// Resolve parameters and return type
method.resolve_info(self)?;
// Everything is now setup for the verifier to run
method.verify(self)?;
let signature = method.resolved_param_config();
if user_arguments.len() > signature.len() && !has_rest_or_args && !method.is_unchecked() {
return Err(make_error_1063(self, method, user_arguments.len()));
}
// Create locals
self.push_stack(this);
// Statically verify all non-variadic, provided parameters.
let static_arg_count = min(user_arguments.len(), signature.len());
for (i, param_config) in signature.iter().enumerate().take(static_arg_count) {
let arg = user_arguments.get_at(i);
let coerced_arg = if let Some(param_class) = param_config.param_type {
arg.coerce_to_type(self, param_class)?
} else {
arg
};
self.push_stack(coerced_arg);
}
// Now add missing arguments
if user_arguments.len() < signature.len() {
// Apply remaining default parameters
for param_config in signature[user_arguments.len()..].iter() {
let arg = if let Some(default_value) = ¶m_config.default_value {
*default_value
} else if method.is_unchecked() {
Value::Undefined
} else {
return Err(make_error_1063(self, method, user_arguments.len()));
};
let coerced_arg = if let Some(param_class) = param_config.param_type {
arg.coerce_to_type(self, param_class)?
} else {
arg
};
self.push_stack(coerced_arg);
}
}
// Finally, handle variadic arguments
if has_rest_or_args {
let args_object = self.create_varargs_object(method, signature, user_arguments, callee);
self.push_stack(args_object);
}
// `Stack::get_stack_frame` already initializes all values on the frame
// to undefined, so we just have to increase the stack pointer
self.reset_stack();
// Inherit the caller's default XML namespace if this method doesn't
// set its own via dxns opcodes.
if !method.sets_dxns() {
self.default_xml_namespace = caller_dxns;
}
Ok(())
}
/// Construct an activation for the execution of a builtin method.
///
/// It is a logic error to attempt to execute builtins within the same
/// activation as the method or script that called them. You must use this
/// function to construct a new activation for the builtin so that it can
/// properly supercall.
pub fn from_builtin(
context: &'a mut UpdateContext<'gc>,
bound_superclass_object: Option<ClassObject<'gc>>,
outer: ScopeChain<'gc>,
caller_domain: Option<Domain<'gc>>,
caller_movie: Option<Arc<SwfMovie>>,
caller_dxns: Option<AvmString<'gc>>,
) -> Self {
Self {
num_locals: 0,
outer,
caller_domain,
caller_movie,
bound_superclass_object,
stack: StackFrame::empty(),
scope_depth: context.avm2.scope_stack.len(),
is_interpreter: false,
default_xml_namespace: caller_dxns,
context,
}
}
/// Call the superclass's instance initializer.
///
/// This method may panic if called with a Null or Undefined receiver.
fn super_init(
&mut self,
receiver: Value<'gc>,
args: FunctionArgs<'_, 'gc>,
) -> Result<Value<'gc>, Error<'gc>> {
let bound_superclass_object = self
.bound_superclass_object
.expect("Superclass object is required to run super_init");
bound_superclass_object.call_init(receiver, args, self)
}
/// Retrieve a local register.
pub fn local_register(&mut self, id: u32) -> Value<'gc> {
// Verification guarantees that this points to a local register
self.stack.value_at(id as usize)
}
/// Set a local register.
pub fn set_local_register(&mut self, id: u32, value: impl Into<Value<'gc>>) {
// Verification guarantees that this is valid
self.stack.set_value_at(id as usize, value.into());
}
/// Returns whether this Activation is running in "interpreter mode" as
/// opposed to "JIT mode". Note that these modes do not actually correspond
/// to whether the method is being interpreted or JITted.
pub fn is_interpreter(&self) -> bool {
self.is_interpreter
}
/// Get the current default XML namespace URI for this activation, if any.
pub fn default_xml_namespace(&self) -> Option<AvmString<'gc>> {
self.default_xml_namespace
}
/// Retrieve the outer scope of this activation
pub fn outer(&self) -> ScopeChain<'gc> {
self.outer
}
/// Sets the outer scope of this activation
pub fn set_outer(&mut self, new_outer: ScopeChain<'gc>) {
self.outer = new_outer;
}
/// Creates a new ScopeChain by chaining the current state of this
/// activation's scope stack with the outer scope.
pub fn create_scopechain(&self) -> ScopeChain<'gc> {
self.outer.chain(self.gc(), self.scope_frame())
}
/// Returns the domain of the original AS3 caller. This will be `None`
/// if this activation was constructed with `from_nothing`
pub fn caller_domain(&self) -> Option<Domain<'gc>> {
self.caller_domain
}
/// Returns the movie of the original AS3 caller. This will be `None`
/// if this activation was constructed with `from_nothing`
pub fn caller_movie(&self) -> Option<Arc<SwfMovie>> {
self.caller_movie.clone()
}
/// Like `caller_movie()`, but returns the root movie if `caller_movie`
/// is `None`. This matches what FP does in most cases.
pub fn caller_movie_or_root(&self) -> Arc<SwfMovie> {
self.caller_movie().unwrap_or(self.context.root_swf.clone())
}
/// Returns the global scope of this activation.
///
/// The global scope refers to scope at the bottom of the
/// outer scope. If the outer scope is empty, we use the bottom
/// of the current scope stack instead.
///
/// The verifier guarantees that there is always a global scope
/// when this function is called.
pub fn global_scope(&self) -> Value<'gc> {
let outer_scope = self.outer;
outer_scope
.get(0)
.unwrap_or_else(|| self.scope_frame()[0])
.values()
}
pub fn avm2(&mut self) -> &mut Avm2<'gc> {
self.context.avm2
}
pub fn scope_frame(&self) -> &[Scope<'gc>] {
&self.context.avm2.scope_stack[self.scope_depth..]
}
/// Pushes a value onto the operand stack.
#[inline(always)]
pub fn push_stack(&self, value: impl Into<Value<'gc>>) {
self.stack.push(value.into());
}
/// Pops a value off the operand stack.
#[inline(always)]
#[must_use]
pub fn pop_stack(&self) -> Value<'gc> {
self.stack.pop()
}
/// Pops multiple values off the operand stack, collecting them into a collection.
#[inline]
#[must_use]
pub fn pop_stack_args<C>(&self, arg_count: u32) -> C
where
C: FromIterator<Value<'gc>>,
{
self.stack
.pop_args(arg_count)
.iter()
.map(Cell::get)
.collect()
}
/// Pops multiple values off the operand stack.
#[inline]
#[must_use]
pub fn get_args(&self, arg_count: u32) -> FunctionArgs<'a, 'gc> {
let slice = self.stack.pop_args(arg_count);
FunctionArgs::from_cell_slice(slice)
}
/// Pushes a scope onto the scope stack.
#[inline]
pub fn push_scope(&mut self, scope: Scope<'gc>) {
self.avm2().push_scope(scope);
}
/// Pops a scope off of the scope stack.
#[inline]
pub fn pop_scope(&mut self) {
self.avm2().pop_scope();
}
/// Cleans up after this Activation. This removes stack and local entries,
/// and clears the scope stack. This method must be called after an Activation
/// created with `Activation::init_from_activation` or `Activation::from_script`
/// is finished executing.
///
/// This function should take `mut self` instead of `&mut self`, but that
/// results in worse codegen (the entire Activation is moved).
#[inline]
pub fn cleanup(&mut self) {
self.clear_scope();
let stack = self.context.avm2.stack;
stack.dispose_stack_frame(self.stack.take());
}
/// Clears the operand stack used by this activation.
///
/// This is called `reset_stack` because it sets the stack pointer to the
/// first stack entry, which also makes it useful for initializing the stack.
#[inline]
fn reset_stack(&self) {
// This sets the stack pointer to the first stack entry, which is right
// after all the entries for local registers
self.stack.set_stack_pointer(self.num_locals);
}
/// Clears the scope stack used by this activation.
#[inline]
fn clear_scope(&mut self) {
let scope_depth = self.scope_depth;
self.avm2().scope_stack.truncate(scope_depth);
}
/// Get the superclass of the class that defined the currently-executing
/// method, if it exists.
///
/// If the currently-executing method is not part of a class, then this
/// returns `None`.
pub fn bound_superclass_object(&self) -> Option<ClassObject<'gc>> {
self.bound_superclass_object
}
pub fn run_actions(&mut self, method: Method<'gc>) -> Result<Value<'gc>, Error<'gc>> {
// The method must be verified at this point
let verified_info = method.get_verified_info();
let opcodes = verified_info.parsed_code.as_slice();
self.timeout_check()?;
let mut ip = 0;
loop {
let op = &opcodes[ip];
ip += 1;
avm_debug!(self.avm2(), "Opcode: {op:?}");
let result = match op {
Op::PushDouble { value } => self.op_push_double(*value),
Op::PushFalse => self.op_push_false(),
Op::PushInt { value } => self.op_push_int(*value),
Op::PushNamespace { namespace } => self.op_push_namespace(*namespace),
Op::PushNull => self.op_push_null(),
Op::PushShort { value } => self.op_push_short(*value),
Op::PushString { string } => self.op_push_string(*string),
Op::PushTrue => self.op_push_true(),
Op::PushUint { value } => self.op_push_uint(*value),
Op::PushUndefined => self.op_push_undefined(),
Op::Pop => self.op_pop(),
Op::Dup => self.op_dup(),
Op::GetLocal { index } => self.op_get_local(*index),
Op::SetLocal { index } => self.op_set_local(*index),
Op::StoreLocal { index } => self.op_store_local(*index),
Op::Kill { index } => self.op_kill(*index),
Op::Call { num_args } => self.op_call(*num_args),
Op::CallMethod {
index,
num_args,
push_return_value,
} => self.op_call_method(*index, *num_args, *push_return_value),
Op::CallNative {
method,
num_args,
push_return_value,
} => self.op_call_native(*method, *num_args, *push_return_value),
Op::CallProperty {
multiname,
num_args,
} => self.op_call_property(*multiname, *num_args),
Op::CallPropLex {
multiname,
num_args,
} => self.op_call_prop_lex(*multiname, *num_args),
Op::CallPropVoid {
multiname,
num_args,
} => self.op_call_prop_void(*multiname, *num_args),
Op::CallStatic { method, num_args } => self.op_call_static(*method, *num_args),
Op::CallSuper {
multiname,
num_args,
} => self.op_call_super(*multiname, *num_args),
Op::GetPropertyStatic { multiname } => self.op_get_property_static(*multiname),
Op::GetPropertyFast { multiname } => self.op_get_property_fast(*multiname),
Op::GetPropertySlow { multiname } => self.op_get_property_slow(*multiname),
Op::SetPropertyStatic { multiname } => self.op_set_property_static(*multiname),
Op::SetPropertyFast { multiname } => self.op_set_property_fast(*multiname),
Op::SetPropertySlow { multiname } => self.op_set_property_slow(*multiname),
Op::InitProperty { multiname } => self.op_init_property(*multiname),
Op::DeleteProperty { multiname } => self.op_delete_property(*multiname),
Op::GetSuper { multiname } => self.op_get_super(*multiname),
Op::SetSuper { multiname } => self.op_set_super(*multiname),
Op::In => self.op_in(),
Op::PushScope => self.op_push_scope(),
Op::NewCatch { index } => self.op_newcatch(method, *index),
Op::PushWith => self.op_push_with(),
Op::PopScope => self.op_pop_scope(),
Op::GetOuterScope { index } => self.op_get_outer_scope(*index),
Op::GetScopeObject { index } => self.op_get_scope_object(*index),
Op::FindDef { multiname } => self.op_find_def(*multiname),
Op::FindProperty { multiname } => self.op_find_property(*multiname),
Op::FindPropStrict { multiname } => self.op_find_prop_strict(*multiname),
Op::GetScriptGlobals { script } => self.op_get_script_globals(*script),
Op::GetDescendants { multiname } => self.op_get_descendants(*multiname),
Op::GetSlot { index } => self.op_get_slot(*index),
Op::SetSlot { index } => self.op_set_slot(*index),
Op::SetSlotCoerceI { index } => self.op_set_slot_coerce_i(*index),
Op::SetSlotNoCoerce { index } => self.op_set_slot_no_coerce(*index),
Op::SetGlobalSlot { index } => self.op_set_global_slot(*index),
Op::Construct { num_args } => self.op_construct(*num_args),
Op::ConstructProp {
multiname,
num_args,
} => self.op_construct_prop(*multiname, *num_args),
Op::ConstructSlot { index, num_args } => self.op_construct_slot(*index, *num_args),
Op::ConstructSuper { num_args } => self.op_construct_super(*num_args),
Op::NewActivation { activation_class } => self.op_new_activation(*activation_class),
Op::NewObject { num_args } => self.op_new_object(*num_args),
Op::NewFunction { method } => self.op_new_function(*method),
Op::NewClass { class } => self.op_new_class(*class),
Op::ApplyType { num_types } => self.op_apply_type(*num_types),
Op::NewArray { num_args } => self.op_new_array(*num_args),
Op::CoerceA => Ok(()),
Op::CoerceB => self.op_coerce_b(),
Op::CoerceD => self.op_coerce_d(),
Op::CoerceDSwapPop => self.op_coerce_d_swap_pop(),
Op::CoerceI => self.op_coerce_i(),
Op::CoerceISwapPop => self.op_coerce_i_swap_pop(),
Op::CoerceO => self.op_coerce_o(),
Op::CoerceS => self.op_coerce_s(),
Op::CoerceU => self.op_coerce_u(),
Op::CoerceUSwapPop => self.op_coerce_u_swap_pop(),
Op::ConvertO => self.op_convert_o(),
Op::ConvertS => self.op_convert_s(),
Op::Add => self.op_add(),
Op::AddI => self.op_add_i(),
Op::BitAnd => self.op_bitand(),
Op::BitNot => self.op_bitnot(),
Op::BitOr => self.op_bitor(),
Op::BitXor => self.op_bitxor(),
Op::DecLocal { index } => self.op_declocal(*index),
Op::DecLocalI { index } => self.op_declocal_i(*index),
Op::Decrement => self.op_decrement(),
Op::DecrementI => self.op_decrement_i(),
Op::Divide => self.op_divide(),
Op::IncLocal { index } => self.op_inclocal(*index),
Op::IncLocalI { index } => self.op_inclocal_i(*index),
Op::Increment => self.op_increment(),
Op::IncrementI => self.op_increment_i(),
Op::LShift => self.op_lshift(),
Op::Modulo => self.op_modulo(),
Op::Multiply => self.op_multiply(),
Op::MultiplyI => self.op_multiply_i(),
Op::Negate => self.op_negate(),
Op::NegateI => self.op_negate_i(),
Op::RShift => self.op_rshift(),
Op::Subtract => self.op_subtract(),
Op::SubtractI => self.op_subtract_i(),
Op::Swap => self.op_swap(),
Op::URShift => self.op_urshift(),
Op::StrictEquals => self.op_strict_equals(),
Op::Equals => self.op_equals(),
Op::GreaterEquals => self.op_greater_equals(),
Op::GreaterThan => self.op_greater_than(),
Op::LessEquals => self.op_less_equals(),
Op::LessThan => self.op_less_than(),
Op::Nop => Ok(()),
Op::Not => self.op_not(),
Op::HasNext => self.op_has_next(),
Op::HasNext2 {
object_register,
index_register,
} => self.op_has_next_2(*object_register, *index_register),
Op::NextName => self.op_next_name(),
Op::NextValue => self.op_next_value(),
Op::IsType { class } => self.op_is_type(*class),
Op::IsTypeLate => self.op_is_type_late(),
Op::AsType { class } => self.op_as_type(*class),
Op::AsTypeLate => self.op_as_type_late(),
Op::InstanceOf => self.op_instance_of(),
Op::Debug {
is_local_register,
register_name,
register,
} => self.op_debug(*is_local_register, *register_name, *register),
Op::DebugFile { file_name } => self.op_debug_file(*file_name),
Op::DebugLine { line_num } => self.op_debug_line(*line_num),
Op::Bkpt => self.op_bkpt(),
Op::BkptLine { line_num } => self.op_bkpt_line(*line_num),
Op::Timestamp => self.op_timestamp(),
Op::TypeOf => self.op_type_of(),
Op::Dxns { string } => self.op_dxns(*string),
Op::DxnsLate => self.op_dxns_late(),
Op::EscXAttr => self.op_esc_xattr(),
Op::EscXElem => self.op_esc_elem(),
Op::Coerce { class } => self.op_coerce(*class),
Op::CoerceSwapPop { class } => self.op_coerce_swap_pop(*class),
Op::CheckFilter => self.op_check_filter(),
Op::Si8 => self.op_si8(),
Op::Si16 => self.op_si16(),
Op::Si32 => self.op_si32(),
Op::Sf32 => self.op_sf32(),
Op::Sf64 => self.op_sf64(),
Op::Li8 => self.op_li8(),
Op::Li16 => self.op_li16(),
Op::Li32 => self.op_li32(),
Op::Lf32 => self.op_lf32(),
Op::Lf64 => self.op_lf64(),
Op::Sxi1 => self.op_sxi1(),
Op::Sxi8 => self.op_sxi8(),
Op::Sxi16 => self.op_sxi16(),
Op::Throw => self.op_throw(),
// Branch ops
Op::Jump { offset } => {
self.timeout_check()?;
ip = *offset;
continue;
}
Op::IfTrue { offset } => {
self.timeout_check()?;
if self.check_if_true() {
ip = *offset;
}
continue;
}
Op::IfFalse { offset } => {
self.timeout_check()?;
if !self.check_if_true() {
ip = *offset;
}
continue;
}
Op::PopJump { offset } => {
self.timeout_check()?;
let _ = self.pop_stack();
ip = *offset;
continue;
}
Op::LookupSwitch(lookup_switch) => {
self.timeout_check()?;
ip = self.lookup_switch(lookup_switch);
continue;
}
// Return ops
Op::ReturnValue { return_type } => {
let coerce_result = self.return_value(*return_type);
match coerce_result {
Ok(value) => return Ok(value),
Err(error) => Err(error),
}
}
Op::ReturnVoid { return_type } => {
return Ok(self.return_void(*return_type));
}
};
if let Err(error) = result {
ip = self.handle_err(method, ip, error)?;
}
}
}
/// If a local exception handler exists for the error, use it to handle
/// the error. Otherwise pass the error down the stack.
fn handle_err(
&mut self,
method: Method<'gc>,
ip: usize,
original_error: Error<'gc>,
) -> Result<usize, Error<'gc>> {
let error = if let Some(error) = original_error.as_avm_error() {
error
} else {
return Err(original_error);
};
let verified_info = method.get_verified_info();
let exception_list = &verified_info.exceptions;
let last_ip = ip - 1;
for e in exception_list {
if last_ip >= e.from_offset && last_ip < e.to_offset {
let matches = if let Some(target_class) = e.target_class {
// This ensures null and undefined don't match
error.is_of_type(target_class)
} else {
// A typeless catch block (i.e. `catch(err:*) { ... }`) will
// always match.
true
};
if matches {
#[cfg(feature = "avm_debug")]
tracing::info!(target: "avm_caught", "Caught exception: {:?}", original_error);
self.reset_stack();
self.push_stack(error);
self.clear_scope();
return Ok(e.target_offset);
}
}
}
Err(original_error)
}
#[inline(always)]
fn timeout_check(&mut self) -> Result<(), Error<'gc>> {
*self.context.actions_since_timeout_check += 1;
if *self.context.actions_since_timeout_check >= 10000 {
*self.context.actions_since_timeout_check = 0;
if self.context.update_start.elapsed() >= self.context.max_execution_duration {
return Err(
"A script in this movie has taken too long to execute and has been terminated."
.into(),
);
}
}
Ok(())
}
fn op_push_double(&mut self, value: f64) -> Result<(), Error<'gc>> {
self.push_stack(value);
Ok(())
}
fn op_push_false(&mut self) -> Result<(), Error<'gc>> {
self.push_stack(false);
Ok(())
}
fn op_push_int(&mut self, value: i32) -> Result<(), Error<'gc>> {
self.push_stack(value);
Ok(())
}
fn op_push_namespace(&mut self, namespace: Namespace<'gc>) -> Result<(), Error<'gc>> {
let ns_object = NamespaceObject::from_namespace(self, namespace);
self.push_stack(ns_object);
Ok(())
}
fn op_push_null(&mut self) -> Result<(), Error<'gc>> {
self.push_stack(Value::Null);
Ok(())
}
fn op_push_short(&mut self, value: i16) -> Result<(), Error<'gc>> {
self.push_stack(value);
Ok(())
}
fn op_push_string(&mut self, string: AvmAtom<'gc>) -> Result<(), Error<'gc>> {
self.push_stack(string);
Ok(())
}
fn op_push_true(&mut self) -> Result<(), Error<'gc>> {
self.push_stack(true);
Ok(())
}
fn op_push_uint(&mut self, value: u32) -> Result<(), Error<'gc>> {
self.push_stack(value);