1 from __future__ import unicode_literals
14 def _extract_tags(file_contents):
15 if file_contents[1:3] != b'WS':
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:])
21 raise NotImplementedError(
22 'Unsupported compression format %r' %
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
29 pos = framesize_len + 2 + 2
30 while pos < len(content):
31 header16 = struct.unpack('<H', content[pos:pos + 2])[0]
33 tag_code = header16 >> 6
34 tag_len = header16 & 0x3f
36 tag_len = struct.unpack('<I', content[pos:pos + 4])[0]
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])
45 class _AVM_Object(object):
46 def __init__(self, value=None, name_hint=None):
48 self.name_hint = name_hint
51 nh = '' if self.name_hint is None else (' %s' % self.name_hint)
52 return 'AVMObject%s(%r)' % (nh, self.value)
55 class _AVMClass_Object(object):
56 def __init__(self, avm_class):
57 self.avm_class = avm_class
60 return '%s#%x' % (self.avm_class.name, id(self))
63 class _AVMClass(object):
64 def __init__(self, name_idx, name):
65 self.name_idx = name_idx
67 self.method_names = {}
70 self.method_pyfunctions = {}
72 class ScopeDict(dict):
73 def __init__(self, avm_class):
74 super(ScopeDict, self).__init__()
75 self.avm_class = avm_class
77 def __getitem__(self, k):
78 print('getting %r' % k)
79 return super(ScopeDict, self).__getitem__(k)
81 def __contains__(self, k):
82 print('contains %r' % k)
83 return super(ScopeDict, self).__contains__(k)
86 return '%s__Scope(%s)' % (
88 super(ScopeDict, self).__repr__())
90 self.variables = ScopeDict(self)
92 def make_object(self):
93 return _AVMClass_Object(self)
96 def _read_int(reader):
102 b = struct.unpack('<B', buf)[0]
103 res = res | ((b & 0x7f) << shift)
111 res = _read_int(reader)
112 assert res & 0xf0000000 == 0
118 v = _read_int(reader)
119 if v & 0x80000000 != 0:
120 v = - ((v ^ 0xffffffff) + 1)
127 last_byte = b'\xff' if (ord(bs[2:3]) >= 0x80) else b'\x00'
128 return struct.unpack('<i', bs + last_byte)[0]
131 def _read_string(reader):
133 resb = reader.read(slen)
134 assert len(resb) == slen
135 return resb.decode('utf-8')
138 def _read_bytes(count, reader):
140 resb = reader.read(count)
141 assert len(resb) == count
145 def _read_byte(reader):
146 resb = _read_bytes(1, reader=reader)
147 res = struct.unpack('<B', resb)[0]
151 class SWFInterpreter(object):
152 def __init__(self, file_contents):
154 for tag_code, tag in _extract_tags(file_contents)
156 p = code_tag.index(b'\0', 4) + 1
157 code_reader = io.BytesIO(code_tag[p:])
159 # Parse ABC (AVM2 ByteCode)
161 # Define a couple convenience methods
162 u30 = lambda *args: _u30(*args, reader=code_reader)
163 s32 = lambda *args: _s32(*args, reader=code_reader)
164 u32 = lambda *args: _u32(*args, reader=code_reader)
165 read_bytes = lambda *args: _read_bytes(*args, reader=code_reader)
166 read_byte = lambda *args: _read_byte(*args, reader=code_reader)
168 # minor_version + major_version
173 for _c in range(1, int_count):
176 for _c in range(1, uint_count):
179 read_bytes(max(0, (double_count - 1)) * 8)
181 self.constant_strings = ['']
182 for _c in range(1, string_count):
183 s = _read_string(code_reader)
184 self.constant_strings.append(s)
185 namespace_count = u30()
186 for _c in range(1, namespace_count):
190 for _c in range(1, ns_set_count):
192 for _c2 in range(count):
194 multiname_count = u30()
203 0x0e: 2, # MultinameA
204 0x1b: 1, # MultinameL
205 0x1c: 1, # MultinameLA
207 self.multinames = ['']
208 for _c in range(1, multiname_count):
210 assert kind in MULTINAME_SIZES, 'Invalid multiname kind %r' % kind
212 u30() # namespace_idx
214 self.multinames.append(self.constant_strings[name_idx])
216 self.multinames.append('[MULTINAME kind: %d]' % kind)
217 for _c2 in range(MULTINAME_SIZES[kind]):
222 MethodInfo = collections.namedtuple(
224 ['NEED_ARGUMENTS', 'NEED_REST'])
226 for method_id in range(method_count):
229 for _ in range(param_count):
231 u30() # name index (always 0 for youtube)
233 if flags & 0x08 != 0:
236 for c in range(option_count):
239 if flags & 0x80 != 0:
240 # Param names present
241 for _ in range(param_count):
243 mi = MethodInfo(flags & 0x01 != 0, flags & 0x04 != 0)
244 method_infos.append(mi)
247 metadata_count = u30()
248 for _c in range(metadata_count):
251 for _c2 in range(item_count):
255 def parse_traits_info():
256 trait_name_idx = u30()
257 kind_full = read_byte()
258 kind = kind_full & 0x0f
259 attrs = kind_full >> 4
261 if kind in [0x00, 0x06]: # Slot or Const
263 u30() # type_name_idx
267 elif kind in [0x01, 0x02, 0x03]: # Method / Getter / Setter
270 methods[self.multinames[trait_name_idx]] = method_idx
271 elif kind == 0x04: # Class
274 elif kind == 0x05: # Function
277 methods[function_idx] = self.multinames[trait_name_idx]
279 raise ExtractorError('Unsupported trait kind %d' % kind)
281 if attrs & 0x4 != 0: # Metadata present
282 metadata_count = u30()
283 for _c3 in range(metadata_count):
284 u30() # metadata index
291 for class_id in range(class_count):
293 classes.append(_AVMClass(name_idx, self.multinames[name_idx]))
294 u30() # super_name idx
296 if flags & 0x08 != 0: # Protected namespace is present
297 u30() # protected_ns_idx
299 for _c2 in range(intrf_count):
303 for _c2 in range(trait_count):
305 assert len(classes) == class_count
306 self._classes_by_name = dict((c.name, c) for c in classes)
308 for avm_class in classes:
311 for _c2 in range(trait_count):
312 trait_methods = parse_traits_info()
313 avm_class.method_names.update(trait_methods.items())
314 avm_class.method_idxs.update(dict(
316 for name, idx in trait_methods.items()))
320 for _c in range(script_count):
323 for _c2 in range(trait_count):
327 method_body_count = u30()
328 Method = collections.namedtuple('Method', ['code', 'local_count'])
329 for _c in range(method_body_count):
333 u30() # init_scope_depth
334 u30() # max_scope_depth
336 code = read_bytes(code_length)
337 for avm_class in classes:
338 if method_idx in avm_class.method_idxs:
339 m = Method(code, local_count)
340 avm_class.methods[avm_class.method_idxs[method_idx]] = m
341 exception_count = u30()
342 for _c2 in range(exception_count):
349 for _c2 in range(trait_count):
352 assert p + code_reader.tell() == len(code_tag)
354 def extract_class(self, class_name):
356 return self._classes_by_name[class_name]
358 raise ExtractorError('Class %r not found' % class_name)
360 def extract_function(self, avm_class, func_name):
361 if func_name in avm_class.method_pyfunctions:
362 return avm_class.method_pyfunctions[func_name]
363 if func_name in self._classes_by_name:
364 return self._classes_by_name[func_name].make_object()
365 if func_name not in avm_class.methods:
366 raise ExtractorError('Cannot find function %r' % func_name)
367 m = avm_class.methods[func_name]
371 coder = io.BytesIO(m.code)
372 s24 = lambda: _s24(coder)
373 u30 = lambda: _u30(coder)
375 print('Invoking %s.%s(%r)' % (avm_class.name, func_name, tuple(args)))
376 registers = [avm_class.variables] + list(args) + [None] * m.local_count
378 scopes = collections.deque([avm_class.variables])
380 opcode = _read_byte(coder)
381 print('opcode: %r, stack(%d): %r' % (opcode, len(stack), stack))
382 if opcode == 17: # iftrue
386 coder.seek(coder.tell() + offset)
387 elif opcode == 18: # iffalse
391 coder.seek(coder.tell() + offset)
392 elif opcode == 36: # pushbyte
393 v = _read_byte(coder)
395 elif opcode == 42: # dup
398 elif opcode == 44: # pushstring
400 stack.append(self.constant_strings[idx])
401 elif opcode == 48: # pushscope
402 new_scope = stack.pop()
403 scopes.append(new_scope)
404 elif opcode == 70: # callproperty
406 mname = self.multinames[index]
408 args = list(reversed(
409 [stack.pop() for _ in range(arg_count)]))
412 assert len(args) == 1
413 assert isinstance(args[0], compat_str)
414 assert isinstance(obj, compat_str)
418 res = obj.split(args[0])
420 elif mname == 'slice':
421 assert len(args) == 1
422 assert isinstance(args[0], int)
423 assert isinstance(obj, list)
426 elif mname == 'join':
427 assert len(args) == 1
428 assert isinstance(args[0], compat_str)
429 assert isinstance(obj, list)
430 res = args[0].join(obj)
432 elif mname in avm_class.method_pyfunctions:
433 stack.append(avm_class.method_pyfunctions[mname](args))
435 raise NotImplementedError(
436 'Unsupported property %r on %r'
438 elif opcode == 72: # returnvalue
441 elif opcode == 74: # constructproperty
444 args = list(reversed(
445 [stack.pop() for _ in range(arg_count)]))
448 mname = self.multinames[index]
449 construct_method = self.extract_function(
450 obj.avm_class, mname)
451 # We do not actually call the constructor for now;
452 # we just pretend it does nothing
454 elif opcode == 79: # callpropvoid
456 mname = self.multinames[index]
458 args = list(reversed(
459 [stack.pop() for _ in range(arg_count)]))
461 if mname == 'reverse':
462 assert isinstance(obj, list)
465 raise NotImplementedError(
466 'Unsupported (void) property %r on %r'
468 elif opcode == 86: # newarray
471 for i in range(arg_count):
472 arr.append(stack.pop())
475 elif opcode == 93: # findpropstrict
477 mname = self.multinames[index]
478 for s in reversed(scopes):
485 elif opcode == 94: # findproperty
487 mname = self.multinames[index]
488 for s in reversed(scopes):
495 elif opcode == 96: # getlex
497 mname = self.multinames[index]
498 for s in reversed(scopes):
504 # I cannot find where static variables are initialized
505 # so let's just return None
506 res = scope.get(mname)
508 elif opcode == 97: # setproperty
511 idx = self.multinames[index]
514 elif opcode == 98: # getlocal
516 stack.append(registers[index])
517 elif opcode == 99: # setlocal
520 registers[index] = value
521 elif opcode == 102: # getproperty
523 pname = self.multinames[index]
524 if pname == 'length':
526 assert isinstance(obj, list)
527 stack.append(len(obj))
528 else: # Assume attribute access
530 assert isinstance(idx, int)
532 assert isinstance(obj, list)
533 stack.append(obj[idx])
534 elif opcode == 115: # convert_
536 intvalue = int(value)
537 stack.append(intvalue)
538 elif opcode == 128: # coerce
540 elif opcode == 133: # coerce_s
541 assert isinstance(stack[-1], (type(None), compat_str))
542 elif opcode == 160: # add
545 res = value1 + value2
547 elif opcode == 161: # subtract
550 res = value1 - value2
552 elif opcode == 164: # modulo
555 res = value1 % value2
557 elif opcode == 175: # greaterequals
560 result = value1 >= value2
562 elif opcode == 208: # getlocal_0
563 stack.append(registers[0])
564 elif opcode == 209: # getlocal_1
565 stack.append(registers[1])
566 elif opcode == 210: # getlocal_2
567 stack.append(registers[2])
568 elif opcode == 211: # getlocal_3
569 stack.append(registers[3])
570 elif opcode == 212: # setlocal_0
571 registers[0] = stack.pop()
572 elif opcode == 213: # setlocal_1
573 registers[1] = stack.pop()
574 elif opcode == 214: # setlocal_2
575 registers[2] = stack.pop()
576 elif opcode == 215: # setlocal_3
577 registers[3] = stack.pop()
579 raise NotImplementedError(
580 'Unsupported opcode %d' % opcode)
582 avm_class.method_pyfunctions[func_name] = resfunc