swfinterp.py 20 KB

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