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