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