swfinterp.py 21 KB

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