swfinterp.py 19 KB

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