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