[swfinterp] Basic support for constants (only ints for now)
[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             u30()  # cinit
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         for _c in range(method_body_count):
377             method_idx = u30()
378             u30()  # max_stack
379             local_count = u30()
380             u30()  # init_scope_depth
381             u30()  # max_scope_depth
382             code_length = u30()
383             code = read_bytes(code_length)
384             for avm_class in classes:
385                 if method_idx in avm_class.method_idxs:
386                     m = Method(code, local_count)
387                     avm_class.methods[avm_class.method_idxs[method_idx]] = m
388             exception_count = u30()
389             for _c2 in range(exception_count):
390                 u30()  # from
391                 u30()  # to
392                 u30()  # target
393                 u30()  # exc_type
394                 u30()  # var_name
395             trait_count = u30()
396             for _c2 in range(trait_count):
397                 parse_traits_info()
398
399         assert p + code_reader.tell() == len(code_tag)
400
401     def patch_function(self, avm_class, func_name, f):
402         self._patched_functions[(avm_class, func_name)] = f
403
404     def extract_class(self, class_name):
405         try:
406             return self._classes_by_name[class_name]
407         except KeyError:
408             raise ExtractorError('Class %r not found' % class_name)
409
410     def extract_function(self, avm_class, func_name):
411         p = self._patched_functions.get((avm_class, func_name))
412         if p:
413             return p
414         if func_name in avm_class.method_pyfunctions:
415             return avm_class.method_pyfunctions[func_name]
416         if func_name in self._classes_by_name:
417             return self._classes_by_name[func_name].make_object()
418         if func_name not in avm_class.methods:
419             raise ExtractorError('Cannot find function %s.%s' % (
420                 avm_class.name, func_name))
421         m = avm_class.methods[func_name]
422
423         def resfunc(args):
424             # Helper functions
425             coder = io.BytesIO(m.code)
426             s24 = lambda: _s24(coder)
427             u30 = lambda: _u30(coder)
428
429             registers = [avm_class.variables] + list(args) + [None] * m.local_count
430             stack = []
431             scopes = collections.deque([
432                 self._classes_by_name, avm_class.variables])
433             while True:
434                 opcode = _read_byte(coder)
435                 if opcode == 9:  # label
436                     pass  # Spec says: "Do nothing."
437                 elif opcode == 16:  # jump
438                     offset = s24()
439                     coder.seek(coder.tell() + offset)
440                 elif opcode == 17:  # iftrue
441                     offset = s24()
442                     value = stack.pop()
443                     if value:
444                         coder.seek(coder.tell() + offset)
445                 elif opcode == 18:  # iffalse
446                     offset = s24()
447                     value = stack.pop()
448                     if not value:
449                         coder.seek(coder.tell() + offset)
450                 elif opcode == 19:  # ifeq
451                     offset = s24()
452                     value2 = stack.pop()
453                     value1 = stack.pop()
454                     if value2 == value1:
455                         coder.seek(coder.tell() + offset)
456                 elif opcode == 20:  # ifne
457                     offset = s24()
458                     value2 = stack.pop()
459                     value1 = stack.pop()
460                     if value2 != value1:
461                         coder.seek(coder.tell() + offset)
462                 elif opcode == 21:  # iflt
463                     offset = s24()
464                     value2 = stack.pop()
465                     value1 = stack.pop()
466                     if value1 < value2:
467                         coder.seek(coder.tell() + offset)
468                 elif opcode == 32:  # pushnull
469                     stack.append(None)
470                 elif opcode == 33:  # pushundefined
471                     stack.append(undefined)
472                 elif opcode == 36:  # pushbyte
473                     v = _read_byte(coder)
474                     stack.append(v)
475                 elif opcode == 37:  # pushshort
476                     v = u30()
477                     stack.append(v)
478                 elif opcode == 38:  # pushtrue
479                     stack.append(True)
480                 elif opcode == 39:  # pushfalse
481                     stack.append(False)
482                 elif opcode == 40:  # pushnan
483                     stack.append(float('NaN'))
484                 elif opcode == 42:  # dup
485                     value = stack[-1]
486                     stack.append(value)
487                 elif opcode == 44:  # pushstring
488                     idx = u30()
489                     stack.append(self.constant_strings[idx])
490                 elif opcode == 48:  # pushscope
491                     new_scope = stack.pop()
492                     scopes.append(new_scope)
493                 elif opcode == 66:  # construct
494                     arg_count = u30()
495                     args = list(reversed(
496                         [stack.pop() for _ in range(arg_count)]))
497                     obj = stack.pop()
498                     res = obj.avm_class.make_object()
499                     stack.append(res)
500                 elif opcode == 70:  # callproperty
501                     index = u30()
502                     mname = self.multinames[index]
503                     arg_count = u30()
504                     args = list(reversed(
505                         [stack.pop() for _ in range(arg_count)]))
506                     obj = stack.pop()
507
508                     if obj == StringClass:
509                         if mname == 'String':
510                             assert len(args) == 1
511                             assert isinstance(args[0], (
512                                 int, compat_str, _Undefined))
513                             if args[0] == undefined:
514                                 res = 'undefined'
515                             else:
516                                 res = compat_str(args[0])
517                             stack.append(res)
518                             continue
519                         else:
520                             raise NotImplementedError(
521                                 'Function String.%s is not yet implemented'
522                                 % mname)
523                     elif isinstance(obj, _AVMClass_Object):
524                         func = self.extract_function(obj.avm_class, mname)
525                         res = func(args)
526                         stack.append(res)
527                         continue
528                     elif isinstance(obj, _AVMClass):
529                         func = self.extract_function(obj, mname)
530                         res = func(args)
531                         stack.append(res)
532                         continue
533                     elif isinstance(obj, _ScopeDict):
534                         if mname in obj.avm_class.method_names:
535                             func = self.extract_function(obj.avm_class, mname)
536                             res = func(args)
537                         else:
538                             res = obj[mname]
539                         stack.append(res)
540                         continue
541                     elif isinstance(obj, compat_str):
542                         if mname == 'split':
543                             assert len(args) == 1
544                             assert isinstance(args[0], compat_str)
545                             if args[0] == '':
546                                 res = list(obj)
547                             else:
548                                 res = obj.split(args[0])
549                             stack.append(res)
550                             continue
551                         elif mname == 'charCodeAt':
552                             assert len(args) <= 1
553                             idx = 0 if len(args) == 0 else args[0]
554                             assert isinstance(idx, int)
555                             res = ord(obj[idx])
556                             stack.append(res)
557                             continue
558                     elif isinstance(obj, list):
559                         if mname == 'slice':
560                             assert len(args) == 1
561                             assert isinstance(args[0], int)
562                             res = obj[args[0]:]
563                             stack.append(res)
564                             continue
565                         elif mname == 'join':
566                             assert len(args) == 1
567                             assert isinstance(args[0], compat_str)
568                             res = args[0].join(obj)
569                             stack.append(res)
570                             continue
571                     raise NotImplementedError(
572                         'Unsupported property %r on %r'
573                         % (mname, obj))
574                 elif opcode == 71:  # returnvoid
575                     res = undefined
576                     return res
577                 elif opcode == 72:  # returnvalue
578                     res = stack.pop()
579                     return res
580                 elif opcode == 74:  # constructproperty
581                     index = u30()
582                     arg_count = u30()
583                     args = list(reversed(
584                         [stack.pop() for _ in range(arg_count)]))
585                     obj = stack.pop()
586
587                     mname = self.multinames[index]
588                     assert isinstance(obj, _AVMClass)
589
590                     # We do not actually call the constructor for now;
591                     # we just pretend it does nothing
592                     stack.append(obj.make_object())
593                 elif opcode == 79:  # callpropvoid
594                     index = u30()
595                     mname = self.multinames[index]
596                     arg_count = u30()
597                     args = list(reversed(
598                         [stack.pop() for _ in range(arg_count)]))
599                     obj = stack.pop()
600                     if isinstance(obj, _AVMClass_Object):
601                         func = self.extract_function(obj.avm_class, mname)
602                         res = func(args)
603                         assert res is undefined
604                         continue
605                     if isinstance(obj, _ScopeDict):
606                         assert mname in obj.avm_class.method_names
607                         func = self.extract_function(obj.avm_class, mname)
608                         res = func(args)
609                         assert res is undefined
610                         continue
611                     if mname == 'reverse':
612                         assert isinstance(obj, list)
613                         obj.reverse()
614                     else:
615                         raise NotImplementedError(
616                             'Unsupported (void) property %r on %r'
617                             % (mname, obj))
618                 elif opcode == 86:  # newarray
619                     arg_count = u30()
620                     arr = []
621                     for i in range(arg_count):
622                         arr.append(stack.pop())
623                     arr = arr[::-1]
624                     stack.append(arr)
625                 elif opcode == 93:  # findpropstrict
626                     index = u30()
627                     mname = self.multinames[index]
628                     for s in reversed(scopes):
629                         if mname in s:
630                             res = s
631                             break
632                     else:
633                         res = scopes[0]
634                     if mname not in res and mname in _builtin_classes:
635                         stack.append(_builtin_classes[mname])
636                     else:
637                         stack.append(res[mname])
638                 elif opcode == 94:  # findproperty
639                     index = u30()
640                     mname = self.multinames[index]
641                     for s in reversed(scopes):
642                         if mname in s:
643                             res = s
644                             break
645                     else:
646                         res = avm_class.variables
647                     stack.append(res)
648                 elif opcode == 96:  # getlex
649                     index = u30()
650                     mname = self.multinames[index]
651                     for s in reversed(scopes):
652                         if mname in s:
653                             scope = s
654                             break
655                     else:
656                         scope = avm_class.variables
657
658                     if mname in scope:
659                         res = scope[mname]
660                     else:
661                         res = avm_class.constants[mname]
662                     stack.append(res)
663                 elif opcode == 97:  # setproperty
664                     index = u30()
665                     value = stack.pop()
666                     idx = self.multinames[index]
667                     if isinstance(idx, _Multiname):
668                         idx = stack.pop()
669                     obj = stack.pop()
670                     obj[idx] = value
671                 elif opcode == 98:  # getlocal
672                     index = u30()
673                     stack.append(registers[index])
674                 elif opcode == 99:  # setlocal
675                     index = u30()
676                     value = stack.pop()
677                     registers[index] = value
678                 elif opcode == 102:  # getproperty
679                     index = u30()
680                     pname = self.multinames[index]
681                     if pname == 'length':
682                         obj = stack.pop()
683                         assert isinstance(obj, (compat_str, list))
684                         stack.append(len(obj))
685                     elif isinstance(pname, compat_str):  # Member access
686                         obj = stack.pop()
687                         assert isinstance(obj, (dict, _ScopeDict)), \
688                             'Accessing member %r on %r' % (pname, obj)
689                         res = obj.get(pname, undefined)
690                         stack.append(res)
691                     else:  # Assume attribute access
692                         idx = stack.pop()
693                         assert isinstance(idx, int)
694                         obj = stack.pop()
695                         assert isinstance(obj, list)
696                         stack.append(obj[idx])
697                 elif opcode == 115:  # convert_
698                     value = stack.pop()
699                     intvalue = int(value)
700                     stack.append(intvalue)
701                 elif opcode == 128:  # coerce
702                     u30()
703                 elif opcode == 130:  # coerce_a
704                     value = stack.pop()
705                     # um, yes, it's any value
706                     stack.append(value)
707                 elif opcode == 133:  # coerce_s
708                     assert isinstance(stack[-1], (type(None), compat_str))
709                 elif opcode == 147:  # decrement
710                     value = stack.pop()
711                     assert isinstance(value, int)
712                     stack.append(value - 1)
713                 elif opcode == 149:  # typeof
714                     value = stack.pop()
715                     return {
716                         _Undefined: 'undefined',
717                         compat_str: 'String',
718                         int: 'Number',
719                         float: 'Number',
720                     }[type(value)]
721                 elif opcode == 160:  # add
722                     value2 = stack.pop()
723                     value1 = stack.pop()
724                     res = value1 + value2
725                     stack.append(res)
726                 elif opcode == 161:  # subtract
727                     value2 = stack.pop()
728                     value1 = stack.pop()
729                     res = value1 - value2
730                     stack.append(res)
731                 elif opcode == 162:  # multiply
732                     value2 = stack.pop()
733                     value1 = stack.pop()
734                     res = value1 * value2
735                     stack.append(res)
736                 elif opcode == 164:  # modulo
737                     value2 = stack.pop()
738                     value1 = stack.pop()
739                     res = value1 % value2
740                     stack.append(res)
741                 elif opcode == 168:  # bitand
742                     value2 = stack.pop()
743                     value1 = stack.pop()
744                     assert isinstance(value1, int)
745                     assert isinstance(value2, int)
746                     res = value1 & value2
747                     stack.append(res)
748                 elif opcode == 171:  # equals
749                     value2 = stack.pop()
750                     value1 = stack.pop()
751                     result = value1 == value2
752                     stack.append(result)
753                 elif opcode == 175:  # greaterequals
754                     value2 = stack.pop()
755                     value1 = stack.pop()
756                     result = value1 >= value2
757                     stack.append(result)
758                 elif opcode == 192:  # increment_i
759                     value = stack.pop()
760                     assert isinstance(value, int)
761                     stack.append(value + 1)
762                 elif opcode == 208:  # getlocal_0
763                     stack.append(registers[0])
764                 elif opcode == 209:  # getlocal_1
765                     stack.append(registers[1])
766                 elif opcode == 210:  # getlocal_2
767                     stack.append(registers[2])
768                 elif opcode == 211:  # getlocal_3
769                     stack.append(registers[3])
770                 elif opcode == 212:  # setlocal_0
771                     registers[0] = stack.pop()
772                 elif opcode == 213:  # setlocal_1
773                     registers[1] = stack.pop()
774                 elif opcode == 214:  # setlocal_2
775                     registers[2] = stack.pop()
776                 elif opcode == 215:  # setlocal_3
777                     registers[3] = stack.pop()
778                 else:
779                     raise NotImplementedError(
780                         'Unsupported opcode %d' % opcode)
781
782         avm_class.method_pyfunctions[func_name] = resfunc
783         return resfunc
784