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