From 814d580a15c5f7478f173f621809155a369e07fa Mon Sep 17 00:00:00 2001
From: Damien George <damien.p.george@gmail.com>
Date: Tue, 11 Dec 2018 00:52:33 +1100
Subject: [PATCH] tools/mpy-tool.py: Fix calc of opcode size for opcodes with
 map caching.

Following an equivalent fix to py/bc.c.  The reason the incorrect values
for the opcode constants were not previously causing a bug is because they
were never being used: these opcodes always have qstr arguments so the part
of the code that was comparing them would never be reached.

Thanks to @malinah for finding the problem and providing the initial patch.
---
 tools/mpy-tool.py | 21 +++++++++++----------
 1 file changed, 11 insertions(+), 10 deletions(-)

diff --git a/tools/mpy-tool.py b/tools/mpy-tool.py
index c667bd0e6..5b63e33c4 100755
--- a/tools/mpy-tool.py
+++ b/tools/mpy-tool.py
@@ -73,9 +73,9 @@ MP_BC_MAKE_CLOSURE = 0x62
 MP_BC_MAKE_CLOSURE_DEFARGS = 0x63
 MP_BC_RAISE_VARARGS = 0x5c
 # extra byte if caching enabled:
-MP_BC_LOAD_NAME = 0x1c
-MP_BC_LOAD_GLOBAL = 0x1d
-MP_BC_LOAD_ATTR = 0x1e
+MP_BC_LOAD_NAME = 0x1b
+MP_BC_LOAD_GLOBAL = 0x1c
+MP_BC_LOAD_ATTR = 0x1d
 MP_BC_STORE_ATTR = 0x26
 
 def make_opcode_format():
@@ -166,18 +166,18 @@ def mp_opcode_format(bytecode, ip, opcode_format=make_opcode_format()):
     ip_start = ip
     f = (opcode_format[opcode >> 2] >> (2 * (opcode & 3))) & 3
     if f == MP_OPCODE_QSTR:
+        if config.MICROPY_OPT_CACHE_MAP_LOOKUP_IN_BYTECODE:
+            if (opcode == MP_BC_LOAD_NAME
+                or opcode == MP_BC_LOAD_GLOBAL
+                or opcode == MP_BC_LOAD_ATTR
+                or opcode == MP_BC_STORE_ATTR):
+                ip += 1
         ip += 3
     else:
         extra_byte = (
             opcode == MP_BC_RAISE_VARARGS
             or opcode == MP_BC_MAKE_CLOSURE
             or opcode == MP_BC_MAKE_CLOSURE_DEFARGS
-            or config.MICROPY_OPT_CACHE_MAP_LOOKUP_IN_BYTECODE and (
-                opcode == MP_BC_LOAD_NAME
-                or opcode == MP_BC_LOAD_GLOBAL
-                or opcode == MP_BC_LOAD_ATTR
-                or opcode == MP_BC_STORE_ATTR
-            )
         )
         ip += 1
         if f == MP_OPCODE_VAR_UINT:
@@ -278,7 +278,8 @@ class RawCode:
             f, sz = mp_opcode_format(self.bytecode, ip)
             if f == 1:
                 qst = self._unpack_qstr(ip + 1).qstr_id
-                print('   ', '0x%02x,' % self.bytecode[ip], qst, '& 0xff,', qst, '>> 8,')
+                extra = '' if sz == 3 else ' 0x%02x,' % self.bytecode[ip + 3]
+                print('   ', '0x%02x,' % self.bytecode[ip], qst, '& 0xff,', qst, '>> 8,', extra)
             else:
                 print('   ', ''.join('0x%02x, ' % self.bytecode[ip + i] for i in range(sz)))
             ip += sz
-- 
GitLab