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:
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 for _c in range(method_body_count):
380 u30() # init_scope_depth
381 u30() # max_scope_depth
383 code = read_bytes(code_length)
384 for avm_class in classes:
385 if method_idx in avm_class.method_idxs:
386 m = Method(code, local_count)
387 avm_class.methods[avm_class.method_idxs[method_idx]] = m
388 exception_count = u30()
389 for _c2 in range(exception_count):
396 for _c2 in range(trait_count):
399 assert p + code_reader.tell() == len(code_tag)
401 def patch_function(self, avm_class, func_name, f):
402 self._patched_functions[(avm_class, func_name)] = f
404 def extract_class(self, class_name):
406 return self._classes_by_name[class_name]
408 raise ExtractorError('Class %r not found' % class_name)
410 def extract_function(self, avm_class, func_name):
411 p = self._patched_functions.get((avm_class, func_name))
414 if func_name in avm_class.method_pyfunctions:
415 return avm_class.method_pyfunctions[func_name]
416 if func_name in self._classes_by_name:
417 return self._classes_by_name[func_name].make_object()
418 if func_name not in avm_class.methods:
419 raise ExtractorError('Cannot find function %s.%s' % (
420 avm_class.name, func_name))
421 m = avm_class.methods[func_name]
425 coder = io.BytesIO(m.code)
426 s24 = lambda: _s24(coder)
427 u30 = lambda: _u30(coder)
429 registers = [avm_class.variables] + list(args) + [None] * m.local_count
431 scopes = collections.deque([
432 self._classes_by_name, avm_class.variables])
434 opcode = _read_byte(coder)
435 if opcode == 9: # label
436 pass # Spec says: "Do nothing."
437 elif opcode == 16: # jump
439 coder.seek(coder.tell() + offset)
440 elif opcode == 17: # iftrue
444 coder.seek(coder.tell() + offset)
445 elif opcode == 18: # iffalse
449 coder.seek(coder.tell() + offset)
450 elif opcode == 19: # ifeq
455 coder.seek(coder.tell() + offset)
456 elif opcode == 20: # ifne
461 coder.seek(coder.tell() + offset)
462 elif opcode == 21: # iflt
467 coder.seek(coder.tell() + offset)
468 elif opcode == 32: # pushnull
470 elif opcode == 33: # pushundefined
471 stack.append(undefined)
472 elif opcode == 36: # pushbyte
473 v = _read_byte(coder)
475 elif opcode == 37: # pushshort
478 elif opcode == 38: # pushtrue
480 elif opcode == 39: # pushfalse
482 elif opcode == 40: # pushnan
483 stack.append(float('NaN'))
484 elif opcode == 42: # dup
487 elif opcode == 44: # pushstring
489 stack.append(self.constant_strings[idx])
490 elif opcode == 48: # pushscope
491 new_scope = stack.pop()
492 scopes.append(new_scope)
493 elif opcode == 66: # construct
495 args = list(reversed(
496 [stack.pop() for _ in range(arg_count)]))
498 res = obj.avm_class.make_object()
500 elif opcode == 70: # callproperty
502 mname = self.multinames[index]
504 args = list(reversed(
505 [stack.pop() for _ in range(arg_count)]))
508 if obj == StringClass:
509 if mname == 'String':
510 assert len(args) == 1
511 assert isinstance(args[0], (
512 int, compat_str, _Undefined))
513 if args[0] == undefined:
516 res = compat_str(args[0])
520 raise NotImplementedError(
521 'Function String.%s is not yet implemented'
523 elif isinstance(obj, _AVMClass_Object):
524 func = self.extract_function(obj.avm_class, mname)
528 elif isinstance(obj, _AVMClass):
529 func = self.extract_function(obj, mname)
533 elif isinstance(obj, _ScopeDict):
534 if mname in obj.avm_class.method_names:
535 func = self.extract_function(obj.avm_class, mname)
541 elif isinstance(obj, compat_str):
543 assert len(args) == 1
544 assert isinstance(args[0], compat_str)
548 res = obj.split(args[0])
551 elif mname == 'charCodeAt':
552 assert len(args) <= 1
553 idx = 0 if len(args) == 0 else args[0]
554 assert isinstance(idx, int)
558 elif isinstance(obj, list):
560 assert len(args) == 1
561 assert isinstance(args[0], int)
565 elif mname == 'join':
566 assert len(args) == 1
567 assert isinstance(args[0], compat_str)
568 res = args[0].join(obj)
571 raise NotImplementedError(
572 'Unsupported property %r on %r'
574 elif opcode == 71: # returnvoid
577 elif opcode == 72: # returnvalue
580 elif opcode == 74: # constructproperty
583 args = list(reversed(
584 [stack.pop() for _ in range(arg_count)]))
587 mname = self.multinames[index]
588 assert isinstance(obj, _AVMClass)
590 # We do not actually call the constructor for now;
591 # we just pretend it does nothing
592 stack.append(obj.make_object())
593 elif opcode == 79: # callpropvoid
595 mname = self.multinames[index]
597 args = list(reversed(
598 [stack.pop() for _ in range(arg_count)]))
600 if isinstance(obj, _AVMClass_Object):
601 func = self.extract_function(obj.avm_class, mname)
603 assert res is undefined
605 if isinstance(obj, _ScopeDict):
606 assert mname in obj.avm_class.method_names
607 func = self.extract_function(obj.avm_class, mname)
609 assert res is undefined
611 if mname == 'reverse':
612 assert isinstance(obj, list)
615 raise NotImplementedError(
616 'Unsupported (void) property %r on %r'
618 elif opcode == 86: # newarray
621 for i in range(arg_count):
622 arr.append(stack.pop())
625 elif opcode == 93: # findpropstrict
627 mname = self.multinames[index]
628 for s in reversed(scopes):
634 if mname not in res and mname in _builtin_classes:
635 stack.append(_builtin_classes[mname])
637 stack.append(res[mname])
638 elif opcode == 94: # findproperty
640 mname = self.multinames[index]
641 for s in reversed(scopes):
646 res = avm_class.variables
648 elif opcode == 96: # getlex
650 mname = self.multinames[index]
651 for s in reversed(scopes):
656 scope = avm_class.variables
661 res = avm_class.constants[mname]
663 elif opcode == 97: # setproperty
666 idx = self.multinames[index]
667 if isinstance(idx, _Multiname):
671 elif opcode == 98: # getlocal
673 stack.append(registers[index])
674 elif opcode == 99: # setlocal
677 registers[index] = value
678 elif opcode == 102: # getproperty
680 pname = self.multinames[index]
681 if pname == 'length':
683 assert isinstance(obj, (compat_str, list))
684 stack.append(len(obj))
685 elif isinstance(pname, compat_str): # Member access
687 assert isinstance(obj, (dict, _ScopeDict)), \
688 'Accessing member %r on %r' % (pname, obj)
689 res = obj.get(pname, undefined)
691 else: # Assume attribute access
693 assert isinstance(idx, int)
695 assert isinstance(obj, list)
696 stack.append(obj[idx])
697 elif opcode == 115: # convert_
699 intvalue = int(value)
700 stack.append(intvalue)
701 elif opcode == 128: # coerce
703 elif opcode == 130: # coerce_a
705 # um, yes, it's any value
707 elif opcode == 133: # coerce_s
708 assert isinstance(stack[-1], (type(None), compat_str))
709 elif opcode == 147: # decrement
711 assert isinstance(value, int)
712 stack.append(value - 1)
713 elif opcode == 149: # typeof
716 _Undefined: 'undefined',
717 compat_str: 'String',
721 elif opcode == 160: # add
724 res = value1 + value2
726 elif opcode == 161: # subtract
729 res = value1 - value2
731 elif opcode == 162: # multiply
734 res = value1 * value2
736 elif opcode == 164: # modulo
739 res = value1 % value2
741 elif opcode == 168: # bitand
744 assert isinstance(value1, int)
745 assert isinstance(value2, int)
746 res = value1 & value2
748 elif opcode == 171: # equals
751 result = value1 == value2
753 elif opcode == 175: # greaterequals
756 result = value1 >= value2
758 elif opcode == 192: # increment_i
760 assert isinstance(value, int)
761 stack.append(value + 1)
762 elif opcode == 208: # getlocal_0
763 stack.append(registers[0])
764 elif opcode == 209: # getlocal_1
765 stack.append(registers[1])
766 elif opcode == 210: # getlocal_2
767 stack.append(registers[2])
768 elif opcode == 211: # getlocal_3
769 stack.append(registers[3])
770 elif opcode == 212: # setlocal_0
771 registers[0] = stack.pop()
772 elif opcode == 213: # setlocal_1
773 registers[1] = stack.pop()
774 elif opcode == 214: # setlocal_2
775 registers[2] = stack.pop()
776 elif opcode == 215: # setlocal_3
777 registers[3] = stack.pop()
779 raise NotImplementedError(
780 'Unsupported opcode %d' % opcode)
782 avm_class.method_pyfunctions[func_name] = resfunc