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