swfinterp.py 24 KB

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