You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

503 lines
18 KiB

  1. from __future__ import unicode_literals
  2. import collections
  3. import io
  4. import struct
  5. import zlib
  6. from .utils import ExtractorError
  7. def _extract_tags(content):
  8. pos = 0
  9. while pos < len(content):
  10. header16 = struct.unpack('<H', content[pos:pos + 2])[0]
  11. pos += 2
  12. tag_code = header16 >> 6
  13. tag_len = header16 & 0x3f
  14. if tag_len == 0x3f:
  15. tag_len = struct.unpack('<I', content[pos:pos + 4])[0]
  16. pos += 4
  17. assert pos + tag_len <= len(content)
  18. yield (tag_code, content[pos:pos + tag_len])
  19. pos += tag_len
  20. class _AVMClass_Object(object):
  21. def __init__(self, avm_class):
  22. self.avm_class = avm_class
  23. def __repr__(self):
  24. return '%s#%x' % (self.avm_class.name, id(self))
  25. class _AVMClass(object):
  26. def __init__(self, name_idx, name):
  27. self.name_idx = name_idx
  28. self.name = name
  29. self.method_names = {}
  30. self.method_idxs = {}
  31. self.methods = {}
  32. self.method_pyfunctions = {}
  33. self.variables = {}
  34. def make_object(self):
  35. return _AVMClass_Object(self)
  36. def _read_int(reader):
  37. res = 0
  38. shift = 0
  39. for _ in range(5):
  40. buf = reader.read(1)
  41. assert len(buf) == 1
  42. b = struct.unpack('<B', buf)[0]
  43. res = res | ((b & 0x7f) << shift)
  44. if b & 0x80 == 0:
  45. break
  46. shift += 7
  47. return res
  48. def _u30(reader):
  49. res = _read_int(reader)
  50. assert res & 0xf0000000 == 0
  51. return res
  52. u32 = _read_int
  53. def _s32(reader):
  54. v = _read_int(reader)
  55. if v & 0x80000000 != 0:
  56. v = - ((v ^ 0xffffffff) + 1)
  57. return v
  58. def _s24(reader):
  59. bs = reader.read(3)
  60. assert len(bs) == 3
  61. first_byte = b'\xff' if (ord(bs[0:1]) >= 0x80) else b'\x00'
  62. return struct.unpack('!i', first_byte + bs)
  63. def _read_string(reader):
  64. slen = _u30(reader)
  65. resb = reader.read(slen)
  66. assert len(resb) == slen
  67. return resb.decode('utf-8')
  68. def _read_bytes(count, reader):
  69. if reader is None:
  70. reader = code_reader
  71. resb = reader.read(count)
  72. assert len(resb) == count
  73. return resb
  74. def _read_byte(reader):
  75. resb = _read_bytes(1, reader=reader)
  76. res = struct.unpack('<B', resb)[0]
  77. return res
  78. class SWFInterpreter(object):
  79. def __init__(self, file_contents):
  80. if file_contents[1:3] != b'WS':
  81. raise ExtractorError(
  82. 'Not an SWF file; header is %r' % file_contents[:3])
  83. if file_contents[:1] == b'C':
  84. content = zlib.decompress(file_contents[8:])
  85. else:
  86. raise NotImplementedError(
  87. 'Unsupported compression format %r' %
  88. file_contents[:1])
  89. code_tag = next(tag
  90. for tag_code, tag in _extract_tags(content)
  91. if tag_code == 82)
  92. p = code_tag.index(b'\0', 4) + 1
  93. code_reader = io.BytesIO(code_tag[p:])
  94. # Parse ABC (AVM2 ByteCode)
  95. # Define a couple convenience methods
  96. u30 = lambda *args: _u30(*args, reader=code_reader)
  97. s32 = lambda *args: _s32(*args, reader=code_reader)
  98. u32 = lambda *args: _u32(*args, reader=code_reader)
  99. read_bytes = lambda *args: _read_bytes(*args, reader=code_reader)
  100. read_byte = lambda *args: _read_byte(*args, reader=code_reader)
  101. # minor_version + major_version
  102. read_bytes(2 + 2)
  103. # Constant pool
  104. int_count = u30()
  105. for _c in range(1, int_count):
  106. s32()
  107. uint_count = u30()
  108. for _c in range(1, uint_count):
  109. u32()
  110. double_count = u30()
  111. read_bytes((double_count - 1) * 8)
  112. string_count = u30()
  113. constant_strings = ['']
  114. for _c in range(1, string_count):
  115. s = _read_string(code_reader)
  116. constant_strings.append(s)
  117. namespace_count = u30()
  118. for _c in range(1, namespace_count):
  119. read_bytes(1) # kind
  120. u30() # name
  121. ns_set_count = u30()
  122. for _c in range(1, ns_set_count):
  123. count = u30()
  124. for _c2 in range(count):
  125. u30()
  126. multiname_count = u30()
  127. MULTINAME_SIZES = {
  128. 0x07: 2, # QName
  129. 0x0d: 2, # QNameA
  130. 0x0f: 1, # RTQName
  131. 0x10: 1, # RTQNameA
  132. 0x11: 0, # RTQNameL
  133. 0x12: 0, # RTQNameLA
  134. 0x09: 2, # Multiname
  135. 0x0e: 2, # MultinameA
  136. 0x1b: 1, # MultinameL
  137. 0x1c: 1, # MultinameLA
  138. }
  139. self.multinames = ['']
  140. for _c in range(1, multiname_count):
  141. kind = u30()
  142. assert kind in MULTINAME_SIZES, 'Invalid multiname kind %r' % kind
  143. if kind == 0x07:
  144. u30() # namespace_idx
  145. name_idx = u30()
  146. self.multinames.append(constant_strings[name_idx])
  147. else:
  148. self.multinames.append('[MULTINAME kind: %d]' % kind)
  149. for _c2 in range(MULTINAME_SIZES[kind]):
  150. u30()
  151. # Methods
  152. method_count = u30()
  153. MethodInfo = collections.namedtuple(
  154. 'MethodInfo',
  155. ['NEED_ARGUMENTS', 'NEED_REST'])
  156. method_infos = []
  157. for method_id in range(method_count):
  158. param_count = u30()
  159. u30() # return type
  160. for _ in range(param_count):
  161. u30() # param type
  162. u30() # name index (always 0 for youtube)
  163. flags = read_byte()
  164. if flags & 0x08 != 0:
  165. # Options present
  166. option_count = u30()
  167. for c in range(option_count):
  168. u30() # val
  169. read_bytes(1) # kind
  170. if flags & 0x80 != 0:
  171. # Param names present
  172. for _ in range(param_count):
  173. u30() # param name
  174. mi = MethodInfo(flags & 0x01 != 0, flags & 0x04 != 0)
  175. method_infos.append(mi)
  176. # Metadata
  177. metadata_count = u30()
  178. for _c in range(metadata_count):
  179. u30() # name
  180. item_count = u30()
  181. for _c2 in range(item_count):
  182. u30() # key
  183. u30() # value
  184. def parse_traits_info():
  185. trait_name_idx = u30()
  186. kind_full = read_byte()
  187. kind = kind_full & 0x0f
  188. attrs = kind_full >> 4
  189. methods = {}
  190. if kind in [0x00, 0x06]: # Slot or Const
  191. u30() # Slot id
  192. u30() # type_name_idx
  193. vindex = u30()
  194. if vindex != 0:
  195. read_byte() # vkind
  196. elif kind in [0x01, 0x02, 0x03]: # Method / Getter / Setter
  197. u30() # disp_id
  198. method_idx = u30()
  199. methods[self.multinames[trait_name_idx]] = method_idx
  200. elif kind == 0x04: # Class
  201. u30() # slot_id
  202. u30() # classi
  203. elif kind == 0x05: # Function
  204. u30() # slot_id
  205. function_idx = u30()
  206. methods[function_idx] = self.multinames[trait_name_idx]
  207. else:
  208. raise ExtractorError('Unsupported trait kind %d' % kind)
  209. if attrs & 0x4 != 0: # Metadata present
  210. metadata_count = u30()
  211. for _c3 in range(metadata_count):
  212. u30() # metadata index
  213. return methods
  214. # Classes
  215. class_count = u30()
  216. classes = []
  217. for class_id in range(class_count):
  218. name_idx = u30()
  219. classes.append(_AVMClass(name_idx, self.multinames[name_idx]))
  220. u30() # super_name idx
  221. flags = read_byte()
  222. if flags & 0x08 != 0: # Protected namespace is present
  223. u30() # protected_ns_idx
  224. intrf_count = u30()
  225. for _c2 in range(intrf_count):
  226. u30()
  227. u30() # iinit
  228. trait_count = u30()
  229. for _c2 in range(trait_count):
  230. parse_traits_info()
  231. assert len(classes) == class_count
  232. self._classes_by_name = dict((c.name, c) for c in classes)
  233. for avm_class in classes:
  234. u30() # cinit
  235. trait_count = u30()
  236. for _c2 in range(trait_count):
  237. trait_methods = parse_traits_info()
  238. avm_class.method_names.update(trait_methods.items())
  239. avm_class.method_idxs.update(dict(
  240. (idx, name)
  241. for name, idx in trait_methods.items()))
  242. # Scripts
  243. script_count = u30()
  244. for _c in range(script_count):
  245. u30() # init
  246. trait_count = u30()
  247. for _c2 in range(trait_count):
  248. parse_traits_info()
  249. # Method bodies
  250. method_body_count = u30()
  251. Method = collections.namedtuple('Method', ['code', 'local_count'])
  252. for _c in range(method_body_count):
  253. method_idx = u30()
  254. u30() # max_stack
  255. local_count = u30()
  256. u30() # init_scope_depth
  257. u30() # max_scope_depth
  258. code_length = u30()
  259. code = read_bytes(code_length)
  260. for avm_class in classes:
  261. if method_idx in avm_class.method_idxs:
  262. m = Method(code, local_count)
  263. avm_class.methods[avm_class.method_idxs[method_idx]] = m
  264. exception_count = u30()
  265. for _c2 in range(exception_count):
  266. u30() # from
  267. u30() # to
  268. u30() # target
  269. u30() # exc_type
  270. u30() # var_name
  271. trait_count = u30()
  272. for _c2 in range(trait_count):
  273. parse_traits_info()
  274. assert p + code_reader.tell() == len(code_tag)
  275. def extract_class(self, class_name):
  276. try:
  277. return self._classes_by_name[class_name]
  278. except KeyError:
  279. raise ExtractorError('Class %r not found' % class_name)
  280. def extract_function(self, avm_class, func_name):
  281. if func_name in avm_class.method_pyfunctions:
  282. return avm_class.method_pyfunctions[func_name]
  283. if func_name in self._classes_by_name:
  284. return self._classes_by_name[func_name].make_object()
  285. if func_name not in avm_class.methods:
  286. raise ExtractorError('Cannot find function %r' % func_name)
  287. m = avm_class.methods[func_name]
  288. def resfunc(args):
  289. # Helper functions
  290. coder = io.BytesIO(m.code)
  291. s24 = lambda: _s24(coder)
  292. u30 = lambda: _u30(coder)
  293. print('Invoking %s.%s(%r)' % (avm_class.name, func_name, tuple(args)))
  294. registers = ['(this)'] + list(args) + [None] * m.local_count
  295. stack = []
  296. while True:
  297. opcode = _read_byte(coder)
  298. print('opcode: %r, stack(%d): %r' % (opcode, len(stack), stack))
  299. if opcode == 17: # iftrue
  300. offset = s24()
  301. value = stack.pop()
  302. if value:
  303. coder.seek(coder.tell() + offset)
  304. elif opcode == 36: # pushbyte
  305. v = _read_byte(coder)
  306. stack.append(v)
  307. elif opcode == 44: # pushstring
  308. idx = u30()
  309. stack.append(constant_strings[idx])
  310. elif opcode == 48: # pushscope
  311. # We don't implement the scope register, so we'll just
  312. # ignore the popped value
  313. new_scope = stack.pop()
  314. elif opcode == 70: # callproperty
  315. index = u30()
  316. mname = self.multinames[index]
  317. arg_count = u30()
  318. args = list(reversed(
  319. [stack.pop() for _ in range(arg_count)]))
  320. obj = stack.pop()
  321. if mname == 'split':
  322. assert len(args) == 1
  323. assert isinstance(args[0], compat_str)
  324. assert isinstance(obj, compat_str)
  325. if args[0] == '':
  326. res = list(obj)
  327. else:
  328. res = obj.split(args[0])
  329. stack.append(res)
  330. elif mname == 'slice':
  331. assert len(args) == 1
  332. assert isinstance(args[0], int)
  333. assert isinstance(obj, list)
  334. res = obj[args[0]:]
  335. stack.append(res)
  336. elif mname == 'join':
  337. assert len(args) == 1
  338. assert isinstance(args[0], compat_str)
  339. assert isinstance(obj, list)
  340. res = args[0].join(obj)
  341. stack.append(res)
  342. elif mname in avm_class.method_pyfunctions:
  343. stack.append(avm_class.method_pyfunctions[mname](args))
  344. else:
  345. raise NotImplementedError(
  346. 'Unsupported property %r on %r'
  347. % (mname, obj))
  348. elif opcode == 72: # returnvalue
  349. res = stack.pop()
  350. return res
  351. elif opcode == 74: # constructproperty
  352. index = u30()
  353. arg_count = u30()
  354. args = list(reversed(
  355. [stack.pop() for _ in range(arg_count)]))
  356. obj = stack.pop()
  357. mname = self.multinames[index]
  358. construct_method = self.extract_function(
  359. obj.avm_class, mname)
  360. # We do not actually call the constructor for now;
  361. # we just pretend it does nothing
  362. stack.append(obj)
  363. elif opcode == 79: # callpropvoid
  364. index = u30()
  365. mname = self.multinames[index]
  366. arg_count = u30()
  367. args = list(reversed(
  368. [stack.pop() for _ in range(arg_count)]))
  369. obj = stack.pop()
  370. if mname == 'reverse':
  371. assert isinstance(obj, list)
  372. obj.reverse()
  373. else:
  374. raise NotImplementedError(
  375. 'Unsupported (void) property %r on %r'
  376. % (mname, obj))
  377. elif opcode == 86: # newarray
  378. arg_count = u30()
  379. arr = []
  380. for i in range(arg_count):
  381. arr.append(stack.pop())
  382. arr = arr[::-1]
  383. stack.append(arr)
  384. elif opcode == 93: # findpropstrict
  385. index = u30()
  386. mname = self.multinames[index]
  387. res = self.extract_function(avm_class, mname)
  388. stack.append(res)
  389. elif opcode == 94: # findproperty
  390. index = u30()
  391. mname = self.multinames[index]
  392. res = avm_class.variables.get(mname)
  393. stack.append(res)
  394. elif opcode == 96: # getlex
  395. index = u30()
  396. mname = self.multinames[index]
  397. res = avm_class.variables.get(mname, None)
  398. stack.append(res)
  399. elif opcode == 97: # setproperty
  400. index = u30()
  401. value = stack.pop()
  402. idx = self.multinames[index]
  403. obj = stack.pop()
  404. obj[idx] = value
  405. elif opcode == 98: # getlocal
  406. index = u30()
  407. stack.append(registers[index])
  408. elif opcode == 99: # setlocal
  409. index = u30()
  410. value = stack.pop()
  411. registers[index] = value
  412. elif opcode == 102: # getproperty
  413. index = u30()
  414. pname = self.multinames[index]
  415. if pname == 'length':
  416. obj = stack.pop()
  417. assert isinstance(obj, list)
  418. stack.append(len(obj))
  419. else: # Assume attribute access
  420. idx = stack.pop()
  421. assert isinstance(idx, int)
  422. obj = stack.pop()
  423. assert isinstance(obj, list)
  424. stack.append(obj[idx])
  425. elif opcode == 128: # coerce
  426. u30()
  427. elif opcode == 133: # coerce_s
  428. assert isinstance(stack[-1], (type(None), compat_str))
  429. elif opcode == 164: # modulo
  430. value2 = stack.pop()
  431. value1 = stack.pop()
  432. res = value1 % value2
  433. stack.append(res)
  434. elif opcode == 175: # greaterequals
  435. value2 = stack.pop()
  436. value1 = stack.pop()
  437. result = value1 >= value2
  438. stack.append(result)
  439. elif opcode == 208: # getlocal_0
  440. stack.append(registers[0])
  441. elif opcode == 209: # getlocal_1
  442. stack.append(registers[1])
  443. elif opcode == 210: # getlocal_2
  444. stack.append(registers[2])
  445. elif opcode == 211: # getlocal_3
  446. stack.append(registers[3])
  447. elif opcode == 214: # setlocal_2
  448. registers[2] = stack.pop()
  449. elif opcode == 215: # setlocal_3
  450. registers[3] = stack.pop()
  451. else:
  452. raise NotImplementedError(
  453. 'Unsupported opcode %d' % opcode)
  454. avm_class.method_pyfunctions[func_name] = resfunc
  455. return resfunc