1 from __future__ import unicode_literals
8 from .utils import ExtractorError
11 def _extract_tags(content):
13 while pos < len(content):
14 header16 = struct.unpack('<H', content[pos:pos + 2])[0]
16 tag_code = header16 >> 6
17 tag_len = header16 & 0x3f
19 tag_len = struct.unpack('<I', content[pos:pos + 4])[0]
21 assert pos + tag_len <= len(content)
22 yield (tag_code, content[pos:pos + tag_len])
26 class _AVMClass_Object(object):
27 def __init__(self, avm_class):
28 self.avm_class = avm_class
31 return '%s#%x' % (self.avm_class.name, id(self))
34 class _AVMClass(object):
35 def __init__(self, name_idx, name):
36 self.name_idx = name_idx
38 self.method_names = {}
41 self.method_pyfunctions = {}
44 def make_object(self):
45 return _AVMClass_Object(self)
48 def _read_int(reader):
54 b = struct.unpack('<B', buf)[0]
55 res = res | ((b & 0x7f) << shift)
63 res = _read_int(reader)
64 assert res & 0xf0000000 == 0
71 if v & 0x80000000 != 0:
72 v = - ((v ^ 0xffffffff) + 1)
79 first_byte = b'\xff' if (ord(bs[0:1]) >= 0x80) else b'\x00'
80 return struct.unpack('!i', first_byte + bs)
83 def _read_string(reader):
85 resb = reader.read(slen)
86 assert len(resb) == slen
87 return resb.decode('utf-8')
90 def _read_bytes(count, reader):
93 resb = reader.read(count)
94 assert len(resb) == count
98 def _read_byte(reader):
99 resb = _read_bytes(1, reader=reader)
100 res = struct.unpack('<B', resb)[0]
104 class SWFInterpreter(object):
105 def __init__(self, file_contents):
106 if file_contents[1:3] != b'WS':
107 raise ExtractorError(
108 'Not an SWF file; header is %r' % file_contents[:3])
109 if file_contents[:1] == b'C':
110 content = zlib.decompress(file_contents[8:])
112 raise NotImplementedError(
113 'Unsupported compression format %r' %
117 for tag_code, tag in _extract_tags(content)
119 p = code_tag.index(b'\0', 4) + 1
120 code_reader = io.BytesIO(code_tag[p:])
122 # Parse ABC (AVM2 ByteCode)
124 # Define a couple convenience methods
125 u30 = lambda *args: _u30(*args, reader=code_reader)
126 s32 = lambda *args: _s32(*args, reader=code_reader)
127 u32 = lambda *args: _u32(*args, reader=code_reader)
128 read_bytes = lambda *args: _read_bytes(*args, reader=code_reader)
129 read_byte = lambda *args: _read_byte(*args, reader=code_reader)
131 # minor_version + major_version
136 for _c in range(1, int_count):
139 for _c in range(1, uint_count):
142 read_bytes((double_count - 1) * 8)
144 constant_strings = ['']
145 for _c in range(1, string_count):
146 s = _read_string(code_reader)
147 constant_strings.append(s)
148 namespace_count = u30()
149 for _c in range(1, namespace_count):
153 for _c in range(1, ns_set_count):
155 for _c2 in range(count):
157 multiname_count = u30()
166 0x0e: 2, # MultinameA
167 0x1b: 1, # MultinameL
168 0x1c: 1, # MultinameLA
170 self.multinames = ['']
171 for _c in range(1, multiname_count):
173 assert kind in MULTINAME_SIZES, 'Invalid multiname kind %r' % kind
175 u30() # namespace_idx
177 self.multinames.append(constant_strings[name_idx])
179 self.multinames.append('[MULTINAME kind: %d]' % kind)
180 for _c2 in range(MULTINAME_SIZES[kind]):
185 MethodInfo = collections.namedtuple(
187 ['NEED_ARGUMENTS', 'NEED_REST'])
189 for method_id in range(method_count):
192 for _ in range(param_count):
194 u30() # name index (always 0 for youtube)
196 if flags & 0x08 != 0:
199 for c in range(option_count):
202 if flags & 0x80 != 0:
203 # Param names present
204 for _ in range(param_count):
206 mi = MethodInfo(flags & 0x01 != 0, flags & 0x04 != 0)
207 method_infos.append(mi)
210 metadata_count = u30()
211 for _c in range(metadata_count):
214 for _c2 in range(item_count):
218 def parse_traits_info():
219 trait_name_idx = u30()
220 kind_full = read_byte()
221 kind = kind_full & 0x0f
222 attrs = kind_full >> 4
224 if kind in [0x00, 0x06]: # Slot or Const
226 u30() # type_name_idx
230 elif kind in [0x01, 0x02, 0x03]: # Method / Getter / Setter
233 methods[self.multinames[trait_name_idx]] = method_idx
234 elif kind == 0x04: # Class
237 elif kind == 0x05: # Function
240 methods[function_idx] = self.multinames[trait_name_idx]
242 raise ExtractorError('Unsupported trait kind %d' % kind)
244 if attrs & 0x4 != 0: # Metadata present
245 metadata_count = u30()
246 for _c3 in range(metadata_count):
247 u30() # metadata index
254 for class_id in range(class_count):
256 classes.append(_AVMClass(name_idx, self.multinames[name_idx]))
257 u30() # super_name idx
259 if flags & 0x08 != 0: # Protected namespace is present
260 u30() # protected_ns_idx
262 for _c2 in range(intrf_count):
266 for _c2 in range(trait_count):
268 assert len(classes) == class_count
269 self._classes_by_name = dict((c.name, c) for c in classes)
271 for avm_class in classes:
274 for _c2 in range(trait_count):
275 trait_methods = parse_traits_info()
276 avm_class.method_names.update(trait_methods.items())
277 avm_class.method_idxs.update(dict(
279 for name, idx in trait_methods.items()))
283 for _c in range(script_count):
286 for _c2 in range(trait_count):
290 method_body_count = u30()
291 Method = collections.namedtuple('Method', ['code', 'local_count'])
292 for _c in range(method_body_count):
296 u30() # init_scope_depth
297 u30() # max_scope_depth
299 code = read_bytes(code_length)
300 for avm_class in classes:
301 if method_idx in avm_class.method_idxs:
302 m = Method(code, local_count)
303 avm_class.methods[avm_class.method_idxs[method_idx]] = m
304 exception_count = u30()
305 for _c2 in range(exception_count):
312 for _c2 in range(trait_count):
315 assert p + code_reader.tell() == len(code_tag)
317 def extract_class(self, class_name):
319 return self._classes_by_name[class_name]
321 raise ExtractorError('Class %r not found' % class_name)
323 def extract_function(self, avm_class, func_name):
324 if func_name in avm_class.method_pyfunctions:
325 return avm_class.method_pyfunctions[func_name]
326 if func_name in self._classes_by_name:
327 return self._classes_by_name[func_name].make_object()
328 if func_name not in avm_class.methods:
329 raise ExtractorError('Cannot find function %r' % func_name)
330 m = avm_class.methods[func_name]
334 coder = io.BytesIO(m.code)
335 s24 = lambda: _s24(coder)
336 u30 = lambda: _u30(coder)
338 print('Invoking %s.%s(%r)' % (avm_class.name, func_name, tuple(args)))
339 registers = ['(this)'] + list(args) + [None] * m.local_count
342 opcode = _read_byte(coder)
343 print('opcode: %r, stack(%d): %r' % (opcode, len(stack), stack))
344 if opcode == 17: # iftrue
348 coder.seek(coder.tell() + offset)
349 elif opcode == 36: # pushbyte
350 v = _read_byte(coder)
352 elif opcode == 44: # pushstring
354 stack.append(constant_strings[idx])
355 elif opcode == 48: # pushscope
356 # We don't implement the scope register, so we'll just
357 # ignore the popped value
358 new_scope = stack.pop()
359 elif opcode == 70: # callproperty
361 mname = self.multinames[index]
363 args = list(reversed(
364 [stack.pop() for _ in range(arg_count)]))
367 assert len(args) == 1
368 assert isinstance(args[0], compat_str)
369 assert isinstance(obj, compat_str)
373 res = obj.split(args[0])
375 elif mname == 'slice':
376 assert len(args) == 1
377 assert isinstance(args[0], int)
378 assert isinstance(obj, list)
381 elif mname == 'join':
382 assert len(args) == 1
383 assert isinstance(args[0], compat_str)
384 assert isinstance(obj, list)
385 res = args[0].join(obj)
387 elif mname in avm_class.method_pyfunctions:
388 stack.append(avm_class.method_pyfunctions[mname](args))
390 raise NotImplementedError(
391 'Unsupported property %r on %r'
393 elif opcode == 72: # returnvalue
396 elif opcode == 74: # constructproperty
399 args = list(reversed(
400 [stack.pop() for _ in range(arg_count)]))
403 mname = self.multinames[index]
404 construct_method = self.extract_function(
405 obj.avm_class, mname)
406 # We do not actually call the constructor for now;
407 # we just pretend it does nothing
409 elif opcode == 79: # callpropvoid
411 mname = self.multinames[index]
413 args = list(reversed(
414 [stack.pop() for _ in range(arg_count)]))
416 if mname == 'reverse':
417 assert isinstance(obj, list)
420 raise NotImplementedError(
421 'Unsupported (void) property %r on %r'
423 elif opcode == 86: # newarray
426 for i in range(arg_count):
427 arr.append(stack.pop())
430 elif opcode == 93: # findpropstrict
432 mname = self.multinames[index]
433 res = self.extract_function(avm_class, mname)
435 elif opcode == 94: # findproperty
437 mname = self.multinames[index]
438 res = avm_class.variables.get(mname)
440 elif opcode == 96: # getlex
442 mname = self.multinames[index]
443 res = avm_class.variables.get(mname, None)
445 elif opcode == 97: # setproperty
448 idx = self.multinames[index]
451 elif opcode == 98: # getlocal
453 stack.append(registers[index])
454 elif opcode == 99: # setlocal
457 registers[index] = value
458 elif opcode == 102: # getproperty
460 pname = self.multinames[index]
461 if pname == 'length':
463 assert isinstance(obj, list)
464 stack.append(len(obj))
465 else: # Assume attribute access
467 assert isinstance(idx, int)
469 assert isinstance(obj, list)
470 stack.append(obj[idx])
471 elif opcode == 128: # coerce
473 elif opcode == 133: # coerce_s
474 assert isinstance(stack[-1], (type(None), compat_str))
475 elif opcode == 164: # modulo
478 res = value1 % value2
480 elif opcode == 175: # greaterequals
483 result = value1 >= value2
485 elif opcode == 208: # getlocal_0
486 stack.append(registers[0])
487 elif opcode == 209: # getlocal_1
488 stack.append(registers[1])
489 elif opcode == 210: # getlocal_2
490 stack.append(registers[2])
491 elif opcode == 211: # getlocal_3
492 stack.append(registers[3])
493 elif opcode == 214: # setlocal_2
494 registers[2] = stack.pop()
495 elif opcode == 215: # setlocal_3
496 registers[3] = stack.pop()
498 raise NotImplementedError(
499 'Unsupported opcode %d' % opcode)
501 avm_class.method_pyfunctions[func_name] = resfunc