swfinterp.py 21 KB

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