[swfinterp] Add more builtins and improve static variables
[youtube-dl] / youtube_dl / swfinterp.py
1 from __future__ import unicode_literals
2
3 import collections
4 import io
5 import zlib
6
7 from .utils import (
8     compat_str,
9     ExtractorError,
10     struct_unpack,
11 )
12
13
14 def _extract_tags(file_contents):
15     if file_contents[1:3] != b'WS':
16         raise ExtractorError(
17             'Not an SWF file; header is %r' % file_contents[:3])
18     if file_contents[:1] == b'C':
19         content = zlib.decompress(file_contents[8:])
20     else:
21         raise NotImplementedError(
22             'Unsupported compression format %r' %
23             file_contents[:1])
24
25     # Determine number of bits in framesize rectangle
26     framesize_nbits = struct_unpack('!B', content[:1])[0] >> 3
27     framesize_len = (5 + 4 * framesize_nbits + 7) // 8
28
29     pos = framesize_len + 2 + 2
30     while pos < len(content):
31         header16 = struct_unpack('<H', content[pos:pos + 2])[0]
32         pos += 2
33         tag_code = header16 >> 6
34         tag_len = header16 & 0x3f
35         if tag_len == 0x3f:
36             tag_len = struct_unpack('<I', content[pos:pos + 4])[0]
37             pos += 4
38         assert pos + tag_len <= len(content), \
39             ('Tag %d ends at %d+%d - that\'s longer than the file (%d)'
40                 % (tag_code, pos, tag_len, len(content)))
41         yield (tag_code, content[pos:pos + tag_len])
42         pos += tag_len
43
44
45 class _AVMClass_Object(object):
46     def __init__(self, avm_class):
47         self.avm_class = avm_class
48
49     def __repr__(self):
50         return '%s#%x' % (self.avm_class.name, id(self))
51
52
53 class _ScopeDict(dict):
54     def __init__(self, avm_class):
55         super(_ScopeDict, self).__init__()
56         self.avm_class = avm_class
57
58     def __repr__(self):
59         return '%s__Scope(%s)' % (
60             self.avm_class.name,
61             super(_ScopeDict, self).__repr__())
62
63
64 class _AVMClass(object):
65     def __init__(self, name_idx, name, static_properties=None):
66         self.name_idx = name_idx
67         self.name = name
68         self.method_names = {}
69         self.method_idxs = {}
70         self.methods = {}
71         self.method_pyfunctions = {}
72         self.static_properties = static_properties if static_properties else {}
73
74         self.variables = _ScopeDict(self)
75         self.constants = {}
76
77     def make_object(self):
78         return _AVMClass_Object(self)
79
80     def __repr__(self):
81         return '_AVMClass(%s)' % (self.name)
82
83     def register_methods(self, methods):
84         self.method_names.update(methods.items())
85         self.method_idxs.update(dict(
86             (idx, name)
87             for name, idx in methods.items()))
88
89
90 class _Multiname(object):
91     def __init__(self, kind):
92         self.kind = kind
93
94     def __repr__(self):
95         return '[MULTINAME kind: 0x%x]' % self.kind
96
97
98 def _read_int(reader):
99     res = 0
100     shift = 0
101     for _ in range(5):
102         buf = reader.read(1)
103         assert len(buf) == 1
104         b = struct_unpack('<B', buf)[0]
105         res = res | ((b & 0x7f) << shift)
106         if b & 0x80 == 0:
107             break
108         shift += 7
109     return res
110
111
112 def _u30(reader):
113     res = _read_int(reader)
114     assert res & 0xf0000000 == 0
115     return res
116 _u32 = _read_int
117
118
119 def _s32(reader):
120     v = _read_int(reader)
121     if v & 0x80000000 != 0:
122         v = - ((v ^ 0xffffffff) + 1)
123     return v
124
125
126 def _s24(reader):
127     bs = reader.read(3)
128     assert len(bs) == 3
129     last_byte = b'\xff' if (ord(bs[2:3]) >= 0x80) else b'\x00'
130     return struct_unpack('<i', bs + last_byte)[0]
131
132
133 def _read_string(reader):
134     slen = _u30(reader)
135     resb = reader.read(slen)
136     assert len(resb) == slen
137     return resb.decode('utf-8')
138
139
140 def _read_bytes(count, reader):
141     assert count >= 0
142     resb = reader.read(count)
143     assert len(resb) == count
144     return resb
145
146
147 def _read_byte(reader):
148     resb = _read_bytes(1, reader=reader)
149     res = struct_unpack('<B', resb)[0]
150     return res
151
152
153 StringClass = _AVMClass('(no name idx)', 'String')
154 ByteArrayClass = _AVMClass('(no name idx)', 'ByteArray')
155 TimerClass = _AVMClass('(no name idx)', 'Timer')
156 TimerEventClass = _AVMClass('(no name idx)', 'TimerEvent', {'TIMER': 'timer'})
157 _builtin_classes = {
158     StringClass.name: StringClass,
159     ByteArrayClass.name: ByteArrayClass,
160     TimerClass.name: TimerClass,
161     TimerEventClass.name: TimerEventClass,
162 }
163
164
165 class _Undefined(object):
166     def __bool__(self):
167         return False
168     __nonzero__ = __bool__
169
170     def __hash__(self):
171         return 0
172
173 undefined = _Undefined()
174
175
176 class SWFInterpreter(object):
177     def __init__(self, file_contents):
178         self._patched_functions = {
179             (TimerClass, 'addEventListener'): lambda params: undefined,
180         }
181         code_tag = next(tag
182                         for tag_code, tag in _extract_tags(file_contents)
183                         if tag_code == 82)
184         p = code_tag.index(b'\0', 4) + 1
185         code_reader = io.BytesIO(code_tag[p:])
186
187         # Parse ABC (AVM2 ByteCode)
188
189         # Define a couple convenience methods
190         u30 = lambda *args: _u30(*args, reader=code_reader)
191         s32 = lambda *args: _s32(*args, reader=code_reader)
192         u32 = lambda *args: _u32(*args, reader=code_reader)
193         read_bytes = lambda *args: _read_bytes(*args, reader=code_reader)
194         read_byte = lambda *args: _read_byte(*args, reader=code_reader)
195
196         # minor_version + major_version
197         read_bytes(2 + 2)
198
199         # Constant pool
200         int_count = u30()
201         self.constant_ints = [0]
202         for _c in range(1, int_count):
203             self.constant_ints.append(s32())
204         self.constant_uints = [0]
205         uint_count = u30()
206         for _c in range(1, uint_count):
207             self.constant_uints.append(u32())
208         double_count = u30()
209         read_bytes(max(0, (double_count - 1)) * 8)
210         string_count = u30()
211         self.constant_strings = ['']
212         for _c in range(1, string_count):
213             s = _read_string(code_reader)
214             self.constant_strings.append(s)
215         namespace_count = u30()
216         for _c in range(1, namespace_count):
217             read_bytes(1)  # kind
218             u30()  # name
219         ns_set_count = u30()
220         for _c in range(1, ns_set_count):
221             count = u30()
222             for _c2 in range(count):
223                 u30()
224         multiname_count = u30()
225         MULTINAME_SIZES = {
226             0x07: 2,  # QName
227             0x0d: 2,  # QNameA
228             0x0f: 1,  # RTQName
229             0x10: 1,  # RTQNameA
230             0x11: 0,  # RTQNameL
231             0x12: 0,  # RTQNameLA
232             0x09: 2,  # Multiname
233             0x0e: 2,  # MultinameA
234             0x1b: 1,  # MultinameL
235             0x1c: 1,  # MultinameLA
236         }
237         self.multinames = ['']
238         for _c in range(1, multiname_count):
239             kind = u30()
240             assert kind in MULTINAME_SIZES, 'Invalid multiname kind %r' % kind
241             if kind == 0x07:
242                 u30()  # namespace_idx
243                 name_idx = u30()
244                 self.multinames.append(self.constant_strings[name_idx])
245             elif kind == 0x09:
246                 name_idx = u30()
247                 u30()
248                 self.multinames.append(self.constant_strings[name_idx])
249             else:
250                 self.multinames.append(_Multiname(kind))
251                 for _c2 in range(MULTINAME_SIZES[kind]):
252                     u30()
253
254         # Methods
255         method_count = u30()
256         MethodInfo = collections.namedtuple(
257             'MethodInfo',
258             ['NEED_ARGUMENTS', 'NEED_REST'])
259         method_infos = []
260         for method_id in range(method_count):
261             param_count = u30()
262             u30()  # return type
263             for _ in range(param_count):
264                 u30()  # param type
265             u30()  # name index (always 0 for youtube)
266             flags = read_byte()
267             if flags & 0x08 != 0:
268                 # Options present
269                 option_count = u30()
270                 for c in range(option_count):
271                     u30()  # val
272                     read_bytes(1)  # kind
273             if flags & 0x80 != 0:
274                 # Param names present
275                 for _ in range(param_count):
276                     u30()  # param name
277             mi = MethodInfo(flags & 0x01 != 0, flags & 0x04 != 0)
278             method_infos.append(mi)
279
280         # Metadata
281         metadata_count = u30()
282         for _c in range(metadata_count):
283             u30()  # name
284             item_count = u30()
285             for _c2 in range(item_count):
286                 u30()  # key
287                 u30()  # value
288
289         def parse_traits_info():
290             trait_name_idx = u30()
291             kind_full = read_byte()
292             kind = kind_full & 0x0f
293             attrs = kind_full >> 4
294             methods = {}
295             constants = None
296             if kind == 0x00:  # Slot
297                 u30()  # Slot id
298                 u30()  # type_name_idx
299                 vindex = u30()
300                 if vindex != 0:
301                     read_byte()  # vkind
302             elif kind == 0x06:  # Const
303                 u30()  # Slot id
304                 u30()  # type_name_idx
305                 vindex = u30()
306                 vkind = 'any'
307                 if vindex != 0:
308                     vkind = read_byte()
309                 if vkind == 0x03:  # Constant_Int
310                     value = self.constant_ints[vindex]
311                 elif vkind == 0x04:  # Constant_UInt
312                     value = self.constant_uints[vindex]
313                 else:
314                     return {}, None  # Ignore silently for now
315                 constants = {self.multinames[trait_name_idx]: value}
316             elif kind in (0x01, 0x02, 0x03):  # Method / Getter / Setter
317                 u30()  # disp_id
318                 method_idx = u30()
319                 methods[self.multinames[trait_name_idx]] = method_idx
320             elif kind == 0x04:  # Class
321                 u30()  # slot_id
322                 u30()  # classi
323             elif kind == 0x05:  # Function
324                 u30()  # slot_id
325                 function_idx = u30()
326                 methods[function_idx] = self.multinames[trait_name_idx]
327             else:
328                 raise ExtractorError('Unsupported trait kind %d' % kind)
329
330             if attrs & 0x4 != 0:  # Metadata present
331                 metadata_count = u30()
332                 for _c3 in range(metadata_count):
333                     u30()  # metadata index
334
335             return methods, constants
336
337         # Classes
338         class_count = u30()
339         classes = []
340         for class_id in range(class_count):
341             name_idx = u30()
342
343             cname = self.multinames[name_idx]
344             avm_class = _AVMClass(name_idx, cname)
345             classes.append(avm_class)
346
347             u30()  # super_name idx
348             flags = read_byte()
349             if flags & 0x08 != 0:  # Protected namespace is present
350                 u30()  # protected_ns_idx
351             intrf_count = u30()
352             for _c2 in range(intrf_count):
353                 u30()
354             u30()  # iinit
355             trait_count = u30()
356             for _c2 in range(trait_count):
357                 trait_methods, trait_constants = parse_traits_info()
358                 avm_class.register_methods(trait_methods)
359                 if trait_constants:
360                     avm_class.constants.update(trait_constants)
361
362         assert len(classes) == class_count
363         self._classes_by_name = dict((c.name, c) for c in classes)
364
365         for avm_class in classes:
366             avm_class.cinit_idx = u30()
367             trait_count = u30()
368             for _c2 in range(trait_count):
369                 trait_methods, trait_constants = parse_traits_info()
370                 avm_class.register_methods(trait_methods)
371                 if trait_constants:
372                     avm_class.constants.update(trait_constants)
373
374         # Scripts
375         script_count = u30()
376         for _c in range(script_count):
377             u30()  # init
378             trait_count = u30()
379             for _c2 in range(trait_count):
380                 parse_traits_info()
381
382         # Method bodies
383         method_body_count = u30()
384         Method = collections.namedtuple('Method', ['code', 'local_count'])
385         self._all_methods = []
386         for _c in range(method_body_count):
387             method_idx = u30()
388             u30()  # max_stack
389             local_count = u30()
390             u30()  # init_scope_depth
391             u30()  # max_scope_depth
392             code_length = u30()
393             code = read_bytes(code_length)
394             m = Method(code, local_count)
395             self._all_methods.append(m)
396             for avm_class in classes:
397                 if method_idx in avm_class.method_idxs:
398                     avm_class.methods[avm_class.method_idxs[method_idx]] = m
399             exception_count = u30()
400             for _c2 in range(exception_count):
401                 u30()  # from
402                 u30()  # to
403                 u30()  # target
404                 u30()  # exc_type
405                 u30()  # var_name
406             trait_count = u30()
407             for _c2 in range(trait_count):
408                 parse_traits_info()
409
410         assert p + code_reader.tell() == len(code_tag)
411
412     def patch_function(self, avm_class, func_name, f):
413         self._patched_functions[(avm_class, func_name)] = f
414
415     def extract_class(self, class_name, call_cinit=True):
416         try:
417             res = self._classes_by_name[class_name]
418         except KeyError:
419             raise ExtractorError('Class %r not found' % class_name)
420
421         if call_cinit and hasattr(res, 'cinit_idx'):
422             res.register_methods({'$cinit': res.cinit_idx})
423             res.methods['$cinit'] = self._all_methods[res.cinit_idx]
424             cinit = self.extract_function(res, '$cinit')
425             cinit([])
426
427         return res
428
429     def extract_function(self, avm_class, func_name):
430         p = self._patched_functions.get((avm_class, func_name))
431         if p:
432             return p
433         if func_name in avm_class.method_pyfunctions:
434             return avm_class.method_pyfunctions[func_name]
435         if func_name in self._classes_by_name:
436             return self._classes_by_name[func_name].make_object()
437         if func_name not in avm_class.methods:
438             raise ExtractorError('Cannot find function %s.%s' % (
439                 avm_class.name, func_name))
440         m = avm_class.methods[func_name]
441
442         def resfunc(args):
443             # Helper functions
444             coder = io.BytesIO(m.code)
445             s24 = lambda: _s24(coder)
446             u30 = lambda: _u30(coder)
447
448             registers = [avm_class.variables] + list(args) + [None] * m.local_count
449             stack = []
450             scopes = collections.deque([
451                 self._classes_by_name, avm_class.constants, avm_class.variables])
452             while True:
453                 opcode = _read_byte(coder)
454                 if opcode == 9:  # label
455                     pass  # Spec says: "Do nothing."
456                 elif opcode == 16:  # jump
457                     offset = s24()
458                     coder.seek(coder.tell() + offset)
459                 elif opcode == 17:  # iftrue
460                     offset = s24()
461                     value = stack.pop()
462                     if value:
463                         coder.seek(coder.tell() + offset)
464                 elif opcode == 18:  # iffalse
465                     offset = s24()
466                     value = stack.pop()
467                     if not value:
468                         coder.seek(coder.tell() + offset)
469                 elif opcode == 19:  # ifeq
470                     offset = s24()
471                     value2 = stack.pop()
472                     value1 = stack.pop()
473                     if value2 == value1:
474                         coder.seek(coder.tell() + offset)
475                 elif opcode == 20:  # ifne
476                     offset = s24()
477                     value2 = stack.pop()
478                     value1 = stack.pop()
479                     if value2 != value1:
480                         coder.seek(coder.tell() + offset)
481                 elif opcode == 21:  # iflt
482                     offset = s24()
483                     value2 = stack.pop()
484                     value1 = stack.pop()
485                     if value1 < value2:
486                         coder.seek(coder.tell() + offset)
487                 elif opcode == 32:  # pushnull
488                     stack.append(None)
489                 elif opcode == 33:  # pushundefined
490                     stack.append(undefined)
491                 elif opcode == 36:  # pushbyte
492                     v = _read_byte(coder)
493                     stack.append(v)
494                 elif opcode == 37:  # pushshort
495                     v = u30()
496                     stack.append(v)
497                 elif opcode == 38:  # pushtrue
498                     stack.append(True)
499                 elif opcode == 39:  # pushfalse
500                     stack.append(False)
501                 elif opcode == 40:  # pushnan
502                     stack.append(float('NaN'))
503                 elif opcode == 42:  # dup
504                     value = stack[-1]
505                     stack.append(value)
506                 elif opcode == 44:  # pushstring
507                     idx = u30()
508                     stack.append(self.constant_strings[idx])
509                 elif opcode == 48:  # pushscope
510                     new_scope = stack.pop()
511                     scopes.append(new_scope)
512                 elif opcode == 66:  # construct
513                     arg_count = u30()
514                     args = list(reversed(
515                         [stack.pop() for _ in range(arg_count)]))
516                     obj = stack.pop()
517                     res = obj.avm_class.make_object()
518                     stack.append(res)
519                 elif opcode == 70:  # callproperty
520                     index = u30()
521                     mname = self.multinames[index]
522                     arg_count = u30()
523                     args = list(reversed(
524                         [stack.pop() for _ in range(arg_count)]))
525                     obj = stack.pop()
526
527                     if obj == StringClass:
528                         if mname == 'String':
529                             assert len(args) == 1
530                             assert isinstance(args[0], (
531                                 int, compat_str, _Undefined))
532                             if args[0] == undefined:
533                                 res = 'undefined'
534                             else:
535                                 res = compat_str(args[0])
536                             stack.append(res)
537                             continue
538                         else:
539                             raise NotImplementedError(
540                                 'Function String.%s is not yet implemented'
541                                 % mname)
542                     elif isinstance(obj, _AVMClass_Object):
543                         func = self.extract_function(obj.avm_class, mname)
544                         res = func(args)
545                         stack.append(res)
546                         continue
547                     elif isinstance(obj, _AVMClass):
548                         func = self.extract_function(obj, mname)
549                         res = func(args)
550                         stack.append(res)
551                         continue
552                     elif isinstance(obj, _ScopeDict):
553                         if mname in obj.avm_class.method_names:
554                             func = self.extract_function(obj.avm_class, mname)
555                             res = func(args)
556                         else:
557                             res = obj[mname]
558                         stack.append(res)
559                         continue
560                     elif isinstance(obj, compat_str):
561                         if mname == 'split':
562                             assert len(args) == 1
563                             assert isinstance(args[0], compat_str)
564                             if args[0] == '':
565                                 res = list(obj)
566                             else:
567                                 res = obj.split(args[0])
568                             stack.append(res)
569                             continue
570                         elif mname == 'charCodeAt':
571                             assert len(args) <= 1
572                             idx = 0 if len(args) == 0 else args[0]
573                             assert isinstance(idx, int)
574                             res = ord(obj[idx])
575                             stack.append(res)
576                             continue
577                     elif isinstance(obj, list):
578                         if mname == 'slice':
579                             assert len(args) == 1
580                             assert isinstance(args[0], int)
581                             res = obj[args[0]:]
582                             stack.append(res)
583                             continue
584                         elif mname == 'join':
585                             assert len(args) == 1
586                             assert isinstance(args[0], compat_str)
587                             res = args[0].join(obj)
588                             stack.append(res)
589                             continue
590                     raise NotImplementedError(
591                         'Unsupported property %r on %r'
592                         % (mname, obj))
593                 elif opcode == 71:  # returnvoid
594                     res = undefined
595                     return res
596                 elif opcode == 72:  # returnvalue
597                     res = stack.pop()
598                     return res
599                 elif opcode == 73:  # constructsuper
600                     # Not yet implemented, just hope it works without it
601                     arg_count = u30()
602                     args = list(reversed(
603                         [stack.pop() for _ in range(arg_count)]))
604                     obj = stack.pop()
605                 elif opcode == 74:  # constructproperty
606                     index = u30()
607                     arg_count = u30()
608                     args = list(reversed(
609                         [stack.pop() for _ in range(arg_count)]))
610                     obj = stack.pop()
611
612                     mname = self.multinames[index]
613                     assert isinstance(obj, _AVMClass)
614
615                     # We do not actually call the constructor for now;
616                     # we just pretend it does nothing
617                     stack.append(obj.make_object())
618                 elif opcode == 79:  # callpropvoid
619                     index = u30()
620                     mname = self.multinames[index]
621                     arg_count = u30()
622                     args = list(reversed(
623                         [stack.pop() for _ in range(arg_count)]))
624                     obj = stack.pop()
625                     if isinstance(obj, _AVMClass_Object):
626                         func = self.extract_function(obj.avm_class, mname)
627                         res = func(args)
628                         assert res is undefined
629                         continue
630                     if isinstance(obj, _ScopeDict):
631                         assert mname in obj.avm_class.method_names
632                         func = self.extract_function(obj.avm_class, mname)
633                         res = func(args)
634                         assert res is undefined
635                         continue
636                     if mname == 'reverse':
637                         assert isinstance(obj, list)
638                         obj.reverse()
639                     else:
640                         raise NotImplementedError(
641                             'Unsupported (void) property %r on %r'
642                             % (mname, obj))
643                 elif opcode == 86:  # newarray
644                     arg_count = u30()
645                     arr = []
646                     for i in range(arg_count):
647                         arr.append(stack.pop())
648                     arr = arr[::-1]
649                     stack.append(arr)
650                 elif opcode == 93:  # findpropstrict
651                     index = u30()
652                     mname = self.multinames[index]
653                     for s in reversed(scopes):
654                         if mname in s:
655                             res = s
656                             break
657                     else:
658                         res = scopes[0]
659                     if mname not in res and mname in _builtin_classes:
660                         stack.append(_builtin_classes[mname])
661                     else:
662                         stack.append(res[mname])
663                 elif opcode == 94:  # findproperty
664                     index = u30()
665                     mname = self.multinames[index]
666                     for s in reversed(scopes):
667                         if mname in s:
668                             res = s
669                             break
670                     else:
671                         res = avm_class.variables
672                     stack.append(res)
673                 elif opcode == 96:  # getlex
674                     index = u30()
675                     mname = self.multinames[index]
676                     for s in reversed(scopes):
677                         if mname in s:
678                             scope = s
679                             break
680                     else:
681                         scope = avm_class.variables
682
683                     if mname in scope:
684                         res = scope[mname]
685                     elif mname in _builtin_classes:
686                         res = _builtin_classes[mname]
687                     else:
688                         # Assume unitialized
689                         res = undefined
690                     stack.append(res)
691                 elif opcode == 97:  # setproperty
692                     index = u30()
693                     value = stack.pop()
694                     idx = self.multinames[index]
695                     if isinstance(idx, _Multiname):
696                         idx = stack.pop()
697                     obj = stack.pop()
698                     obj[idx] = value
699                 elif opcode == 98:  # getlocal
700                     index = u30()
701                     stack.append(registers[index])
702                 elif opcode == 99:  # setlocal
703                     index = u30()
704                     value = stack.pop()
705                     registers[index] = value
706                 elif opcode == 102:  # getproperty
707                     index = u30()
708                     pname = self.multinames[index]
709                     if pname == 'length':
710                         obj = stack.pop()
711                         assert isinstance(obj, (compat_str, list))
712                         stack.append(len(obj))
713                     elif isinstance(pname, compat_str):  # Member access
714                         obj = stack.pop()
715                         if isinstance(obj, _AVMClass):
716                             res = obj.static_properties[pname]
717                             stack.append(res)
718                             continue
719
720                         assert isinstance(obj, (dict, _ScopeDict)),\
721                             'Accessing member %r on %r' % (pname, obj)
722                         res = obj.get(pname, undefined)
723                         stack.append(res)
724                     else:  # Assume attribute access
725                         idx = stack.pop()
726                         assert isinstance(idx, int)
727                         obj = stack.pop()
728                         assert isinstance(obj, list)
729                         stack.append(obj[idx])
730                 elif opcode == 104:  # initproperty
731                     index = u30()
732                     value = stack.pop()
733                     idx = self.multinames[index]
734                     if isinstance(idx, _Multiname):
735                         idx = stack.pop()
736                     obj = stack.pop()
737                     obj[idx] = value
738                 elif opcode == 115:  # convert_
739                     value = stack.pop()
740                     intvalue = int(value)
741                     stack.append(intvalue)
742                 elif opcode == 128:  # coerce
743                     u30()
744                 elif opcode == 130:  # coerce_a
745                     value = stack.pop()
746                     # um, yes, it's any value
747                     stack.append(value)
748                 elif opcode == 133:  # coerce_s
749                     assert isinstance(stack[-1], (type(None), compat_str))
750                 elif opcode == 147:  # decrement
751                     value = stack.pop()
752                     assert isinstance(value, int)
753                     stack.append(value - 1)
754                 elif opcode == 149:  # typeof
755                     value = stack.pop()
756                     return {
757                         _Undefined: 'undefined',
758                         compat_str: 'String',
759                         int: 'Number',
760                         float: 'Number',
761                     }[type(value)]
762                 elif opcode == 160:  # add
763                     value2 = stack.pop()
764                     value1 = stack.pop()
765                     res = value1 + value2
766                     stack.append(res)
767                 elif opcode == 161:  # subtract
768                     value2 = stack.pop()
769                     value1 = stack.pop()
770                     res = value1 - value2
771                     stack.append(res)
772                 elif opcode == 162:  # multiply
773                     value2 = stack.pop()
774                     value1 = stack.pop()
775                     res = value1 * value2
776                     stack.append(res)
777                 elif opcode == 164:  # modulo
778                     value2 = stack.pop()
779                     value1 = stack.pop()
780                     res = value1 % value2
781                     stack.append(res)
782                 elif opcode == 168:  # bitand
783                     value2 = stack.pop()
784                     value1 = stack.pop()
785                     assert isinstance(value1, int)
786                     assert isinstance(value2, int)
787                     res = value1 & value2
788                     stack.append(res)
789                 elif opcode == 171:  # equals
790                     value2 = stack.pop()
791                     value1 = stack.pop()
792                     result = value1 == value2
793                     stack.append(result)
794                 elif opcode == 175:  # greaterequals
795                     value2 = stack.pop()
796                     value1 = stack.pop()
797                     result = value1 >= value2
798                     stack.append(result)
799                 elif opcode == 192:  # increment_i
800                     value = stack.pop()
801                     assert isinstance(value, int)
802                     stack.append(value + 1)
803                 elif opcode == 208:  # getlocal_0
804                     stack.append(registers[0])
805                 elif opcode == 209:  # getlocal_1
806                     stack.append(registers[1])
807                 elif opcode == 210:  # getlocal_2
808                     stack.append(registers[2])
809                 elif opcode == 211:  # getlocal_3
810                     stack.append(registers[3])
811                 elif opcode == 212:  # setlocal_0
812                     registers[0] = stack.pop()
813                 elif opcode == 213:  # setlocal_1
814                     registers[1] = stack.pop()
815                 elif opcode == 214:  # setlocal_2
816                     registers[2] = stack.pop()
817                 elif opcode == 215:  # setlocal_3
818                     registers[3] = stack.pop()
819                 else:
820                     raise NotImplementedError(
821                         'Unsupported opcode %d' % opcode)
822
823         avm_class.method_pyfunctions[func_name] = resfunc
824         return resfunc
825