1 from __future__ import unicode_literals
8 from .utils import ExtractorError
11 def _extract_tags(file_contents):
12 if file_contents[1:3] != b'WS':
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:])
18 raise NotImplementedError(
19 'Unsupported compression format %r' %
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
26 pos = framesize_len + 2 + 2
27 while pos < len(content):
28 header16 = struct.unpack('<H', content[pos:pos + 2])[0]
30 tag_code = header16 >> 6
31 tag_len = header16 & 0x3f
33 tag_len = struct.unpack('<I', content[pos:pos + 4])[0]
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])
42 class _AVMClass_Object(object):
43 def __init__(self, avm_class):
44 self.avm_class = avm_class
47 return '%s#%x' % (self.avm_class.name, id(self))
50 class _AVMClass(object):
51 def __init__(self, name_idx, name):
52 self.name_idx = name_idx
54 self.method_names = {}
57 self.method_pyfunctions = {}
60 def make_object(self):
61 return _AVMClass_Object(self)
64 def _read_int(reader):
70 b = struct.unpack('<B', buf)[0]
71 res = res | ((b & 0x7f) << shift)
79 res = _read_int(reader)
80 assert res & 0xf0000000 == 0
87 if v & 0x80000000 != 0:
88 v = - ((v ^ 0xffffffff) + 1)
95 first_byte = b'\xff' if (ord(bs[0:1]) >= 0x80) else b'\x00'
96 return struct.unpack('!i', first_byte + bs)
99 def _read_string(reader):
101 resb = reader.read(slen)
102 assert len(resb) == slen
103 return resb.decode('utf-8')
106 def _read_bytes(count, reader):
108 resb = reader.read(count)
109 assert len(resb) == count
113 def _read_byte(reader):
114 resb = _read_bytes(1, reader=reader)
115 res = struct.unpack('<B', resb)[0]
119 class SWFInterpreter(object):
120 def __init__(self, file_contents):
122 for tag_code, tag in _extract_tags(file_contents)
124 p = code_tag.index(b'\0', 4) + 1
125 code_reader = io.BytesIO(code_tag[p:])
127 # Parse ABC (AVM2 ByteCode)
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)
136 # minor_version + major_version
141 for _c in range(1, int_count):
144 for _c in range(1, uint_count):
147 read_bytes(max(0, (double_count - 1)) * 8)
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):
158 for _c in range(1, ns_set_count):
160 for _c2 in range(count):
162 multiname_count = u30()
171 0x0e: 2, # MultinameA
172 0x1b: 1, # MultinameL
173 0x1c: 1, # MultinameLA
175 self.multinames = ['']
176 for _c in range(1, multiname_count):
178 assert kind in MULTINAME_SIZES, 'Invalid multiname kind %r' % kind
180 u30() # namespace_idx
182 self.multinames.append(constant_strings[name_idx])
184 self.multinames.append('[MULTINAME kind: %d]' % kind)
185 for _c2 in range(MULTINAME_SIZES[kind]):
190 MethodInfo = collections.namedtuple(
192 ['NEED_ARGUMENTS', 'NEED_REST'])
194 for method_id in range(method_count):
197 for _ in range(param_count):
199 u30() # name index (always 0 for youtube)
201 if flags & 0x08 != 0:
204 for c in range(option_count):
207 if flags & 0x80 != 0:
208 # Param names present
209 for _ in range(param_count):
211 mi = MethodInfo(flags & 0x01 != 0, flags & 0x04 != 0)
212 method_infos.append(mi)
215 metadata_count = u30()
216 for _c in range(metadata_count):
219 for _c2 in range(item_count):
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
229 if kind in [0x00, 0x06]: # Slot or Const
231 u30() # type_name_idx
235 elif kind in [0x01, 0x02, 0x03]: # Method / Getter / Setter
238 methods[self.multinames[trait_name_idx]] = method_idx
239 elif kind == 0x04: # Class
242 elif kind == 0x05: # Function
245 methods[function_idx] = self.multinames[trait_name_idx]
247 raise ExtractorError('Unsupported trait kind %d' % kind)
249 if attrs & 0x4 != 0: # Metadata present
250 metadata_count = u30()
251 for _c3 in range(metadata_count):
252 u30() # metadata index
259 for class_id in range(class_count):
261 classes.append(_AVMClass(name_idx, self.multinames[name_idx]))
262 u30() # super_name idx
264 if flags & 0x08 != 0: # Protected namespace is present
265 u30() # protected_ns_idx
267 for _c2 in range(intrf_count):
271 for _c2 in range(trait_count):
273 assert len(classes) == class_count
274 self._classes_by_name = dict((c.name, c) for c in classes)
276 for avm_class in classes:
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(
284 for name, idx in trait_methods.items()))
288 for _c in range(script_count):
291 for _c2 in range(trait_count):
295 method_body_count = u30()
296 Method = collections.namedtuple('Method', ['code', 'local_count'])
297 for _c in range(method_body_count):
301 u30() # init_scope_depth
302 u30() # max_scope_depth
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):
317 for _c2 in range(trait_count):
320 assert p + code_reader.tell() == len(code_tag)
322 def extract_class(self, class_name):
324 return self._classes_by_name[class_name]
326 raise ExtractorError('Class %r not found' % class_name)
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]
339 coder = io.BytesIO(m.code)
340 s24 = lambda: _s24(coder)
341 u30 = lambda: _u30(coder)
343 print('Invoking %s.%s(%r)' % (avm_class.name, func_name, tuple(args)))
344 registers = ['(this)'] + list(args) + [None] * m.local_count
347 opcode = _read_byte(coder)
348 print('opcode: %r, stack(%d): %r' % (opcode, len(stack), stack))
349 if opcode == 17: # iftrue
353 coder.seek(coder.tell() + offset)
354 elif opcode == 36: # pushbyte
355 v = _read_byte(coder)
357 elif opcode == 42: # dup
360 elif opcode == 44: # pushstring
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
369 mname = self.multinames[index]
371 args = list(reversed(
372 [stack.pop() for _ in range(arg_count)]))
375 assert len(args) == 1
376 assert isinstance(args[0], compat_str)
377 assert isinstance(obj, compat_str)
381 res = obj.split(args[0])
383 elif mname == 'slice':
384 assert len(args) == 1
385 assert isinstance(args[0], int)
386 assert isinstance(obj, list)
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)
395 elif mname in avm_class.method_pyfunctions:
396 stack.append(avm_class.method_pyfunctions[mname](args))
398 raise NotImplementedError(
399 'Unsupported property %r on %r'
401 elif opcode == 72: # returnvalue
404 elif opcode == 74: # constructproperty
407 args = list(reversed(
408 [stack.pop() for _ in range(arg_count)]))
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
417 elif opcode == 79: # callpropvoid
419 mname = self.multinames[index]
421 args = list(reversed(
422 [stack.pop() for _ in range(arg_count)]))
424 if mname == 'reverse':
425 assert isinstance(obj, list)
428 raise NotImplementedError(
429 'Unsupported (void) property %r on %r'
431 elif opcode == 86: # newarray
434 for i in range(arg_count):
435 arr.append(stack.pop())
438 elif opcode == 93: # findpropstrict
440 mname = self.multinames[index]
441 res = self.extract_function(avm_class, mname)
443 elif opcode == 94: # findproperty
445 mname = self.multinames[index]
446 res = avm_class.variables.get(mname)
448 elif opcode == 96: # getlex
450 mname = self.multinames[index]
451 res = avm_class.variables.get(mname, None)
453 elif opcode == 97: # setproperty
456 idx = self.multinames[index]
459 elif opcode == 98: # getlocal
461 stack.append(registers[index])
462 elif opcode == 99: # setlocal
465 registers[index] = value
466 elif opcode == 102: # getproperty
468 pname = self.multinames[index]
469 if pname == 'length':
471 assert isinstance(obj, list)
472 stack.append(len(obj))
473 else: # Assume attribute access
475 assert isinstance(idx, int)
477 assert isinstance(obj, list)
478 stack.append(obj[idx])
479 elif opcode == 115: # convert_
481 intvalue = int(value)
482 stack.append(intvalue)
483 elif opcode == 128: # coerce
485 elif opcode == 133: # coerce_s
486 assert isinstance(stack[-1], (type(None), compat_str))
487 elif opcode == 160: # add
490 res = value1 + value2
492 elif opcode == 161: # subtract
495 res = value1 - value2
497 elif opcode == 164: # modulo
500 res = value1 % value2
502 elif opcode == 175: # greaterequals
505 result = value1 >= value2
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()
520 raise NotImplementedError(
521 'Unsupported opcode %d' % opcode)
523 avm_class.method_pyfunctions[func_name] = resfunc