swfinterp.py 31 KB

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