You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

830 lines
31 KiB

  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, static_properties=None):
  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.static_properties = static_properties if static_properties else {}
  59. self.variables = _ScopeDict(self)
  60. self.constants = {}
  61. def make_object(self):
  62. return _AVMClass_Object(self)
  63. def __repr__(self):
  64. return '_AVMClass(%s)' % (self.name)
  65. def register_methods(self, methods):
  66. self.method_names.update(methods.items())
  67. self.method_idxs.update(dict(
  68. (idx, name)
  69. for name, idx in methods.items()))
  70. class _Multiname(object):
  71. def __init__(self, kind):
  72. self.kind = kind
  73. def __repr__(self):
  74. return '[MULTINAME kind: 0x%x]' % self.kind
  75. def _read_int(reader):
  76. res = 0
  77. shift = 0
  78. for _ in range(5):
  79. buf = reader.read(1)
  80. assert len(buf) == 1
  81. b = struct_unpack('<B', buf)[0]
  82. res = res | ((b & 0x7f) << shift)
  83. if b & 0x80 == 0:
  84. break
  85. shift += 7
  86. return res
  87. def _u30(reader):
  88. res = _read_int(reader)
  89. assert res & 0xf0000000 == 0
  90. return res
  91. _u32 = _read_int
  92. def _s32(reader):
  93. v = _read_int(reader)
  94. if v & 0x80000000 != 0:
  95. v = - ((v ^ 0xffffffff) + 1)
  96. return v
  97. def _s24(reader):
  98. bs = reader.read(3)
  99. assert len(bs) == 3
  100. last_byte = b'\xff' if (ord(bs[2:3]) >= 0x80) else b'\x00'
  101. return struct_unpack('<i', bs + last_byte)[0]
  102. def _read_string(reader):
  103. slen = _u30(reader)
  104. resb = reader.read(slen)
  105. assert len(resb) == slen
  106. return resb.decode('utf-8')
  107. def _read_bytes(count, reader):
  108. assert count >= 0
  109. resb = reader.read(count)
  110. assert len(resb) == count
  111. return resb
  112. def _read_byte(reader):
  113. resb = _read_bytes(1, reader=reader)
  114. res = struct_unpack('<B', resb)[0]
  115. return res
  116. StringClass = _AVMClass('(no name idx)', 'String')
  117. ByteArrayClass = _AVMClass('(no name idx)', 'ByteArray')
  118. TimerClass = _AVMClass('(no name idx)', 'Timer')
  119. TimerEventClass = _AVMClass('(no name idx)', 'TimerEvent', {'TIMER': 'timer'})
  120. _builtin_classes = {
  121. StringClass.name: StringClass,
  122. ByteArrayClass.name: ByteArrayClass,
  123. TimerClass.name: TimerClass,
  124. TimerEventClass.name: TimerEventClass,
  125. }
  126. class _Undefined(object):
  127. def __bool__(self):
  128. return False
  129. __nonzero__ = __bool__
  130. def __hash__(self):
  131. return 0
  132. def __str__(self):
  133. return 'undefined'
  134. __repr__ = __str__
  135. undefined = _Undefined()
  136. class SWFInterpreter(object):
  137. def __init__(self, file_contents):
  138. self._patched_functions = {
  139. (TimerClass, 'addEventListener'): lambda params: undefined,
  140. }
  141. code_tag = next(tag
  142. for tag_code, tag in _extract_tags(file_contents)
  143. if tag_code == 82)
  144. p = code_tag.index(b'\0', 4) + 1
  145. code_reader = io.BytesIO(code_tag[p:])
  146. # Parse ABC (AVM2 ByteCode)
  147. # Define a couple convenience methods
  148. u30 = lambda *args: _u30(*args, reader=code_reader)
  149. s32 = lambda *args: _s32(*args, reader=code_reader)
  150. u32 = lambda *args: _u32(*args, reader=code_reader)
  151. read_bytes = lambda *args: _read_bytes(*args, reader=code_reader)
  152. read_byte = lambda *args: _read_byte(*args, reader=code_reader)
  153. # minor_version + major_version
  154. read_bytes(2 + 2)
  155. # Constant pool
  156. int_count = u30()
  157. self.constant_ints = [0]
  158. for _c in range(1, int_count):
  159. self.constant_ints.append(s32())
  160. self.constant_uints = [0]
  161. uint_count = u30()
  162. for _c in range(1, uint_count):
  163. self.constant_uints.append(u32())
  164. double_count = u30()
  165. read_bytes(max(0, (double_count - 1)) * 8)
  166. string_count = u30()
  167. self.constant_strings = ['']
  168. for _c in range(1, string_count):
  169. s = _read_string(code_reader)
  170. self.constant_strings.append(s)
  171. namespace_count = u30()
  172. for _c in range(1, namespace_count):
  173. read_bytes(1) # kind
  174. u30() # name
  175. ns_set_count = u30()
  176. for _c in range(1, ns_set_count):
  177. count = u30()
  178. for _c2 in range(count):
  179. u30()
  180. multiname_count = u30()
  181. MULTINAME_SIZES = {
  182. 0x07: 2, # QName
  183. 0x0d: 2, # QNameA
  184. 0x0f: 1, # RTQName
  185. 0x10: 1, # RTQNameA
  186. 0x11: 0, # RTQNameL
  187. 0x12: 0, # RTQNameLA
  188. 0x09: 2, # Multiname
  189. 0x0e: 2, # MultinameA
  190. 0x1b: 1, # MultinameL
  191. 0x1c: 1, # MultinameLA
  192. }
  193. self.multinames = ['']
  194. for _c in range(1, multiname_count):
  195. kind = u30()
  196. assert kind in MULTINAME_SIZES, 'Invalid multiname kind %r' % kind
  197. if kind == 0x07:
  198. u30() # namespace_idx
  199. name_idx = u30()
  200. self.multinames.append(self.constant_strings[name_idx])
  201. elif kind == 0x09:
  202. name_idx = u30()
  203. u30()
  204. self.multinames.append(self.constant_strings[name_idx])
  205. else:
  206. self.multinames.append(_Multiname(kind))
  207. for _c2 in range(MULTINAME_SIZES[kind]):
  208. u30()
  209. # Methods
  210. method_count = u30()
  211. MethodInfo = collections.namedtuple(
  212. 'MethodInfo',
  213. ['NEED_ARGUMENTS', 'NEED_REST'])
  214. method_infos = []
  215. for method_id in range(method_count):
  216. param_count = u30()
  217. u30() # return type
  218. for _ in range(param_count):
  219. u30() # param type
  220. u30() # name index (always 0 for youtube)
  221. flags = read_byte()
  222. if flags & 0x08 != 0:
  223. # Options present
  224. option_count = u30()
  225. for c in range(option_count):
  226. u30() # val
  227. read_bytes(1) # kind
  228. if flags & 0x80 != 0:
  229. # Param names present
  230. for _ in range(param_count):
  231. u30() # param name
  232. mi = MethodInfo(flags & 0x01 != 0, flags & 0x04 != 0)
  233. method_infos.append(mi)
  234. # Metadata
  235. metadata_count = u30()
  236. for _c in range(metadata_count):
  237. u30() # name
  238. item_count = u30()
  239. for _c2 in range(item_count):
  240. u30() # key
  241. u30() # value
  242. def parse_traits_info():
  243. trait_name_idx = u30()
  244. kind_full = read_byte()
  245. kind = kind_full & 0x0f
  246. attrs = kind_full >> 4
  247. methods = {}
  248. constants = None
  249. if kind == 0x00: # Slot
  250. u30() # Slot id
  251. u30() # type_name_idx
  252. vindex = u30()
  253. if vindex != 0:
  254. read_byte() # vkind
  255. elif kind == 0x06: # Const
  256. u30() # Slot id
  257. u30() # type_name_idx
  258. vindex = u30()
  259. vkind = 'any'
  260. if vindex != 0:
  261. vkind = read_byte()
  262. if vkind == 0x03: # Constant_Int
  263. value = self.constant_ints[vindex]
  264. elif vkind == 0x04: # Constant_UInt
  265. value = self.constant_uints[vindex]
  266. else:
  267. return {}, None # Ignore silently for now
  268. constants = {self.multinames[trait_name_idx]: value}
  269. elif kind in (0x01, 0x02, 0x03): # Method / Getter / Setter
  270. u30() # disp_id
  271. method_idx = u30()
  272. methods[self.multinames[trait_name_idx]] = method_idx
  273. elif kind == 0x04: # Class
  274. u30() # slot_id
  275. u30() # classi
  276. elif kind == 0x05: # Function
  277. u30() # slot_id
  278. function_idx = u30()
  279. methods[function_idx] = self.multinames[trait_name_idx]
  280. else:
  281. raise ExtractorError('Unsupported trait kind %d' % kind)
  282. if attrs & 0x4 != 0: # Metadata present
  283. metadata_count = u30()
  284. for _c3 in range(metadata_count):
  285. u30() # metadata index
  286. return methods, constants
  287. # Classes
  288. class_count = u30()
  289. classes = []
  290. for class_id in range(class_count):
  291. name_idx = u30()
  292. cname = self.multinames[name_idx]
  293. avm_class = _AVMClass(name_idx, cname)
  294. classes.append(avm_class)
  295. u30() # super_name idx
  296. flags = read_byte()
  297. if flags & 0x08 != 0: # Protected namespace is present
  298. u30() # protected_ns_idx
  299. intrf_count = u30()
  300. for _c2 in range(intrf_count):
  301. u30()
  302. u30() # iinit
  303. trait_count = u30()
  304. for _c2 in range(trait_count):
  305. trait_methods, trait_constants = parse_traits_info()
  306. avm_class.register_methods(trait_methods)
  307. if trait_constants:
  308. avm_class.constants.update(trait_constants)
  309. assert len(classes) == class_count
  310. self._classes_by_name = dict((c.name, c) for c in classes)
  311. for avm_class in classes:
  312. avm_class.cinit_idx = u30()
  313. trait_count = u30()
  314. for _c2 in range(trait_count):
  315. trait_methods, trait_constants = parse_traits_info()
  316. avm_class.register_methods(trait_methods)
  317. if trait_constants:
  318. avm_class.constants.update(trait_constants)
  319. # Scripts
  320. script_count = u30()
  321. for _c in range(script_count):
  322. u30() # init
  323. trait_count = u30()
  324. for _c2 in range(trait_count):
  325. parse_traits_info()
  326. # Method bodies
  327. method_body_count = u30()
  328. Method = collections.namedtuple('Method', ['code', 'local_count'])
  329. self._all_methods = []
  330. for _c in range(method_body_count):
  331. method_idx = u30()
  332. u30() # max_stack
  333. local_count = u30()
  334. u30() # init_scope_depth
  335. u30() # max_scope_depth
  336. code_length = u30()
  337. code = read_bytes(code_length)
  338. m = Method(code, local_count)
  339. self._all_methods.append(m)
  340. for avm_class in classes:
  341. if method_idx in avm_class.method_idxs:
  342. avm_class.methods[avm_class.method_idxs[method_idx]] = m
  343. exception_count = u30()
  344. for _c2 in range(exception_count):
  345. u30() # from
  346. u30() # to
  347. u30() # target
  348. u30() # exc_type
  349. u30() # var_name
  350. trait_count = u30()
  351. for _c2 in range(trait_count):
  352. parse_traits_info()
  353. assert p + code_reader.tell() == len(code_tag)
  354. def patch_function(self, avm_class, func_name, f):
  355. self._patched_functions[(avm_class, func_name)] = f
  356. def extract_class(self, class_name, call_cinit=True):
  357. try:
  358. res = self._classes_by_name[class_name]
  359. except KeyError:
  360. raise ExtractorError('Class %r not found' % class_name)
  361. if call_cinit and hasattr(res, 'cinit_idx'):
  362. res.register_methods({'$cinit': res.cinit_idx})
  363. res.methods['$cinit'] = self._all_methods[res.cinit_idx]
  364. cinit = self.extract_function(res, '$cinit')
  365. cinit([])
  366. return res
  367. def extract_function(self, avm_class, func_name):
  368. p = self._patched_functions.get((avm_class, func_name))
  369. if p:
  370. return p
  371. if func_name in avm_class.method_pyfunctions:
  372. return avm_class.method_pyfunctions[func_name]
  373. if func_name in self._classes_by_name:
  374. return self._classes_by_name[func_name].make_object()
  375. if func_name not in avm_class.methods:
  376. raise ExtractorError('Cannot find function %s.%s' % (
  377. avm_class.name, func_name))
  378. m = avm_class.methods[func_name]
  379. def resfunc(args):
  380. # Helper functions
  381. coder = io.BytesIO(m.code)
  382. s24 = lambda: _s24(coder)
  383. u30 = lambda: _u30(coder)
  384. registers = [avm_class.variables] + list(args) + [None] * m.local_count
  385. stack = []
  386. scopes = collections.deque([
  387. self._classes_by_name, avm_class.constants, avm_class.variables])
  388. while True:
  389. opcode = _read_byte(coder)
  390. if opcode == 9: # label
  391. pass # Spec says: "Do nothing."
  392. elif opcode == 16: # jump
  393. offset = s24()
  394. coder.seek(coder.tell() + offset)
  395. elif opcode == 17: # iftrue
  396. offset = s24()
  397. value = stack.pop()
  398. if value:
  399. coder.seek(coder.tell() + offset)
  400. elif opcode == 18: # iffalse
  401. offset = s24()
  402. value = stack.pop()
  403. if not value:
  404. coder.seek(coder.tell() + offset)
  405. elif opcode == 19: # ifeq
  406. offset = s24()
  407. value2 = stack.pop()
  408. value1 = stack.pop()
  409. if value2 == value1:
  410. coder.seek(coder.tell() + offset)
  411. elif opcode == 20: # ifne
  412. offset = s24()
  413. value2 = stack.pop()
  414. value1 = stack.pop()
  415. if value2 != value1:
  416. coder.seek(coder.tell() + offset)
  417. elif opcode == 21: # iflt
  418. offset = s24()
  419. value2 = stack.pop()
  420. value1 = stack.pop()
  421. if value1 < value2:
  422. coder.seek(coder.tell() + offset)
  423. elif opcode == 32: # pushnull
  424. stack.append(None)
  425. elif opcode == 33: # pushundefined
  426. stack.append(undefined)
  427. elif opcode == 36: # pushbyte
  428. v = _read_byte(coder)
  429. stack.append(v)
  430. elif opcode == 37: # pushshort
  431. v = u30()
  432. stack.append(v)
  433. elif opcode == 38: # pushtrue
  434. stack.append(True)
  435. elif opcode == 39: # pushfalse
  436. stack.append(False)
  437. elif opcode == 40: # pushnan
  438. stack.append(float('NaN'))
  439. elif opcode == 42: # dup
  440. value = stack[-1]
  441. stack.append(value)
  442. elif opcode == 44: # pushstring
  443. idx = u30()
  444. stack.append(self.constant_strings[idx])
  445. elif opcode == 48: # pushscope
  446. new_scope = stack.pop()
  447. scopes.append(new_scope)
  448. elif opcode == 66: # construct
  449. arg_count = u30()
  450. args = list(reversed(
  451. [stack.pop() for _ in range(arg_count)]))
  452. obj = stack.pop()
  453. res = obj.avm_class.make_object()
  454. stack.append(res)
  455. elif opcode == 70: # callproperty
  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 obj == StringClass:
  463. if mname == 'String':
  464. assert len(args) == 1
  465. assert isinstance(args[0], (
  466. int, compat_str, _Undefined))
  467. if args[0] == undefined:
  468. res = 'undefined'
  469. else:
  470. res = compat_str(args[0])
  471. stack.append(res)
  472. continue
  473. else:
  474. raise NotImplementedError(
  475. 'Function String.%s is not yet implemented'
  476. % mname)
  477. elif isinstance(obj, _AVMClass_Object):
  478. func = self.extract_function(obj.avm_class, mname)
  479. res = func(args)
  480. stack.append(res)
  481. continue
  482. elif isinstance(obj, _AVMClass):
  483. func = self.extract_function(obj, mname)
  484. res = func(args)
  485. stack.append(res)
  486. continue
  487. elif isinstance(obj, _ScopeDict):
  488. if mname in obj.avm_class.method_names:
  489. func = self.extract_function(obj.avm_class, mname)
  490. res = func(args)
  491. else:
  492. res = obj[mname]
  493. stack.append(res)
  494. continue
  495. elif isinstance(obj, compat_str):
  496. if mname == 'split':
  497. assert len(args) == 1
  498. assert isinstance(args[0], compat_str)
  499. if args[0] == '':
  500. res = list(obj)
  501. else:
  502. res = obj.split(args[0])
  503. stack.append(res)
  504. continue
  505. elif mname == 'charCodeAt':
  506. assert len(args) <= 1
  507. idx = 0 if len(args) == 0 else args[0]
  508. assert isinstance(idx, int)
  509. res = ord(obj[idx])
  510. stack.append(res)
  511. continue
  512. elif isinstance(obj, list):
  513. if mname == 'slice':
  514. assert len(args) == 1
  515. assert isinstance(args[0], int)
  516. res = obj[args[0]:]
  517. stack.append(res)
  518. continue
  519. elif mname == 'join':
  520. assert len(args) == 1
  521. assert isinstance(args[0], compat_str)
  522. res = args[0].join(obj)
  523. stack.append(res)
  524. continue
  525. raise NotImplementedError(
  526. 'Unsupported property %r on %r'
  527. % (mname, obj))
  528. elif opcode == 71: # returnvoid
  529. res = undefined
  530. return res
  531. elif opcode == 72: # returnvalue
  532. res = stack.pop()
  533. return res
  534. elif opcode == 73: # constructsuper
  535. # Not yet implemented, just hope it works without it
  536. arg_count = u30()
  537. args = list(reversed(
  538. [stack.pop() for _ in range(arg_count)]))
  539. obj = stack.pop()
  540. elif opcode == 74: # constructproperty
  541. index = u30()
  542. arg_count = u30()
  543. args = list(reversed(
  544. [stack.pop() for _ in range(arg_count)]))
  545. obj = stack.pop()
  546. mname = self.multinames[index]
  547. assert isinstance(obj, _AVMClass)
  548. # We do not actually call the constructor for now;
  549. # we just pretend it does nothing
  550. stack.append(obj.make_object())
  551. elif opcode == 79: # callpropvoid
  552. index = u30()
  553. mname = self.multinames[index]
  554. arg_count = u30()
  555. args = list(reversed(
  556. [stack.pop() for _ in range(arg_count)]))
  557. obj = stack.pop()
  558. if isinstance(obj, _AVMClass_Object):
  559. func = self.extract_function(obj.avm_class, mname)
  560. res = func(args)
  561. assert res is undefined
  562. continue
  563. if isinstance(obj, _ScopeDict):
  564. assert mname in obj.avm_class.method_names
  565. func = self.extract_function(obj.avm_class, mname)
  566. res = func(args)
  567. assert res is undefined
  568. continue
  569. if mname == 'reverse':
  570. assert isinstance(obj, list)
  571. obj.reverse()
  572. else:
  573. raise NotImplementedError(
  574. 'Unsupported (void) property %r on %r'
  575. % (mname, obj))
  576. elif opcode == 86: # newarray
  577. arg_count = u30()
  578. arr = []
  579. for i in range(arg_count):
  580. arr.append(stack.pop())
  581. arr = arr[::-1]
  582. stack.append(arr)
  583. elif opcode == 93: # findpropstrict
  584. index = u30()
  585. mname = self.multinames[index]
  586. for s in reversed(scopes):
  587. if mname in s:
  588. res = s
  589. break
  590. else:
  591. res = scopes[0]
  592. if mname not in res and mname in _builtin_classes:
  593. stack.append(_builtin_classes[mname])
  594. else:
  595. stack.append(res[mname])
  596. elif opcode == 94: # findproperty
  597. index = u30()
  598. mname = self.multinames[index]
  599. for s in reversed(scopes):
  600. if mname in s:
  601. res = s
  602. break
  603. else:
  604. res = avm_class.variables
  605. stack.append(res)
  606. elif opcode == 96: # getlex
  607. index = u30()
  608. mname = self.multinames[index]
  609. for s in reversed(scopes):
  610. if mname in s:
  611. scope = s
  612. break
  613. else:
  614. scope = avm_class.variables
  615. if mname in scope:
  616. res = scope[mname]
  617. elif mname in _builtin_classes:
  618. res = _builtin_classes[mname]
  619. else:
  620. # Assume unitialized
  621. # TODO warn here
  622. res = undefined
  623. stack.append(res)
  624. elif opcode == 97: # setproperty
  625. index = u30()
  626. value = stack.pop()
  627. idx = self.multinames[index]
  628. if isinstance(idx, _Multiname):
  629. idx = stack.pop()
  630. obj = stack.pop()
  631. obj[idx] = value
  632. elif opcode == 98: # getlocal
  633. index = u30()
  634. stack.append(registers[index])
  635. elif opcode == 99: # setlocal
  636. index = u30()
  637. value = stack.pop()
  638. registers[index] = value
  639. elif opcode == 102: # getproperty
  640. index = u30()
  641. pname = self.multinames[index]
  642. if pname == 'length':
  643. obj = stack.pop()
  644. assert isinstance(obj, (compat_str, list))
  645. stack.append(len(obj))
  646. elif isinstance(pname, compat_str): # Member access
  647. obj = stack.pop()
  648. if isinstance(obj, _AVMClass):
  649. res = obj.static_properties[pname]
  650. stack.append(res)
  651. continue
  652. assert isinstance(obj, (dict, _ScopeDict)),\
  653. 'Accessing member %r on %r' % (pname, obj)
  654. res = obj.get(pname, undefined)
  655. stack.append(res)
  656. else: # Assume attribute access
  657. idx = stack.pop()
  658. assert isinstance(idx, int)
  659. obj = stack.pop()
  660. assert isinstance(obj, list)
  661. stack.append(obj[idx])
  662. elif opcode == 104: # initproperty
  663. index = u30()
  664. value = stack.pop()
  665. idx = self.multinames[index]
  666. if isinstance(idx, _Multiname):
  667. idx = stack.pop()
  668. obj = stack.pop()
  669. obj[idx] = value
  670. elif opcode == 115: # convert_
  671. value = stack.pop()
  672. intvalue = int(value)
  673. stack.append(intvalue)
  674. elif opcode == 128: # coerce
  675. u30()
  676. elif opcode == 130: # coerce_a
  677. value = stack.pop()
  678. # um, yes, it's any value
  679. stack.append(value)
  680. elif opcode == 133: # coerce_s
  681. assert isinstance(stack[-1], (type(None), compat_str))
  682. elif opcode == 147: # decrement
  683. value = stack.pop()
  684. assert isinstance(value, int)
  685. stack.append(value - 1)
  686. elif opcode == 149: # typeof
  687. value = stack.pop()
  688. return {
  689. _Undefined: 'undefined',
  690. compat_str: 'String',
  691. int: 'Number',
  692. float: 'Number',
  693. }[type(value)]
  694. elif opcode == 160: # add
  695. value2 = stack.pop()
  696. value1 = stack.pop()
  697. res = value1 + value2
  698. stack.append(res)
  699. elif opcode == 161: # subtract
  700. value2 = stack.pop()
  701. value1 = stack.pop()
  702. res = value1 - value2
  703. stack.append(res)
  704. elif opcode == 162: # multiply
  705. value2 = stack.pop()
  706. value1 = stack.pop()
  707. res = value1 * value2
  708. stack.append(res)
  709. elif opcode == 164: # modulo
  710. value2 = stack.pop()
  711. value1 = stack.pop()
  712. res = value1 % value2
  713. stack.append(res)
  714. elif opcode == 168: # bitand
  715. value2 = stack.pop()
  716. value1 = stack.pop()
  717. assert isinstance(value1, int)
  718. assert isinstance(value2, int)
  719. res = value1 & value2
  720. stack.append(res)
  721. elif opcode == 171: # equals
  722. value2 = stack.pop()
  723. value1 = stack.pop()
  724. result = value1 == value2
  725. stack.append(result)
  726. elif opcode == 175: # greaterequals
  727. value2 = stack.pop()
  728. value1 = stack.pop()
  729. result = value1 >= value2
  730. stack.append(result)
  731. elif opcode == 192: # increment_i
  732. value = stack.pop()
  733. assert isinstance(value, int)
  734. stack.append(value + 1)
  735. elif opcode == 208: # getlocal_0
  736. stack.append(registers[0])
  737. elif opcode == 209: # getlocal_1
  738. stack.append(registers[1])
  739. elif opcode == 210: # getlocal_2
  740. stack.append(registers[2])
  741. elif opcode == 211: # getlocal_3
  742. stack.append(registers[3])
  743. elif opcode == 212: # setlocal_0
  744. registers[0] = stack.pop()
  745. elif opcode == 213: # setlocal_1
  746. registers[1] = stack.pop()
  747. elif opcode == 214: # setlocal_2
  748. registers[2] = stack.pop()
  749. elif opcode == 215: # setlocal_3
  750. registers[3] = stack.pop()
  751. else:
  752. raise NotImplementedError(
  753. 'Unsupported opcode %d' % opcode)
  754. avm_class.method_pyfunctions[func_name] = resfunc
  755. return resfunc