[swfinterp] Start working on basic tests
[youtube-dl] / youtube_dl / swfinterp.py
1 from __future__ import unicode_literals
2
3 import collections
4 import io
5 import struct
6 import zlib
7
8 from .utils import ExtractorError
9
10
11 def _extract_tags(file_contents):
12     if file_contents[1:3] != b'WS':
13         raise ExtractorError(
14             'Not an SWF file; header is %r' % file_contents[:3])
15     if file_contents[:1] == b'C':
16         content = zlib.decompress(file_contents[8:])
17     else:
18         raise NotImplementedError(
19             'Unsupported compression format %r' %
20             file_contents[:1])
21
22     # Determine number of bits in framesize rectangle
23     framesize_nbits = struct.unpack('!B', content[:1])[0] >> 3
24     framesize_len = (5 + 4 * framesize_nbits + 7) // 8
25
26     pos = framesize_len + 2 + 2
27     while pos < len(content):
28         header16 = struct.unpack('<H', content[pos:pos + 2])[0]
29         pos += 2
30         tag_code = header16 >> 6
31         tag_len = header16 & 0x3f
32         if tag_len == 0x3f:
33             tag_len = struct.unpack('<I', content[pos:pos + 4])[0]
34             pos += 4
35         assert pos + tag_len <= len(content), \
36             ('Tag %d ends at %d+%d - that\'s longer than the file (%d)'
37                 % (tag_code, pos, tag_len, len(content)))
38         yield (tag_code, content[pos:pos + tag_len])
39         pos += tag_len
40
41
42 class _AVMClass_Object(object):
43     def __init__(self, avm_class):
44         self.avm_class = avm_class
45
46     def __repr__(self):
47         return '%s#%x' % (self.avm_class.name, id(self))
48
49
50 class _AVMClass(object):
51     def __init__(self, name_idx, name):
52         self.name_idx = name_idx
53         self.name = name
54         self.method_names = {}
55         self.method_idxs = {}
56         self.methods = {}
57         self.method_pyfunctions = {}
58         self.variables = {}
59
60     def make_object(self):
61         return _AVMClass_Object(self)
62
63
64 def _read_int(reader):
65     res = 0
66     shift = 0
67     for _ in range(5):
68         buf = reader.read(1)
69         assert len(buf) == 1
70         b = struct.unpack('<B', buf)[0]
71         res = res | ((b & 0x7f) << shift)
72         if b & 0x80 == 0:
73             break
74         shift += 7
75     return res
76
77
78 def _u30(reader):
79     res = _read_int(reader)
80     assert res & 0xf0000000 == 0
81     return res
82 u32 = _read_int
83
84
85 def _s32(reader):
86     v = _read_int(reader)
87     if v & 0x80000000 != 0:
88         v = - ((v ^ 0xffffffff) + 1)
89     return v
90
91
92 def _s24(reader):
93     bs = reader.read(3)
94     assert len(bs) == 3
95     first_byte = b'\xff' if (ord(bs[0:1]) >= 0x80) else b'\x00'
96     return struct.unpack('!i', first_byte + bs)
97
98
99 def _read_string(reader):
100     slen = _u30(reader)
101     resb = reader.read(slen)
102     assert len(resb) == slen
103     return resb.decode('utf-8')
104
105
106 def _read_bytes(count, reader):
107     assert count >= 0
108     resb = reader.read(count)
109     assert len(resb) == count
110     return resb
111
112
113 def _read_byte(reader):
114     resb = _read_bytes(1, reader=reader)
115     res = struct.unpack('<B', resb)[0]
116     return res
117
118
119 class SWFInterpreter(object):
120     def __init__(self, file_contents):
121         code_tag = next(tag
122                         for tag_code, tag in _extract_tags(file_contents)
123                         if tag_code == 82)
124         p = code_tag.index(b'\0', 4) + 1
125         code_reader = io.BytesIO(code_tag[p:])
126
127         # Parse ABC (AVM2 ByteCode)
128
129         # Define a couple convenience methods
130         u30 = lambda *args: _u30(*args, reader=code_reader)
131         s32 = lambda *args: _s32(*args, reader=code_reader)
132         u32 = lambda *args: _u32(*args, reader=code_reader)
133         read_bytes = lambda *args: _read_bytes(*args, reader=code_reader)
134         read_byte = lambda *args: _read_byte(*args, reader=code_reader)
135
136         # minor_version + major_version
137         read_bytes(2 + 2)
138
139         # Constant pool
140         int_count = u30()
141         for _c in range(1, int_count):
142             s32()
143         uint_count = u30()
144         for _c in range(1, uint_count):
145             u32()
146         double_count = u30()
147         read_bytes(max(0, (double_count - 1)) * 8)
148         string_count = u30()
149         constant_strings = ['']
150         for _c in range(1, string_count):
151             s = _read_string(code_reader)
152             constant_strings.append(s)
153         namespace_count = u30()
154         for _c in range(1, namespace_count):
155             read_bytes(1)  # kind
156             u30()  # name
157         ns_set_count = u30()
158         for _c in range(1, ns_set_count):
159             count = u30()
160             for _c2 in range(count):
161                 u30()
162         multiname_count = u30()
163         MULTINAME_SIZES = {
164             0x07: 2,  # QName
165             0x0d: 2,  # QNameA
166             0x0f: 1,  # RTQName
167             0x10: 1,  # RTQNameA
168             0x11: 0,  # RTQNameL
169             0x12: 0,  # RTQNameLA
170             0x09: 2,  # Multiname
171             0x0e: 2,  # MultinameA
172             0x1b: 1,  # MultinameL
173             0x1c: 1,  # MultinameLA
174         }
175         self.multinames = ['']
176         for _c in range(1, multiname_count):
177             kind = u30()
178             assert kind in MULTINAME_SIZES, 'Invalid multiname kind %r' % kind
179             if kind == 0x07:
180                 u30()  # namespace_idx
181                 name_idx = u30()
182                 self.multinames.append(constant_strings[name_idx])
183             else:
184                 self.multinames.append('[MULTINAME kind: %d]' % kind)
185                 for _c2 in range(MULTINAME_SIZES[kind]):
186                     u30()
187
188         # Methods
189         method_count = u30()
190         MethodInfo = collections.namedtuple(
191             'MethodInfo',
192             ['NEED_ARGUMENTS', 'NEED_REST'])
193         method_infos = []
194         for method_id in range(method_count):
195             param_count = u30()
196             u30()  # return type
197             for _ in range(param_count):
198                 u30()  # param type
199             u30()  # name index (always 0 for youtube)
200             flags = read_byte()
201             if flags & 0x08 != 0:
202                 # Options present
203                 option_count = u30()
204                 for c in range(option_count):
205                     u30()  # val
206                     read_bytes(1)  # kind
207             if flags & 0x80 != 0:
208                 # Param names present
209                 for _ in range(param_count):
210                     u30()  # param name
211             mi = MethodInfo(flags & 0x01 != 0, flags & 0x04 != 0)
212             method_infos.append(mi)
213
214         # Metadata
215         metadata_count = u30()
216         for _c in range(metadata_count):
217             u30()  # name
218             item_count = u30()
219             for _c2 in range(item_count):
220                 u30()  # key
221                 u30()  # value
222
223         def parse_traits_info():
224             trait_name_idx = u30()
225             kind_full = read_byte()
226             kind = kind_full & 0x0f
227             attrs = kind_full >> 4
228             methods = {}
229             if kind in [0x00, 0x06]:  # Slot or Const
230                 u30()  # Slot id
231                 u30()  # type_name_idx
232                 vindex = u30()
233                 if vindex != 0:
234                     read_byte()  # vkind
235             elif kind in [0x01, 0x02, 0x03]:  # Method / Getter / Setter
236                 u30()  # disp_id
237                 method_idx = u30()
238                 methods[self.multinames[trait_name_idx]] = method_idx
239             elif kind == 0x04:  # Class
240                 u30()  # slot_id
241                 u30()  # classi
242             elif kind == 0x05:  # Function
243                 u30()  # slot_id
244                 function_idx = u30()
245                 methods[function_idx] = self.multinames[trait_name_idx]
246             else:
247                 raise ExtractorError('Unsupported trait kind %d' % kind)
248
249             if attrs & 0x4 != 0:  # Metadata present
250                 metadata_count = u30()
251                 for _c3 in range(metadata_count):
252                     u30()  # metadata index
253
254             return methods
255
256         # Classes
257         class_count = u30()
258         classes = []
259         for class_id in range(class_count):
260             name_idx = u30()
261             classes.append(_AVMClass(name_idx, self.multinames[name_idx]))
262             u30()  # super_name idx
263             flags = read_byte()
264             if flags & 0x08 != 0:  # Protected namespace is present
265                 u30()  # protected_ns_idx
266             intrf_count = u30()
267             for _c2 in range(intrf_count):
268                 u30()
269             u30()  # iinit
270             trait_count = u30()
271             for _c2 in range(trait_count):
272                 parse_traits_info()
273         assert len(classes) == class_count
274         self._classes_by_name = dict((c.name, c) for c in classes)
275
276         for avm_class in classes:
277             u30()  # cinit
278             trait_count = u30()
279             for _c2 in range(trait_count):
280                 trait_methods = parse_traits_info()
281                 avm_class.method_names.update(trait_methods.items())
282                 avm_class.method_idxs.update(dict(
283                     (idx, name)
284                     for name, idx in trait_methods.items()))
285
286         # Scripts
287         script_count = u30()
288         for _c in range(script_count):
289             u30()  # init
290             trait_count = u30()
291             for _c2 in range(trait_count):
292                 parse_traits_info()
293
294         # Method bodies
295         method_body_count = u30()
296         Method = collections.namedtuple('Method', ['code', 'local_count'])
297         for _c in range(method_body_count):
298             method_idx = u30()
299             u30()  # max_stack
300             local_count = u30()
301             u30()  # init_scope_depth
302             u30()  # max_scope_depth
303             code_length = u30()
304             code = read_bytes(code_length)
305             for avm_class in classes:
306                 if method_idx in avm_class.method_idxs:
307                     m = Method(code, local_count)
308                     avm_class.methods[avm_class.method_idxs[method_idx]] = m
309             exception_count = u30()
310             for _c2 in range(exception_count):
311                 u30()  # from
312                 u30()  # to
313                 u30()  # target
314                 u30()  # exc_type
315                 u30()  # var_name
316             trait_count = u30()
317             for _c2 in range(trait_count):
318                 parse_traits_info()
319
320         assert p + code_reader.tell() == len(code_tag)
321
322     def extract_class(self, class_name):
323         try:
324             return self._classes_by_name[class_name]
325         except KeyError:
326             raise ExtractorError('Class %r not found' % class_name)
327
328     def extract_function(self, avm_class, func_name):
329         if func_name in avm_class.method_pyfunctions:
330             return avm_class.method_pyfunctions[func_name]
331         if func_name in self._classes_by_name:
332             return self._classes_by_name[func_name].make_object()
333         if func_name not in avm_class.methods:
334             raise ExtractorError('Cannot find function %r' % func_name)
335         m = avm_class.methods[func_name]
336
337         def resfunc(args):
338             # Helper functions
339             coder = io.BytesIO(m.code)
340             s24 = lambda: _s24(coder)
341             u30 = lambda: _u30(coder)
342
343             print('Invoking %s.%s(%r)' % (avm_class.name, func_name, tuple(args)))
344             registers = ['(this)'] + list(args) + [None] * m.local_count
345             stack = []
346             while True:
347                 opcode = _read_byte(coder)
348                 print('opcode: %r, stack(%d): %r' % (opcode, len(stack), stack))
349                 if opcode == 17:  # iftrue
350                     offset = s24()
351                     value = stack.pop()
352                     if value:
353                         coder.seek(coder.tell() + offset)
354                 elif opcode == 36:  # pushbyte
355                     v = _read_byte(coder)
356                     stack.append(v)
357                 elif opcode == 42:  # dup
358                     value = stack[-1]
359                     stack.append(value)
360                 elif opcode == 44:  # pushstring
361                     idx = u30()
362                     stack.append(constant_strings[idx])
363                 elif opcode == 48:  # pushscope
364                     # We don't implement the scope register, so we'll just
365                     # ignore the popped value
366                     new_scope = stack.pop()
367                 elif opcode == 70:  # callproperty
368                     index = u30()
369                     mname = self.multinames[index]
370                     arg_count = u30()
371                     args = list(reversed(
372                         [stack.pop() for _ in range(arg_count)]))
373                     obj = stack.pop()
374                     if mname == 'split':
375                         assert len(args) == 1
376                         assert isinstance(args[0], compat_str)
377                         assert isinstance(obj, compat_str)
378                         if args[0] == '':
379                             res = list(obj)
380                         else:
381                             res = obj.split(args[0])
382                         stack.append(res)
383                     elif mname == 'slice':
384                         assert len(args) == 1
385                         assert isinstance(args[0], int)
386                         assert isinstance(obj, list)
387                         res = obj[args[0]:]
388                         stack.append(res)
389                     elif mname == 'join':
390                         assert len(args) == 1
391                         assert isinstance(args[0], compat_str)
392                         assert isinstance(obj, list)
393                         res = args[0].join(obj)
394                         stack.append(res)
395                     elif mname in avm_class.method_pyfunctions:
396                         stack.append(avm_class.method_pyfunctions[mname](args))
397                     else:
398                         raise NotImplementedError(
399                             'Unsupported property %r on %r'
400                             % (mname, obj))
401                 elif opcode == 72:  # returnvalue
402                     res = stack.pop()
403                     return res
404                 elif opcode == 74:  # constructproperty
405                     index = u30()
406                     arg_count = u30()
407                     args = list(reversed(
408                         [stack.pop() for _ in range(arg_count)]))
409                     obj = stack.pop()
410
411                     mname = self.multinames[index]
412                     construct_method = self.extract_function(
413                         obj.avm_class, mname)
414                     # We do not actually call the constructor for now;
415                     # we just pretend it does nothing
416                     stack.append(obj)
417                 elif opcode == 79:  # callpropvoid
418                     index = u30()
419                     mname = self.multinames[index]
420                     arg_count = u30()
421                     args = list(reversed(
422                         [stack.pop() for _ in range(arg_count)]))
423                     obj = stack.pop()
424                     if mname == 'reverse':
425                         assert isinstance(obj, list)
426                         obj.reverse()
427                     else:
428                         raise NotImplementedError(
429                             'Unsupported (void) property %r on %r'
430                             % (mname, obj))
431                 elif opcode == 86:  # newarray
432                     arg_count = u30()
433                     arr = []
434                     for i in range(arg_count):
435                         arr.append(stack.pop())
436                     arr = arr[::-1]
437                     stack.append(arr)
438                 elif opcode == 93:  # findpropstrict
439                     index = u30()
440                     mname = self.multinames[index]
441                     res = self.extract_function(avm_class, mname)
442                     stack.append(res)
443                 elif opcode == 94:  # findproperty
444                     index = u30()
445                     mname = self.multinames[index]
446                     res = avm_class.variables.get(mname)
447                     stack.append(res)
448                 elif opcode == 96:  # getlex
449                     index = u30()
450                     mname = self.multinames[index]
451                     res = avm_class.variables.get(mname, None)
452                     stack.append(res)
453                 elif opcode == 97:  # setproperty
454                     index = u30()
455                     value = stack.pop()
456                     idx = self.multinames[index]
457                     obj = stack.pop()
458                     obj[idx] = value
459                 elif opcode == 98:  # getlocal
460                     index = u30()
461                     stack.append(registers[index])
462                 elif opcode == 99:  # setlocal
463                     index = u30()
464                     value = stack.pop()
465                     registers[index] = value
466                 elif opcode == 102:  # getproperty
467                     index = u30()
468                     pname = self.multinames[index]
469                     if pname == 'length':
470                         obj = stack.pop()
471                         assert isinstance(obj, list)
472                         stack.append(len(obj))
473                     else:  # Assume attribute access
474                         idx = stack.pop()
475                         assert isinstance(idx, int)
476                         obj = stack.pop()
477                         assert isinstance(obj, list)
478                         stack.append(obj[idx])
479                 elif opcode == 115:  # convert_
480                     value = stack.pop()
481                     intvalue = int(value)
482                     stack.append(intvalue)
483                 elif opcode == 128:  # coerce
484                     u30()
485                 elif opcode == 133:  # coerce_s
486                     assert isinstance(stack[-1], (type(None), compat_str))
487                 elif opcode == 160:  # add
488                     value2 = stack.pop()
489                     value1 = stack.pop()
490                     res = value1 + value2
491                     stack.append(res)
492                 elif opcode == 161:  # subtract
493                     value2 = stack.pop()
494                     value1 = stack.pop()
495                     res = value1 - value2
496                     stack.append(res)
497                 elif opcode == 164:  # modulo
498                     value2 = stack.pop()
499                     value1 = stack.pop()
500                     res = value1 % value2
501                     stack.append(res)
502                 elif opcode == 175:  # greaterequals
503                     value2 = stack.pop()
504                     value1 = stack.pop()
505                     result = value1 >= value2
506                     stack.append(result)
507                 elif opcode == 208:  # getlocal_0
508                     stack.append(registers[0])
509                 elif opcode == 209:  # getlocal_1
510                     stack.append(registers[1])
511                 elif opcode == 210:  # getlocal_2
512                     stack.append(registers[2])
513                 elif opcode == 211:  # getlocal_3
514                     stack.append(registers[3])
515                 elif opcode == 214:  # setlocal_2
516                     registers[2] = stack.pop()
517                 elif opcode == 215:  # setlocal_3
518                     registers[3] = stack.pop()
519                 else:
520                     raise NotImplementedError(
521                         'Unsupported opcode %d' % opcode)
522
523         avm_class.method_pyfunctions[func_name] = resfunc
524         return resfunc
525