swfinterp.py 23 KB

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