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 _AVM_Object(object):
43 def __init__(self, value=None, name_hint=None):
45 self.name_hint = name_hint
48 nh = '' if self.name_hint is None else (' %s' % self.name_hint)
49 return 'AVMObject%s(%r)' % (nh, self.value)
52 class _AVMClass_Object(object):
53 def __init__(self, avm_class):
54 self.avm_class = avm_class
57 return '%s#%x' % (self.avm_class.name, id(self))
60 class _AVMClass(object):
61 def __init__(self, name_idx, name):
62 self.name_idx = name_idx
64 self.method_names = {}
67 self.method_pyfunctions = {}
70 def make_object(self):
71 return _AVMClass_Object(self)
74 def _read_int(reader):
80 b = struct.unpack('<B', buf)[0]
81 res = res | ((b & 0x7f) << shift)
89 res = _read_int(reader)
90 assert res & 0xf0000000 == 0
97 if v & 0x80000000 != 0:
98 v = - ((v ^ 0xffffffff) + 1)
105 last_byte = b'\xff' if (ord(bs[2:3]) >= 0x80) else b'\x00'
106 return struct.unpack('<i', bs + last_byte)[0]
109 def _read_string(reader):
111 resb = reader.read(slen)
112 assert len(resb) == slen
113 return resb.decode('utf-8')
116 def _read_bytes(count, reader):
118 resb = reader.read(count)
119 assert len(resb) == count
123 def _read_byte(reader):
124 resb = _read_bytes(1, reader=reader)
125 res = struct.unpack('<B', resb)[0]
129 class SWFInterpreter(object):
130 def __init__(self, file_contents):
132 for tag_code, tag in _extract_tags(file_contents)
134 p = code_tag.index(b'\0', 4) + 1
135 code_reader = io.BytesIO(code_tag[p:])
137 # Parse ABC (AVM2 ByteCode)
139 # Define a couple convenience methods
140 u30 = lambda *args: _u30(*args, reader=code_reader)
141 s32 = lambda *args: _s32(*args, reader=code_reader)
142 u32 = lambda *args: _u32(*args, reader=code_reader)
143 read_bytes = lambda *args: _read_bytes(*args, reader=code_reader)
144 read_byte = lambda *args: _read_byte(*args, reader=code_reader)
146 # minor_version + major_version
151 for _c in range(1, int_count):
154 for _c in range(1, uint_count):
157 read_bytes(max(0, (double_count - 1)) * 8)
159 constant_strings = ['']
160 for _c in range(1, string_count):
161 s = _read_string(code_reader)
162 constant_strings.append(s)
163 namespace_count = u30()
164 for _c in range(1, namespace_count):
168 for _c in range(1, ns_set_count):
170 for _c2 in range(count):
172 multiname_count = u30()
181 0x0e: 2, # MultinameA
182 0x1b: 1, # MultinameL
183 0x1c: 1, # MultinameLA
185 self.multinames = ['']
186 for _c in range(1, multiname_count):
188 assert kind in MULTINAME_SIZES, 'Invalid multiname kind %r' % kind
190 u30() # namespace_idx
192 self.multinames.append(constant_strings[name_idx])
194 self.multinames.append('[MULTINAME kind: %d]' % kind)
195 for _c2 in range(MULTINAME_SIZES[kind]):
200 MethodInfo = collections.namedtuple(
202 ['NEED_ARGUMENTS', 'NEED_REST'])
204 for method_id in range(method_count):
207 for _ in range(param_count):
209 u30() # name index (always 0 for youtube)
211 if flags & 0x08 != 0:
214 for c in range(option_count):
217 if flags & 0x80 != 0:
218 # Param names present
219 for _ in range(param_count):
221 mi = MethodInfo(flags & 0x01 != 0, flags & 0x04 != 0)
222 method_infos.append(mi)
225 metadata_count = u30()
226 for _c in range(metadata_count):
229 for _c2 in range(item_count):
233 def parse_traits_info():
234 trait_name_idx = u30()
235 kind_full = read_byte()
236 kind = kind_full & 0x0f
237 attrs = kind_full >> 4
239 if kind in [0x00, 0x06]: # Slot or Const
241 u30() # type_name_idx
245 elif kind in [0x01, 0x02, 0x03]: # Method / Getter / Setter
248 methods[self.multinames[trait_name_idx]] = method_idx
249 elif kind == 0x04: # Class
252 elif kind == 0x05: # Function
255 methods[function_idx] = self.multinames[trait_name_idx]
257 raise ExtractorError('Unsupported trait kind %d' % kind)
259 if attrs & 0x4 != 0: # Metadata present
260 metadata_count = u30()
261 for _c3 in range(metadata_count):
262 u30() # metadata index
269 for class_id in range(class_count):
271 classes.append(_AVMClass(name_idx, self.multinames[name_idx]))
272 u30() # super_name idx
274 if flags & 0x08 != 0: # Protected namespace is present
275 u30() # protected_ns_idx
277 for _c2 in range(intrf_count):
281 for _c2 in range(trait_count):
283 assert len(classes) == class_count
284 self._classes_by_name = dict((c.name, c) for c in classes)
286 for avm_class in classes:
289 for _c2 in range(trait_count):
290 trait_methods = parse_traits_info()
291 avm_class.method_names.update(trait_methods.items())
292 avm_class.method_idxs.update(dict(
294 for name, idx in trait_methods.items()))
298 for _c in range(script_count):
301 for _c2 in range(trait_count):
305 method_body_count = u30()
306 Method = collections.namedtuple('Method', ['code', 'local_count'])
307 for _c in range(method_body_count):
311 u30() # init_scope_depth
312 u30() # max_scope_depth
314 code = read_bytes(code_length)
315 for avm_class in classes:
316 if method_idx in avm_class.method_idxs:
317 m = Method(code, local_count)
318 avm_class.methods[avm_class.method_idxs[method_idx]] = m
319 exception_count = u30()
320 for _c2 in range(exception_count):
327 for _c2 in range(trait_count):
330 assert p + code_reader.tell() == len(code_tag)
332 def extract_class(self, class_name):
334 return self._classes_by_name[class_name]
336 raise ExtractorError('Class %r not found' % class_name)
338 def extract_function(self, avm_class, func_name):
339 if func_name in avm_class.method_pyfunctions:
340 return avm_class.method_pyfunctions[func_name]
341 if func_name in self._classes_by_name:
342 return self._classes_by_name[func_name].make_object()
343 if func_name not in avm_class.methods:
344 raise ExtractorError('Cannot find function %r' % func_name)
345 m = avm_class.methods[func_name]
349 coder = io.BytesIO(m.code)
350 s24 = lambda: _s24(coder)
351 u30 = lambda: _u30(coder)
353 print('Invoking %s.%s(%r)' % (avm_class.name, func_name, tuple(args)))
354 registers = [avm_class.variables] + list(args) + [None] * m.local_count
356 scopes = collections.deque([avm_class.variables])
358 opcode = _read_byte(coder)
359 print('opcode: %r, stack(%d): %r' % (opcode, len(stack), stack))
360 if opcode == 17: # iftrue
364 coder.seek(coder.tell() + offset)
365 elif opcode == 18: # iffalse
369 coder.seek(coder.tell() + offset)
370 elif opcode == 36: # pushbyte
371 v = _read_byte(coder)
373 elif opcode == 42: # dup
376 elif opcode == 44: # pushstring
378 stack.append(constant_strings[idx])
379 elif opcode == 48: # pushscope
380 new_scope = stack.pop()
381 scopes.append(new_scope)
382 elif opcode == 70: # callproperty
384 mname = self.multinames[index]
386 args = list(reversed(
387 [stack.pop() for _ in range(arg_count)]))
390 assert len(args) == 1
391 assert isinstance(args[0], compat_str)
392 assert isinstance(obj, compat_str)
396 res = obj.split(args[0])
398 elif mname == 'slice':
399 assert len(args) == 1
400 assert isinstance(args[0], int)
401 assert isinstance(obj, list)
404 elif mname == 'join':
405 assert len(args) == 1
406 assert isinstance(args[0], compat_str)
407 assert isinstance(obj, list)
408 res = args[0].join(obj)
410 elif mname in avm_class.method_pyfunctions:
411 stack.append(avm_class.method_pyfunctions[mname](args))
413 raise NotImplementedError(
414 'Unsupported property %r on %r'
416 elif opcode == 72: # returnvalue
419 elif opcode == 74: # constructproperty
422 args = list(reversed(
423 [stack.pop() for _ in range(arg_count)]))
426 mname = self.multinames[index]
427 construct_method = self.extract_function(
428 obj.avm_class, mname)
429 # We do not actually call the constructor for now;
430 # we just pretend it does nothing
432 elif opcode == 79: # callpropvoid
434 mname = self.multinames[index]
436 args = list(reversed(
437 [stack.pop() for _ in range(arg_count)]))
439 if mname == 'reverse':
440 assert isinstance(obj, list)
443 raise NotImplementedError(
444 'Unsupported (void) property %r on %r'
446 elif opcode == 86: # newarray
449 for i in range(arg_count):
450 arr.append(stack.pop())
453 elif opcode == 94: # findproperty
455 mname = self.multinames[index]
456 for s in reversed(scopes):
463 elif opcode == 96: # getlex
465 mname = self.multinames[index]
466 for s in reversed(scopes):
472 # I cannot find where static variables are initialized
473 # so let's just return None
474 res = scope.get(mname)
476 elif opcode == 97: # setproperty
479 idx = self.multinames[index]
482 elif opcode == 98: # getlocal
484 stack.append(registers[index])
485 elif opcode == 99: # setlocal
488 registers[index] = value
489 elif opcode == 102: # getproperty
491 pname = self.multinames[index]
492 if pname == 'length':
494 assert isinstance(obj, list)
495 stack.append(len(obj))
496 else: # Assume attribute access
498 assert isinstance(idx, int)
500 assert isinstance(obj, list)
501 stack.append(obj[idx])
502 elif opcode == 115: # convert_
504 intvalue = int(value)
505 stack.append(intvalue)
506 elif opcode == 128: # coerce
508 elif opcode == 133: # coerce_s
509 assert isinstance(stack[-1], (type(None), compat_str))
510 elif opcode == 160: # add
513 res = value1 + value2
515 elif opcode == 161: # subtract
518 res = value1 - value2
520 elif opcode == 164: # modulo
523 res = value1 % value2
525 elif opcode == 175: # greaterequals
528 result = value1 >= value2
530 elif opcode == 208: # getlocal_0
531 stack.append(registers[0])
532 elif opcode == 209: # getlocal_1
533 stack.append(registers[1])
534 elif opcode == 210: # getlocal_2
535 stack.append(registers[2])
536 elif opcode == 211: # getlocal_3
537 stack.append(registers[3])
538 elif opcode == 214: # setlocal_2
539 registers[2] = stack.pop()
540 elif opcode == 215: # setlocal_3
541 registers[3] = stack.pop()
543 raise NotImplementedError(
544 'Unsupported opcode %d' % opcode)
546 avm_class.method_pyfunctions[func_name] = resfunc