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 _AVMClass_Object(object):
46 def __init__(self, avm_class):
47 self.avm_class = avm_class
50 return '%s#%x' % (self.avm_class.name, id(self))
53 class _ScopeDict(dict):
54 def __init__(self, avm_class):
55 super(_ScopeDict, self).__init__()
56 self.avm_class = avm_class
59 return '%s__Scope(%s)' % (
61 super(_ScopeDict, self).__repr__())
64 class _AVMClass(object):
65 def __init__(self, name_idx, name):
66 self.name_idx = name_idx
68 self.method_names = {}
71 self.method_pyfunctions = {}
73 self.variables = _ScopeDict(self)
76 def make_object(self):
77 return _AVMClass_Object(self)
80 return '_AVMClass(%s)' % (self.name)
82 def register_methods(self, methods):
83 self.method_names.update(methods.items())
84 self.method_idxs.update(dict(
86 for name, idx in methods.items()))
89 class _Multiname(object):
90 def __init__(self, kind):
94 return '[MULTINAME kind: 0x%x]' % self.kind
97 def _read_int(reader):
103 b = struct_unpack('<B', buf)[0]
104 res = res | ((b & 0x7f) << shift)
112 res = _read_int(reader)
113 assert res & 0xf0000000 == 0
119 v = _read_int(reader)
120 if v & 0x80000000 != 0:
121 v = - ((v ^ 0xffffffff) + 1)
128 last_byte = b'\xff' if (ord(bs[2:3]) >= 0x80) else b'\x00'
129 return struct_unpack('<i', bs + last_byte)[0]
132 def _read_string(reader):
134 resb = reader.read(slen)
135 assert len(resb) == slen
136 return resb.decode('utf-8')
139 def _read_bytes(count, reader):
141 resb = reader.read(count)
142 assert len(resb) == count
146 def _read_byte(reader):
147 resb = _read_bytes(1, reader=reader)
148 res = struct_unpack('<B', resb)[0]
152 StringClass = _AVMClass('(no name idx)', 'String')
153 ByteArrayClass = _AVMClass('(no name idx)', 'ByteArray')
155 StringClass.name: StringClass,
156 ByteArrayClass.name: ByteArrayClass,
160 class _Undefined(object):
161 def __boolean__(self):
167 undefined = _Undefined()
170 class SWFInterpreter(object):
171 def __init__(self, file_contents):
172 self._patched_functions = {}
174 for tag_code, tag in _extract_tags(file_contents)
176 p = code_tag.index(b'\0', 4) + 1
177 code_reader = io.BytesIO(code_tag[p:])
179 # Parse ABC (AVM2 ByteCode)
181 # Define a couple convenience methods
182 u30 = lambda *args: _u30(*args, reader=code_reader)
183 s32 = lambda *args: _s32(*args, reader=code_reader)
184 u32 = lambda *args: _u32(*args, reader=code_reader)
185 read_bytes = lambda *args: _read_bytes(*args, reader=code_reader)
186 read_byte = lambda *args: _read_byte(*args, reader=code_reader)
188 # minor_version + major_version
193 self.constant_ints = [0]
194 for _c in range(1, int_count):
195 self.constant_ints.append(s32())
196 self.constant_uints = [0]
198 for _c in range(1, uint_count):
199 self.constant_uints.append(u32())
201 read_bytes(max(0, (double_count - 1)) * 8)
203 self.constant_strings = ['']
204 for _c in range(1, string_count):
205 s = _read_string(code_reader)
206 self.constant_strings.append(s)
207 namespace_count = u30()
208 for _c in range(1, namespace_count):
212 for _c in range(1, ns_set_count):
214 for _c2 in range(count):
216 multiname_count = u30()
225 0x0e: 2, # MultinameA
226 0x1b: 1, # MultinameL
227 0x1c: 1, # MultinameLA
229 self.multinames = ['']
230 for _c in range(1, multiname_count):
232 assert kind in MULTINAME_SIZES, 'Invalid multiname kind %r' % kind
234 u30() # namespace_idx
236 self.multinames.append(self.constant_strings[name_idx])
240 self.multinames.append(self.constant_strings[name_idx])
242 self.multinames.append(_Multiname(kind))
243 for _c2 in range(MULTINAME_SIZES[kind]):
248 MethodInfo = collections.namedtuple(
250 ['NEED_ARGUMENTS', 'NEED_REST'])
252 for method_id in range(method_count):
255 for _ in range(param_count):
257 u30() # name index (always 0 for youtube)
259 if flags & 0x08 != 0:
262 for c in range(option_count):
265 if flags & 0x80 != 0:
266 # Param names present
267 for _ in range(param_count):
269 mi = MethodInfo(flags & 0x01 != 0, flags & 0x04 != 0)
270 method_infos.append(mi)
273 metadata_count = u30()
274 for _c in range(metadata_count):
277 for _c2 in range(item_count):
281 def parse_traits_info():
282 trait_name_idx = u30()
283 kind_full = read_byte()
284 kind = kind_full & 0x0f
285 attrs = kind_full >> 4
288 if kind == 0x00: # Slot
290 u30() # type_name_idx
294 elif kind == 0x06: # Const
296 u30() # type_name_idx
301 if vkind == 0x03: # Constant_Int
302 value = self.constant_ints[vindex]
303 elif vkind == 0x04: # Constant_UInt
304 value = self.constant_uints[vindex]
306 return {}, None # Ignore silently for now
307 constants = {self.multinames[trait_name_idx]: value}
308 elif kind in (0x01, 0x02, 0x03): # Method / Getter / Setter
311 methods[self.multinames[trait_name_idx]] = method_idx
312 elif kind == 0x04: # Class
315 elif kind == 0x05: # Function
318 methods[function_idx] = self.multinames[trait_name_idx]
320 raise ExtractorError('Unsupported trait kind %d' % kind)
322 if attrs & 0x4 != 0: # Metadata present
323 metadata_count = u30()
324 for _c3 in range(metadata_count):
325 u30() # metadata index
327 return methods, constants
332 for class_id in range(class_count):
335 cname = self.multinames[name_idx]
336 avm_class = _AVMClass(name_idx, cname)
337 classes.append(avm_class)
339 u30() # super_name idx
341 if flags & 0x08 != 0: # Protected namespace is present
342 u30() # protected_ns_idx
344 for _c2 in range(intrf_count):
348 for _c2 in range(trait_count):
349 trait_methods, constants = parse_traits_info()
350 avm_class.register_methods(trait_methods)
351 assert constants is None
353 assert len(classes) == class_count
354 self._classes_by_name = dict((c.name, c) for c in classes)
356 for avm_class in classes:
357 avm_class.cinit_idx = u30()
359 for _c2 in range(trait_count):
360 trait_methods, trait_constants = parse_traits_info()
361 avm_class.register_methods(trait_methods)
363 avm_class.constants.update(trait_constants)
367 for _c in range(script_count):
370 for _c2 in range(trait_count):
374 method_body_count = u30()
375 Method = collections.namedtuple('Method', ['code', 'local_count'])
376 self._all_methods = []
377 for _c in range(method_body_count):
381 u30() # init_scope_depth
382 u30() # max_scope_depth
384 code = read_bytes(code_length)
385 m = Method(code, local_count)
386 self._all_methods.append(m)
387 for avm_class in classes:
388 if method_idx in avm_class.method_idxs:
389 avm_class.methods[avm_class.method_idxs[method_idx]] = m
390 exception_count = u30()
391 for _c2 in range(exception_count):
398 for _c2 in range(trait_count):
401 assert p + code_reader.tell() == len(code_tag)
403 def patch_function(self, avm_class, func_name, f):
404 self._patched_functions[(avm_class, func_name)] = f
406 def extract_class(self, class_name, call_cinit=True):
408 res = self._classes_by_name[class_name]
410 raise ExtractorError('Class %r not found' % class_name)
412 if call_cinit and hasattr(res, 'cinit_idx'):
413 res.register_methods({'$cinit': res.cinit_idx})
414 res.methods['$cinit'] = self._all_methods[res.cinit_idx]
415 cinit = self.extract_function(res, '$cinit')
420 def extract_function(self, avm_class, func_name):
421 p = self._patched_functions.get((avm_class, func_name))
424 if func_name in avm_class.method_pyfunctions:
425 return avm_class.method_pyfunctions[func_name]
426 if func_name in self._classes_by_name:
427 return self._classes_by_name[func_name].make_object()
428 if func_name not in avm_class.methods:
429 raise ExtractorError('Cannot find function %s.%s' % (
430 avm_class.name, func_name))
431 m = avm_class.methods[func_name]
435 coder = io.BytesIO(m.code)
436 s24 = lambda: _s24(coder)
437 u30 = lambda: _u30(coder)
439 registers = [avm_class.variables] + list(args) + [None] * m.local_count
441 scopes = collections.deque([
442 self._classes_by_name, avm_class.variables])
444 opcode = _read_byte(coder)
445 if opcode == 9: # label
446 pass # Spec says: "Do nothing."
447 elif opcode == 16: # jump
449 coder.seek(coder.tell() + offset)
450 elif opcode == 17: # iftrue
454 coder.seek(coder.tell() + offset)
455 elif opcode == 18: # iffalse
459 coder.seek(coder.tell() + offset)
460 elif opcode == 19: # ifeq
465 coder.seek(coder.tell() + offset)
466 elif opcode == 20: # ifne
471 coder.seek(coder.tell() + offset)
472 elif opcode == 21: # iflt
477 coder.seek(coder.tell() + offset)
478 elif opcode == 32: # pushnull
480 elif opcode == 33: # pushundefined
481 stack.append(undefined)
482 elif opcode == 36: # pushbyte
483 v = _read_byte(coder)
485 elif opcode == 37: # pushshort
488 elif opcode == 38: # pushtrue
490 elif opcode == 39: # pushfalse
492 elif opcode == 40: # pushnan
493 stack.append(float('NaN'))
494 elif opcode == 42: # dup
497 elif opcode == 44: # pushstring
499 stack.append(self.constant_strings[idx])
500 elif opcode == 48: # pushscope
501 new_scope = stack.pop()
502 scopes.append(new_scope)
503 elif opcode == 66: # construct
505 args = list(reversed(
506 [stack.pop() for _ in range(arg_count)]))
508 res = obj.avm_class.make_object()
510 elif opcode == 70: # callproperty
512 mname = self.multinames[index]
514 args = list(reversed(
515 [stack.pop() for _ in range(arg_count)]))
518 if obj == StringClass:
519 if mname == 'String':
520 assert len(args) == 1
521 assert isinstance(args[0], (
522 int, compat_str, _Undefined))
523 if args[0] == undefined:
526 res = compat_str(args[0])
530 raise NotImplementedError(
531 'Function String.%s is not yet implemented'
533 elif isinstance(obj, _AVMClass_Object):
534 func = self.extract_function(obj.avm_class, mname)
538 elif isinstance(obj, _AVMClass):
539 func = self.extract_function(obj, mname)
543 elif isinstance(obj, _ScopeDict):
544 if mname in obj.avm_class.method_names:
545 func = self.extract_function(obj.avm_class, mname)
551 elif isinstance(obj, compat_str):
553 assert len(args) == 1
554 assert isinstance(args[0], compat_str)
558 res = obj.split(args[0])
561 elif mname == 'charCodeAt':
562 assert len(args) <= 1
563 idx = 0 if len(args) == 0 else args[0]
564 assert isinstance(idx, int)
568 elif isinstance(obj, list):
570 assert len(args) == 1
571 assert isinstance(args[0], int)
575 elif mname == 'join':
576 assert len(args) == 1
577 assert isinstance(args[0], compat_str)
578 res = args[0].join(obj)
581 raise NotImplementedError(
582 'Unsupported property %r on %r'
584 elif opcode == 71: # returnvoid
587 elif opcode == 72: # returnvalue
590 elif opcode == 74: # constructproperty
593 args = list(reversed(
594 [stack.pop() for _ in range(arg_count)]))
597 mname = self.multinames[index]
598 assert isinstance(obj, _AVMClass)
600 # We do not actually call the constructor for now;
601 # we just pretend it does nothing
602 stack.append(obj.make_object())
603 elif opcode == 79: # callpropvoid
605 mname = self.multinames[index]
607 args = list(reversed(
608 [stack.pop() for _ in range(arg_count)]))
610 if isinstance(obj, _AVMClass_Object):
611 func = self.extract_function(obj.avm_class, mname)
613 assert res is undefined
615 if isinstance(obj, _ScopeDict):
616 assert mname in obj.avm_class.method_names
617 func = self.extract_function(obj.avm_class, mname)
619 assert res is undefined
621 if mname == 'reverse':
622 assert isinstance(obj, list)
625 raise NotImplementedError(
626 'Unsupported (void) property %r on %r'
628 elif opcode == 86: # newarray
631 for i in range(arg_count):
632 arr.append(stack.pop())
635 elif opcode == 93: # findpropstrict
637 mname = self.multinames[index]
638 for s in reversed(scopes):
644 if mname not in res and mname in _builtin_classes:
645 stack.append(_builtin_classes[mname])
647 stack.append(res[mname])
648 elif opcode == 94: # findproperty
650 mname = self.multinames[index]
651 for s in reversed(scopes):
656 res = avm_class.variables
658 elif opcode == 96: # getlex
660 mname = self.multinames[index]
661 for s in reversed(scopes):
666 scope = avm_class.variables
671 res = avm_class.constants[mname]
673 elif opcode == 97: # setproperty
676 idx = self.multinames[index]
677 if isinstance(idx, _Multiname):
681 elif opcode == 98: # getlocal
683 stack.append(registers[index])
684 elif opcode == 99: # setlocal
687 registers[index] = value
688 elif opcode == 102: # getproperty
690 pname = self.multinames[index]
691 if pname == 'length':
693 assert isinstance(obj, (compat_str, list))
694 stack.append(len(obj))
695 elif isinstance(pname, compat_str): # Member access
697 assert isinstance(obj, (dict, _ScopeDict)), \
698 'Accessing member %r on %r' % (pname, obj)
699 res = obj.get(pname, undefined)
701 else: # Assume attribute access
703 assert isinstance(idx, int)
705 assert isinstance(obj, list)
706 stack.append(obj[idx])
707 elif opcode == 104: # initproperty
710 idx = self.multinames[index]
711 if isinstance(idx, _Multiname):
715 elif opcode == 115: # convert_
717 intvalue = int(value)
718 stack.append(intvalue)
719 elif opcode == 128: # coerce
721 elif opcode == 130: # coerce_a
723 # um, yes, it's any value
725 elif opcode == 133: # coerce_s
726 assert isinstance(stack[-1], (type(None), compat_str))
727 elif opcode == 147: # decrement
729 assert isinstance(value, int)
730 stack.append(value - 1)
731 elif opcode == 149: # typeof
734 _Undefined: 'undefined',
735 compat_str: 'String',
739 elif opcode == 160: # add
742 res = value1 + value2
744 elif opcode == 161: # subtract
747 res = value1 - value2
749 elif opcode == 162: # multiply
752 res = value1 * value2
754 elif opcode == 164: # modulo
757 res = value1 % value2
759 elif opcode == 168: # bitand
762 assert isinstance(value1, int)
763 assert isinstance(value2, int)
764 res = value1 & value2
766 elif opcode == 171: # equals
769 result = value1 == value2
771 elif opcode == 175: # greaterequals
774 result = value1 >= value2
776 elif opcode == 192: # increment_i
778 assert isinstance(value, int)
779 stack.append(value + 1)
780 elif opcode == 208: # getlocal_0
781 stack.append(registers[0])
782 elif opcode == 209: # getlocal_1
783 stack.append(registers[1])
784 elif opcode == 210: # getlocal_2
785 stack.append(registers[2])
786 elif opcode == 211: # getlocal_3
787 stack.append(registers[3])
788 elif opcode == 212: # setlocal_0
789 registers[0] = stack.pop()
790 elif opcode == 213: # setlocal_1
791 registers[1] = stack.pop()
792 elif opcode == 214: # setlocal_2
793 registers[2] = stack.pop()
794 elif opcode == 215: # setlocal_3
795 registers[3] = stack.pop()
797 raise NotImplementedError(
798 'Unsupported opcode %d' % opcode)
800 avm_class.method_pyfunctions[func_name] = resfunc