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