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)
75 def make_object(self):
76 return _AVMClass_Object(self)
79 return '_AVMClass(%s)' % (self.name)
81 def register_methods(self, methods):
82 self.method_names.update(methods.items())
83 self.method_idxs.update(dict(
85 for name, idx in methods.items()))
88 class _Multiname(object):
89 def __init__(self, kind):
93 return '[MULTINAME kind: 0x%x]' % self.kind
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):
153 self._patched_functions = {}
155 for tag_code, tag in _extract_tags(file_contents)
157 p = code_tag.index(b'\0', 4) + 1
158 code_reader = io.BytesIO(code_tag[p:])
160 # Parse ABC (AVM2 ByteCode)
162 # Define a couple convenience methods
163 u30 = lambda *args: _u30(*args, reader=code_reader)
164 s32 = lambda *args: _s32(*args, reader=code_reader)
165 u32 = lambda *args: _u32(*args, reader=code_reader)
166 read_bytes = lambda *args: _read_bytes(*args, reader=code_reader)
167 read_byte = lambda *args: _read_byte(*args, reader=code_reader)
169 # minor_version + major_version
174 for _c in range(1, int_count):
177 for _c in range(1, uint_count):
180 read_bytes(max(0, (double_count - 1)) * 8)
182 self.constant_strings = ['']
183 for _c in range(1, string_count):
184 s = _read_string(code_reader)
185 self.constant_strings.append(s)
186 namespace_count = u30()
187 for _c in range(1, namespace_count):
191 for _c in range(1, ns_set_count):
193 for _c2 in range(count):
195 multiname_count = u30()
204 0x0e: 2, # MultinameA
205 0x1b: 1, # MultinameL
206 0x1c: 1, # MultinameLA
208 self.multinames = ['']
209 for _c in range(1, multiname_count):
211 assert kind in MULTINAME_SIZES, 'Invalid multiname kind %r' % kind
213 u30() # namespace_idx
215 self.multinames.append(self.constant_strings[name_idx])
219 self.multinames.append(self.constant_strings[name_idx])
221 self.multinames.append(_Multiname(kind))
222 for _c2 in range(MULTINAME_SIZES[kind]):
227 MethodInfo = collections.namedtuple(
229 ['NEED_ARGUMENTS', 'NEED_REST'])
231 for method_id in range(method_count):
234 for _ in range(param_count):
236 u30() # name index (always 0 for youtube)
238 if flags & 0x08 != 0:
241 for c in range(option_count):
244 if flags & 0x80 != 0:
245 # Param names present
246 for _ in range(param_count):
248 mi = MethodInfo(flags & 0x01 != 0, flags & 0x04 != 0)
249 method_infos.append(mi)
252 metadata_count = u30()
253 for _c in range(metadata_count):
256 for _c2 in range(item_count):
260 def parse_traits_info():
261 trait_name_idx = u30()
262 kind_full = read_byte()
263 kind = kind_full & 0x0f
264 attrs = kind_full >> 4
266 if kind in [0x00, 0x06]: # Slot or Const
268 u30() # type_name_idx
272 elif kind in [0x01, 0x02, 0x03]: # Method / Getter / Setter
275 methods[self.multinames[trait_name_idx]] = method_idx
276 elif kind == 0x04: # Class
279 elif kind == 0x05: # Function
282 methods[function_idx] = self.multinames[trait_name_idx]
284 raise ExtractorError('Unsupported trait kind %d' % kind)
286 if attrs & 0x4 != 0: # Metadata present
287 metadata_count = u30()
288 for _c3 in range(metadata_count):
289 u30() # metadata index
296 for class_id in range(class_count):
299 cname = self.multinames[name_idx]
300 avm_class = _AVMClass(name_idx, cname)
301 classes.append(avm_class)
303 u30() # super_name idx
305 if flags & 0x08 != 0: # Protected namespace is present
306 u30() # protected_ns_idx
308 for _c2 in range(intrf_count):
312 for _c2 in range(trait_count):
313 trait_methods = parse_traits_info()
314 avm_class.register_methods(trait_methods)
316 assert len(classes) == class_count
317 self._classes_by_name = dict((c.name, c) for c in classes)
319 for avm_class in classes:
322 for _c2 in range(trait_count):
323 trait_methods = parse_traits_info()
324 avm_class.register_methods(trait_methods)
328 for _c in range(script_count):
331 for _c2 in range(trait_count):
335 method_body_count = u30()
336 Method = collections.namedtuple('Method', ['code', 'local_count'])
337 for _c in range(method_body_count):
341 u30() # init_scope_depth
342 u30() # max_scope_depth
344 code = read_bytes(code_length)
345 for avm_class in classes:
346 if method_idx in avm_class.method_idxs:
347 m = Method(code, local_count)
348 avm_class.methods[avm_class.method_idxs[method_idx]] = m
349 exception_count = u30()
350 for _c2 in range(exception_count):
357 for _c2 in range(trait_count):
360 assert p + code_reader.tell() == len(code_tag)
362 def patch_function(self, avm_class, func_name, f):
363 self._patched_functions[(avm_class, func_name)] = f
365 def extract_class(self, class_name):
367 return self._classes_by_name[class_name]
369 raise ExtractorError('Class %r not found' % class_name)
371 def extract_function(self, avm_class, func_name):
372 p = self._patched_functions.get((avm_class, func_name))
375 if func_name in avm_class.method_pyfunctions:
376 return avm_class.method_pyfunctions[func_name]
377 if func_name in self._classes_by_name:
378 return self._classes_by_name[func_name].make_object()
379 if func_name not in avm_class.methods:
380 raise ExtractorError('Cannot find function %s.%s' % (
381 avm_class.name, func_name))
382 m = avm_class.methods[func_name]
386 coder = io.BytesIO(m.code)
387 s24 = lambda: _s24(coder)
388 u30 = lambda: _u30(coder)
390 registers = [avm_class.variables] + list(args) + [None] * m.local_count
392 scopes = collections.deque([
393 self._classes_by_name, avm_class.variables])
395 opcode = _read_byte(coder)
396 if opcode == 16: # jump
398 coder.seek(coder.tell() + offset)
399 elif opcode == 17: # iftrue
403 coder.seek(coder.tell() + offset)
404 elif opcode == 18: # iffalse
408 coder.seek(coder.tell() + offset)
409 elif opcode == 19: # ifeq
414 coder.seek(coder.tell() + offset)
415 elif opcode == 20: # ifne
420 coder.seek(coder.tell() + offset)
421 elif opcode == 32: # pushnull
423 elif opcode == 36: # pushbyte
424 v = _read_byte(coder)
426 elif opcode == 42: # dup
429 elif opcode == 44: # pushstring
431 stack.append(self.constant_strings[idx])
432 elif opcode == 48: # pushscope
433 new_scope = stack.pop()
434 scopes.append(new_scope)
435 elif opcode == 66: # construct
437 args = list(reversed(
438 [stack.pop() for _ in range(arg_count)]))
440 res = obj.avm_class.make_object()
442 elif opcode == 70: # callproperty
444 mname = self.multinames[index]
446 args = list(reversed(
447 [stack.pop() for _ in range(arg_count)]))
450 if isinstance(obj, _AVMClass_Object):
451 func = self.extract_function(obj.avm_class, mname)
455 elif isinstance(obj, _ScopeDict):
456 if mname in obj.avm_class.method_names:
457 func = self.extract_function(obj.avm_class, mname)
463 elif isinstance(obj, compat_str):
465 assert len(args) == 1
466 assert isinstance(args[0], compat_str)
470 res = obj.split(args[0])
473 elif isinstance(obj, list):
475 assert len(args) == 1
476 assert isinstance(args[0], int)
480 elif mname == 'join':
481 assert len(args) == 1
482 assert isinstance(args[0], compat_str)
483 res = args[0].join(obj)
486 raise NotImplementedError(
487 'Unsupported property %r on %r'
489 elif opcode == 72: # returnvalue
492 elif opcode == 74: # constructproperty
495 args = list(reversed(
496 [stack.pop() for _ in range(arg_count)]))
499 mname = self.multinames[index]
500 assert isinstance(obj, _AVMClass)
502 # We do not actually call the constructor for now;
503 # we just pretend it does nothing
504 stack.append(obj.make_object())
505 elif opcode == 79: # callpropvoid
507 mname = self.multinames[index]
509 args = list(reversed(
510 [stack.pop() for _ in range(arg_count)]))
512 if mname == 'reverse':
513 assert isinstance(obj, list)
516 raise NotImplementedError(
517 'Unsupported (void) property %r on %r'
519 elif opcode == 86: # newarray
522 for i in range(arg_count):
523 arr.append(stack.pop())
526 elif opcode == 93: # findpropstrict
528 mname = self.multinames[index]
529 for s in reversed(scopes):
535 stack.append(res[mname])
536 elif opcode == 94: # findproperty
538 mname = self.multinames[index]
539 for s in reversed(scopes):
544 res = avm_class.variables
546 elif opcode == 96: # getlex
548 mname = self.multinames[index]
549 for s in reversed(scopes):
554 scope = avm_class.variables
555 # I cannot find where static variables are initialized
556 # so let's just return None
557 res = scope.get(mname)
559 elif opcode == 97: # setproperty
562 idx = self.multinames[index]
563 if isinstance(idx, _Multiname):
567 elif opcode == 98: # getlocal
569 stack.append(registers[index])
570 elif opcode == 99: # setlocal
573 registers[index] = value
574 elif opcode == 102: # getproperty
576 pname = self.multinames[index]
577 if pname == 'length':
579 assert isinstance(obj, list)
580 stack.append(len(obj))
581 elif isinstance(pname, compat_str): # Member access
583 assert isinstance(obj, (dict, _ScopeDict)), \
584 'Accessing member %r on %r' % (pname, obj)
585 stack.append(obj[pname])
586 else: # Assume attribute access
588 assert isinstance(idx, int)
590 assert isinstance(obj, list)
591 stack.append(obj[idx])
592 elif opcode == 115: # convert_
594 intvalue = int(value)
595 stack.append(intvalue)
596 elif opcode == 128: # coerce
598 elif opcode == 133: # coerce_s
599 assert isinstance(stack[-1], (type(None), compat_str))
600 elif opcode == 160: # add
603 res = value1 + value2
605 elif opcode == 161: # subtract
608 res = value1 - value2
610 elif opcode == 164: # modulo
613 res = value1 % value2
615 elif opcode == 175: # greaterequals
618 result = value1 >= value2
620 elif opcode == 208: # getlocal_0
621 stack.append(registers[0])
622 elif opcode == 209: # getlocal_1
623 stack.append(registers[1])
624 elif opcode == 210: # getlocal_2
625 stack.append(registers[2])
626 elif opcode == 211: # getlocal_3
627 stack.append(registers[3])
628 elif opcode == 212: # setlocal_0
629 registers[0] = stack.pop()
630 elif opcode == 213: # setlocal_1
631 registers[1] = stack.pop()
632 elif opcode == 214: # setlocal_2
633 registers[2] = stack.pop()
634 elif opcode == 215: # setlocal_3
635 registers[3] = stack.pop()
637 raise NotImplementedError(
638 'Unsupported opcode %d' % opcode)
640 avm_class.method_pyfunctions[func_name] = resfunc