blob: d497896209cd37c4225c6705aee2efab1a3508ed [file] [log] [blame]
Damien George0699c6b2016-01-31 21:45:22 +00001#!/usr/bin/env python3
2#
3# This file is part of the MicroPython project, http://micropython.org/
4#
5# The MIT License (MIT)
6#
Damien Georgefaf3d3e2019-06-04 22:13:32 +10007# Copyright (c) 2016-2019 Damien P. George
Damien George0699c6b2016-01-31 21:45:22 +00008#
9# Permission is hereby granted, free of charge, to any person obtaining a copy
10# of this software and associated documentation files (the "Software"), to deal
11# in the Software without restriction, including without limitation the rights
12# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
13# copies of the Software, and to permit persons to whom the Software is
14# furnished to do so, subject to the following conditions:
15#
16# The above copyright notice and this permission notice shall be included in
17# all copies or substantial portions of the Software.
18#
19# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
20# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
21# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
22# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
23# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
24# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
25# THE SOFTWARE.
26
Damien Georgec3beb162016-04-15 11:56:10 +010027# Python 2/3 compatibility code
28from __future__ import print_function
29import platform
30if platform.python_version_tuple()[0] == '2':
31 str_cons = lambda val, enc=None: val
32 bytes_cons = lambda val, enc=None: bytearray(val)
33 is_str_type = lambda o: type(o) is str
34 is_bytes_type = lambda o: type(o) is bytearray
35 is_int_type = lambda o: type(o) is int or type(o) is long
36else:
37 str_cons = str
38 bytes_cons = bytes
39 is_str_type = lambda o: type(o) is str
40 is_bytes_type = lambda o: type(o) is bytes
41 is_int_type = lambda o: type(o) is int
42# end compatibility code
43
Damien George0699c6b2016-01-31 21:45:22 +000044import sys
Damien George72ae3c72016-08-10 13:26:11 +100045import struct
Damien George0699c6b2016-01-31 21:45:22 +000046from collections import namedtuple
47
Paul Sokolovsky473e85e2017-05-01 00:01:30 +030048sys.path.append(sys.path[0] + '/../py')
Damien George0699c6b2016-01-31 21:45:22 +000049import makeqstrdata as qstrutil
50
51class FreezeError(Exception):
52 def __init__(self, rawcode, msg):
53 self.rawcode = rawcode
54 self.msg = msg
55
56 def __str__(self):
57 return 'error while freezing %s: %s' % (self.rawcode.source_file, self.msg)
58
59class Config:
Damien George9a5f92e2019-03-07 17:13:24 +110060 MPY_VERSION = 4
Damien George0699c6b2016-01-31 21:45:22 +000061 MICROPY_LONGINT_IMPL_NONE = 0
62 MICROPY_LONGINT_IMPL_LONGLONG = 1
63 MICROPY_LONGINT_IMPL_MPZ = 2
64config = Config()
65
Damien George4f0931b2019-03-01 14:33:03 +110066class QStrType:
67 def __init__(self, str):
68 self.str = str
69 self.qstr_esc = qstrutil.qstr_escape(self.str)
70 self.qstr_id = 'MP_QSTR_' + self.qstr_esc
71
72# Initialise global list of qstrs with static qstrs
73global_qstrs = [None] # MP_QSTR_NULL should never be referenced
74for n in qstrutil.static_qstr_list:
75 global_qstrs.append(QStrType(n))
76
Damien George5996eeb2019-02-25 23:15:51 +110077class QStrWindow:
Damien George74ed0682019-04-08 15:20:56 +100078 def __init__(self, size):
Damien George5996eeb2019-02-25 23:15:51 +110079 self.window = []
Damien George74ed0682019-04-08 15:20:56 +100080 self.size = size
Damien George5996eeb2019-02-25 23:15:51 +110081
82 def push(self, val):
83 self.window = [val] + self.window[:self.size - 1]
84
85 def access(self, idx):
86 val = self.window[idx]
87 self.window = [val] + self.window[:idx] + self.window[idx + 1:]
88 return val
89
Damien Georgeea3c80a2019-02-21 15:18:59 +110090MP_CODE_BYTECODE = 2
91MP_CODE_NATIVE_PY = 3
92MP_CODE_NATIVE_VIPER = 4
93MP_CODE_NATIVE_ASM = 5
94
95MP_NATIVE_ARCH_NONE = 0
96MP_NATIVE_ARCH_X86 = 1
97MP_NATIVE_ARCH_X64 = 2
98MP_NATIVE_ARCH_ARMV6 = 3
99MP_NATIVE_ARCH_ARMV6M = 4
100MP_NATIVE_ARCH_ARMV7M = 5
101MP_NATIVE_ARCH_ARMV7EM = 6
102MP_NATIVE_ARCH_ARMV7EMSP = 7
103MP_NATIVE_ARCH_ARMV7EMDP = 8
104MP_NATIVE_ARCH_XTENSA = 9
105
Damien George0699c6b2016-01-31 21:45:22 +0000106MP_OPCODE_BYTE = 0
107MP_OPCODE_QSTR = 1
108MP_OPCODE_VAR_UINT = 2
109MP_OPCODE_OFFSET = 3
110
111# extra bytes:
Damien George5889cf52019-09-02 20:24:01 +1000112MP_BC_UNWIND_JUMP = 0x40
113MP_BC_MAKE_CLOSURE = 0x20
114MP_BC_MAKE_CLOSURE_DEFARGS = 0x21
115MP_BC_RAISE_VARARGS = 0x60
Damien George0699c6b2016-01-31 21:45:22 +0000116# extra byte if caching enabled:
Damien George5889cf52019-09-02 20:24:01 +1000117MP_BC_LOAD_NAME = 0x11
118MP_BC_LOAD_GLOBAL = 0x12
119MP_BC_LOAD_ATTR = 0x13
120MP_BC_STORE_ATTR = 0x18
Damien George0699c6b2016-01-31 21:45:22 +0000121
122def make_opcode_format():
123 def OC4(a, b, c, d):
124 return a | (b << 2) | (c << 4) | (d << 6)
125 U = 0
126 B = 0
127 Q = 1
128 V = 2
129 O = 3
Damien Georgec3beb162016-04-15 11:56:10 +0100130 return bytes_cons((
Damien George0699c6b2016-01-31 21:45:22 +0000131 # this table is taken verbatim from py/bc.c
132 OC4(U, U, U, U), # 0x00-0x03
133 OC4(U, U, U, U), # 0x04-0x07
134 OC4(U, U, U, U), # 0x08-0x0b
135 OC4(U, U, U, U), # 0x0c-0x0f
136 OC4(B, B, B, U), # 0x10-0x13
137 OC4(V, U, Q, V), # 0x14-0x17
Damien Georgedd11af22017-04-19 09:45:59 +1000138 OC4(B, V, V, Q), # 0x18-0x1b
Damien George0699c6b2016-01-31 21:45:22 +0000139 OC4(Q, Q, Q, Q), # 0x1c-0x1f
140 OC4(B, B, V, V), # 0x20-0x23
141 OC4(Q, Q, Q, B), # 0x24-0x27
142 OC4(V, V, Q, Q), # 0x28-0x2b
143 OC4(U, U, U, U), # 0x2c-0x2f
144 OC4(B, B, B, B), # 0x30-0x33
145 OC4(B, O, O, O), # 0x34-0x37
146 OC4(O, O, U, U), # 0x38-0x3b
147 OC4(U, O, B, O), # 0x3c-0x3f
148 OC4(O, B, B, O), # 0x40-0x43
Damien George5a2599d2019-02-15 12:18:59 +1100149 OC4(O, U, O, B), # 0x44-0x47
Damien George0699c6b2016-01-31 21:45:22 +0000150 OC4(U, U, U, U), # 0x48-0x4b
151 OC4(U, U, U, U), # 0x4c-0x4f
Damien George7df92912016-09-23 12:48:57 +1000152 OC4(V, V, U, V), # 0x50-0x53
153 OC4(B, U, V, V), # 0x54-0x57
Damien George0699c6b2016-01-31 21:45:22 +0000154 OC4(V, V, V, B), # 0x58-0x5b
155 OC4(B, B, B, U), # 0x5c-0x5f
156 OC4(V, V, V, V), # 0x60-0x63
157 OC4(V, V, V, V), # 0x64-0x67
158 OC4(Q, Q, B, U), # 0x68-0x6b
159 OC4(U, U, U, U), # 0x6c-0x6f
160
161 OC4(B, B, B, B), # 0x70-0x73
162 OC4(B, B, B, B), # 0x74-0x77
163 OC4(B, B, B, B), # 0x78-0x7b
164 OC4(B, B, B, B), # 0x7c-0x7f
165 OC4(B, B, B, B), # 0x80-0x83
166 OC4(B, B, B, B), # 0x84-0x87
167 OC4(B, B, B, B), # 0x88-0x8b
168 OC4(B, B, B, B), # 0x8c-0x8f
169 OC4(B, B, B, B), # 0x90-0x93
170 OC4(B, B, B, B), # 0x94-0x97
171 OC4(B, B, B, B), # 0x98-0x9b
172 OC4(B, B, B, B), # 0x9c-0x9f
173 OC4(B, B, B, B), # 0xa0-0xa3
174 OC4(B, B, B, B), # 0xa4-0xa7
175 OC4(B, B, B, B), # 0xa8-0xab
176 OC4(B, B, B, B), # 0xac-0xaf
177
178 OC4(B, B, B, B), # 0xb0-0xb3
179 OC4(B, B, B, B), # 0xb4-0xb7
180 OC4(B, B, B, B), # 0xb8-0xbb
181 OC4(B, B, B, B), # 0xbc-0xbf
182
183 OC4(B, B, B, B), # 0xc0-0xc3
184 OC4(B, B, B, B), # 0xc4-0xc7
185 OC4(B, B, B, B), # 0xc8-0xcb
186 OC4(B, B, B, B), # 0xcc-0xcf
187
188 OC4(B, B, B, B), # 0xd0-0xd3
Damien George933eab42017-10-10 10:37:38 +1100189 OC4(U, U, U, B), # 0xd4-0xd7
Damien George0699c6b2016-01-31 21:45:22 +0000190 OC4(B, B, B, B), # 0xd8-0xdb
191 OC4(B, B, B, B), # 0xdc-0xdf
192
193 OC4(B, B, B, B), # 0xe0-0xe3
194 OC4(B, B, B, B), # 0xe4-0xe7
195 OC4(B, B, B, B), # 0xe8-0xeb
196 OC4(B, B, B, B), # 0xec-0xef
197
198 OC4(B, B, B, B), # 0xf0-0xf3
199 OC4(B, B, B, B), # 0xf4-0xf7
Damien George933eab42017-10-10 10:37:38 +1100200 OC4(U, U, U, U), # 0xf8-0xfb
Damien George0699c6b2016-01-31 21:45:22 +0000201 OC4(U, U, U, U), # 0xfc-0xff
202 ))
203
204# this function mirrors that in py/bc.c
Damien George992a6e12019-03-01 14:03:10 +1100205def mp_opcode_format(bytecode, ip, count_var_uint, opcode_format=make_opcode_format()):
Damien George0699c6b2016-01-31 21:45:22 +0000206 opcode = bytecode[ip]
207 ip_start = ip
208 f = (opcode_format[opcode >> 2] >> (2 * (opcode & 3))) & 3
209 if f == MP_OPCODE_QSTR:
Damien George814d5802018-12-11 00:52:33 +1100210 if config.MICROPY_OPT_CACHE_MAP_LOOKUP_IN_BYTECODE:
211 if (opcode == MP_BC_LOAD_NAME
212 or opcode == MP_BC_LOAD_GLOBAL
213 or opcode == MP_BC_LOAD_ATTR
214 or opcode == MP_BC_STORE_ATTR):
215 ip += 1
Damien George0699c6b2016-01-31 21:45:22 +0000216 ip += 3
217 else:
218 extra_byte = (
Damien Georgeb29fae02019-09-02 13:30:16 +1000219 opcode == MP_BC_UNWIND_JUMP
220 or opcode == MP_BC_RAISE_VARARGS
Damien George0699c6b2016-01-31 21:45:22 +0000221 or opcode == MP_BC_MAKE_CLOSURE
222 or opcode == MP_BC_MAKE_CLOSURE_DEFARGS
Damien George0699c6b2016-01-31 21:45:22 +0000223 )
224 ip += 1
225 if f == MP_OPCODE_VAR_UINT:
Damien George992a6e12019-03-01 14:03:10 +1100226 if count_var_uint:
227 while bytecode[ip] & 0x80 != 0:
228 ip += 1
Damien George0699c6b2016-01-31 21:45:22 +0000229 ip += 1
Damien George0699c6b2016-01-31 21:45:22 +0000230 elif f == MP_OPCODE_OFFSET:
231 ip += 2
232 ip += extra_byte
233 return f, ip - ip_start
234
235def decode_uint(bytecode, ip):
236 unum = 0
237 while True:
238 val = bytecode[ip]
239 ip += 1
240 unum = (unum << 7) | (val & 0x7f)
241 if not (val & 0x80):
242 break
243 return ip, unum
244
Damien Georgeea3c80a2019-02-21 15:18:59 +1100245def extract_prelude(bytecode, ip):
Damien George0699c6b2016-01-31 21:45:22 +0000246 ip, n_state = decode_uint(bytecode, ip)
247 ip, n_exc_stack = decode_uint(bytecode, ip)
248 scope_flags = bytecode[ip]; ip += 1
249 n_pos_args = bytecode[ip]; ip += 1
250 n_kwonly_args = bytecode[ip]; ip += 1
251 n_def_pos_args = bytecode[ip]; ip += 1
252 ip2, code_info_size = decode_uint(bytecode, ip)
253 ip += code_info_size
254 while bytecode[ip] != 0xff:
255 ip += 1
256 ip += 1
257 # ip now points to first opcode
258 # ip2 points to simple_name qstr
259 return ip, ip2, (n_state, n_exc_stack, scope_flags, n_pos_args, n_kwonly_args, n_def_pos_args, code_info_size)
260
Damien Georgeea3c80a2019-02-21 15:18:59 +1100261class MPFunTable:
262 pass
263
Damien George643d2a02019-04-08 11:21:18 +1000264class RawCode(object):
Damien George02fd83b2016-05-03 12:24:39 +0100265 # a set of all escaped names, to make sure they are unique
266 escaped_names = set()
267
Damien Georgeea3c80a2019-02-21 15:18:59 +1100268 # convert code kind number to string
269 code_kind_str = {
270 MP_CODE_BYTECODE: 'MP_CODE_BYTECODE',
271 MP_CODE_NATIVE_PY: 'MP_CODE_NATIVE_PY',
272 MP_CODE_NATIVE_VIPER: 'MP_CODE_NATIVE_VIPER',
273 MP_CODE_NATIVE_ASM: 'MP_CODE_NATIVE_ASM',
274 }
275
276 def __init__(self, code_kind, bytecode, prelude_offset, qstrs, objs, raw_codes):
Damien George0699c6b2016-01-31 21:45:22 +0000277 # set core variables
Damien Georgeea3c80a2019-02-21 15:18:59 +1100278 self.code_kind = code_kind
Damien George0699c6b2016-01-31 21:45:22 +0000279 self.bytecode = bytecode
Damien Georgeea3c80a2019-02-21 15:18:59 +1100280 self.prelude_offset = prelude_offset
Damien George0699c6b2016-01-31 21:45:22 +0000281 self.qstrs = qstrs
282 self.objs = objs
283 self.raw_codes = raw_codes
284
Damien Georgeea3c80a2019-02-21 15:18:59 +1100285 if self.prelude_offset is None:
286 # no prelude, assign a dummy simple_name
287 self.prelude_offset = 0
288 self.simple_name = global_qstrs[1]
289 else:
290 # extract prelude
291 self.ip, self.ip2, self.prelude = extract_prelude(self.bytecode, self.prelude_offset)
292 self.simple_name = self._unpack_qstr(self.ip2)
293 self.source_file = self._unpack_qstr(self.ip2 + 2)
Damien George0699c6b2016-01-31 21:45:22 +0000294
295 def _unpack_qstr(self, ip):
296 qst = self.bytecode[ip] | self.bytecode[ip + 1] << 8
297 return global_qstrs[qst]
298
299 def dump(self):
300 # dump children first
301 for rc in self.raw_codes:
stijne4ab4042017-08-16 10:37:00 +0200302 rc.freeze('')
Damien George0699c6b2016-01-31 21:45:22 +0000303 # TODO
304
Damien Georgeea3c80a2019-02-21 15:18:59 +1100305 def freeze_children(self, parent_name):
Damien George0699c6b2016-01-31 21:45:22 +0000306 self.escaped_name = parent_name + self.simple_name.qstr_esc
307
Damien George02fd83b2016-05-03 12:24:39 +0100308 # make sure the escaped name is unique
309 i = 2
310 while self.escaped_name in RawCode.escaped_names:
311 self.escaped_name = parent_name + self.simple_name.qstr_esc + str(i)
312 i += 1
313 RawCode.escaped_names.add(self.escaped_name)
314
Damien George0699c6b2016-01-31 21:45:22 +0000315 # emit children first
316 for rc in self.raw_codes:
317 rc.freeze(self.escaped_name + '_')
318
Damien Georgeea3c80a2019-02-21 15:18:59 +1100319 def freeze_constants(self):
Damien George0699c6b2016-01-31 21:45:22 +0000320 # generate constant objects
321 for i, obj in enumerate(self.objs):
322 obj_name = 'const_obj_%s_%u' % (self.escaped_name, i)
Damien Georgeea3c80a2019-02-21 15:18:59 +1100323 if obj is MPFunTable:
324 pass
325 elif obj is Ellipsis:
Damien George9ba3de62017-11-15 12:46:08 +1100326 print('#define %s mp_const_ellipsis_obj' % obj_name)
327 elif is_str_type(obj) or is_bytes_type(obj):
Damien Georgeb6bdf182016-09-02 15:10:45 +1000328 if is_str_type(obj):
329 obj = bytes_cons(obj, 'utf8')
330 obj_type = 'mp_type_str'
331 else:
332 obj_type = 'mp_type_bytes'
333 print('STATIC const mp_obj_str_t %s = {{&%s}, %u, %u, (const byte*)"%s"};'
334 % (obj_name, obj_type, qstrutil.compute_hash(obj, config.MICROPY_QSTR_BYTES_IN_HASH),
335 len(obj), ''.join(('\\x%02x' % b) for b in obj)))
Damien Georgec3beb162016-04-15 11:56:10 +0100336 elif is_int_type(obj):
Damien George0699c6b2016-01-31 21:45:22 +0000337 if config.MICROPY_LONGINT_IMPL == config.MICROPY_LONGINT_IMPL_NONE:
338 # TODO check if we can actually fit this long-int into a small-int
339 raise FreezeError(self, 'target does not support long int')
340 elif config.MICROPY_LONGINT_IMPL == config.MICROPY_LONGINT_IMPL_LONGLONG:
341 # TODO
342 raise FreezeError(self, 'freezing int to long-long is not implemented')
343 elif config.MICROPY_LONGINT_IMPL == config.MICROPY_LONGINT_IMPL_MPZ:
344 neg = 0
345 if obj < 0:
346 obj = -obj
347 neg = 1
348 bits_per_dig = config.MPZ_DIG_SIZE
349 digs = []
350 z = obj
351 while z:
352 digs.append(z & ((1 << bits_per_dig) - 1))
353 z >>= bits_per_dig
354 ndigs = len(digs)
355 digs = ','.join(('%#x' % d) for d in digs)
356 print('STATIC const mp_obj_int_t %s = {{&mp_type_int}, '
Damien George44fc92e2018-07-09 13:43:34 +1000357 '{.neg=%u, .fixed_dig=1, .alloc=%u, .len=%u, .dig=(uint%u_t*)(const uint%u_t[]){%s}}};'
358 % (obj_name, neg, ndigs, ndigs, bits_per_dig, bits_per_dig, digs))
Damien George0699c6b2016-01-31 21:45:22 +0000359 elif type(obj) is float:
Damien George72ae3c72016-08-10 13:26:11 +1000360 print('#if MICROPY_OBJ_REPR == MICROPY_OBJ_REPR_A || MICROPY_OBJ_REPR == MICROPY_OBJ_REPR_B')
Damien George0699c6b2016-01-31 21:45:22 +0000361 print('STATIC const mp_obj_float_t %s = {{&mp_type_float}, %.16g};'
362 % (obj_name, obj))
Damien George72ae3c72016-08-10 13:26:11 +1000363 print('#endif')
Damien Georgec51c8832016-09-03 00:19:02 +1000364 elif type(obj) is complex:
365 print('STATIC const mp_obj_complex_t %s = {{&mp_type_complex}, %.16g, %.16g};'
366 % (obj_name, obj.real, obj.imag))
Damien George0699c6b2016-01-31 21:45:22 +0000367 else:
Damien George0699c6b2016-01-31 21:45:22 +0000368 raise FreezeError(self, 'freezing of object %r is not implemented' % (obj,))
369
Damien Georgeb6a32892017-08-12 22:26:18 +1000370 # generate constant table, if it has any entries
371 const_table_len = len(self.qstrs) + len(self.objs) + len(self.raw_codes)
372 if const_table_len:
373 print('STATIC const mp_rom_obj_t const_table_data_%s[%u] = {'
374 % (self.escaped_name, const_table_len))
375 for qst in self.qstrs:
376 print(' MP_ROM_QSTR(%s),' % global_qstrs[qst].qstr_id)
377 for i in range(len(self.objs)):
Damien Georgeea3c80a2019-02-21 15:18:59 +1100378 if self.objs[i] is MPFunTable:
379 print(' mp_fun_table,')
380 elif type(self.objs[i]) is float:
Damien Georgeb6a32892017-08-12 22:26:18 +1000381 print('#if MICROPY_OBJ_REPR == MICROPY_OBJ_REPR_A || MICROPY_OBJ_REPR == MICROPY_OBJ_REPR_B')
382 print(' MP_ROM_PTR(&const_obj_%s_%u),' % (self.escaped_name, i))
383 print('#elif MICROPY_OBJ_REPR == MICROPY_OBJ_REPR_C')
384 n = struct.unpack('<I', struct.pack('<f', self.objs[i]))[0]
385 n = ((n & ~0x3) | 2) + 0x80800000
386 print(' (mp_rom_obj_t)(0x%08x),' % (n,))
Damien George929d10a2018-07-09 12:22:40 +1000387 print('#elif MICROPY_OBJ_REPR == MICROPY_OBJ_REPR_D')
388 n = struct.unpack('<Q', struct.pack('<d', self.objs[i]))[0]
389 n += 0x8004000000000000
390 print(' (mp_rom_obj_t)(0x%016x),' % (n,))
Damien Georgeb6a32892017-08-12 22:26:18 +1000391 print('#endif')
392 else:
393 print(' MP_ROM_PTR(&const_obj_%s_%u),' % (self.escaped_name, i))
394 for rc in self.raw_codes:
395 print(' MP_ROM_PTR(&raw_code_%s),' % rc.escaped_name)
396 print('};')
Damien George0699c6b2016-01-31 21:45:22 +0000397
Damien Georgeea3c80a2019-02-21 15:18:59 +1100398 def freeze_module(self, qstr_links=(), type_sig=0):
Damien George0699c6b2016-01-31 21:45:22 +0000399 # generate module
400 if self.simple_name.str != '<module>':
401 print('STATIC ', end='')
402 print('const mp_raw_code_t raw_code_%s = {' % self.escaped_name)
Damien Georgeea3c80a2019-02-21 15:18:59 +1100403 print(' .kind = %s,' % RawCode.code_kind_str[self.code_kind])
Damien George0699c6b2016-01-31 21:45:22 +0000404 print(' .scope_flags = 0x%02x,' % self.prelude[2])
405 print(' .n_pos_args = %u,' % self.prelude[3])
Damien Georgeea3c80a2019-02-21 15:18:59 +1100406 print(' .fun_data = fun_data_%s,' % self.escaped_name)
407 if len(self.qstrs) + len(self.objs) + len(self.raw_codes):
Damien George636ed0f2019-02-19 14:15:39 +1100408 print(' .const_table = (mp_uint_t*)const_table_data_%s,' % self.escaped_name)
Damien Georgeb6a32892017-08-12 22:26:18 +1000409 else:
Damien George636ed0f2019-02-19 14:15:39 +1100410 print(' .const_table = NULL,')
411 print(' #if MICROPY_PERSISTENT_CODE_SAVE')
412 print(' .fun_data_len = %u,' % len(self.bytecode))
413 print(' .n_obj = %u,' % len(self.objs))
414 print(' .n_raw_code = %u,' % len(self.raw_codes))
Damien Georgec69f58e2019-09-06 23:55:15 +1000415 if self.code_kind == MP_CODE_BYTECODE:
416 print(' #if MICROPY_PY_SYS_SETTRACE')
417 print(' .prelude = {')
418 print(' .n_state = %u,' % self.prelude[0])
419 print(' .n_exc_stack = %u,' % self.prelude[1])
420 print(' .scope_flags = %u,' % self.prelude[2])
421 print(' .n_pos_args = %u,' % self.prelude[3])
422 print(' .n_kwonly_args = %u,' % self.prelude[4])
423 print(' .n_def_pos_args = %u,' % self.prelude[5])
424 print(' .qstr_block_name = %s,' % self.simple_name.qstr_id)
425 print(' .qstr_source_file = %s,' % self.source_file.qstr_id)
426 print(' .line_info = fun_data_%s + %u,' % (self.escaped_name, 0)) # TODO
427 print(' .locals = fun_data_%s + %u,' % (self.escaped_name, 0)) # TODO
428 print(' .opcodes = fun_data_%s + %u,' % (self.escaped_name, self.ip))
429 print(' },')
430 print(' .line_of_definition = %u,' % 0) # TODO
431 print(' #endif')
Jun Wub152bbd2019-05-06 00:31:11 -0700432 print(' #if MICROPY_EMIT_MACHINE_CODE')
Damien Georgeea3c80a2019-02-21 15:18:59 +1100433 print(' .prelude_offset = %u,' % self.prelude_offset)
434 print(' .n_qstr = %u,' % len(qstr_links))
435 print(' .qstr_link = NULL,') # TODO
436 print(' #endif')
437 print(' #endif')
Jun Wub152bbd2019-05-06 00:31:11 -0700438 print(' #if MICROPY_EMIT_MACHINE_CODE')
Damien Georgeea3c80a2019-02-21 15:18:59 +1100439 print(' .type_sig = %u,' % type_sig)
Damien George636ed0f2019-02-19 14:15:39 +1100440 print(' #endif')
Damien George0699c6b2016-01-31 21:45:22 +0000441 print('};')
442
Damien Georgeea3c80a2019-02-21 15:18:59 +1100443class RawCodeBytecode(RawCode):
444 def __init__(self, bytecode, qstrs, objs, raw_codes):
Damien George643d2a02019-04-08 11:21:18 +1000445 super(RawCodeBytecode, self).__init__(MP_CODE_BYTECODE, bytecode, 0, qstrs, objs, raw_codes)
Damien Georgeea3c80a2019-02-21 15:18:59 +1100446
447 def freeze(self, parent_name):
448 self.freeze_children(parent_name)
449
450 # generate bytecode data
451 print()
452 print('// frozen bytecode for file %s, scope %s%s' % (self.source_file.str, parent_name, self.simple_name.str))
453 print('STATIC ', end='')
454 if not config.MICROPY_OPT_CACHE_MAP_LOOKUP_IN_BYTECODE:
455 print('const ', end='')
456 print('byte fun_data_%s[%u] = {' % (self.escaped_name, len(self.bytecode)))
457 print(' ', end='')
458 for i in range(self.ip2):
459 print(' 0x%02x,' % self.bytecode[i], end='')
460 print()
461 print(' ', self.simple_name.qstr_id, '& 0xff,', self.simple_name.qstr_id, '>> 8,')
462 print(' ', self.source_file.qstr_id, '& 0xff,', self.source_file.qstr_id, '>> 8,')
463 print(' ', end='')
464 for i in range(self.ip2 + 4, self.ip):
465 print(' 0x%02x,' % self.bytecode[i], end='')
466 print()
467 ip = self.ip
468 while ip < len(self.bytecode):
469 f, sz = mp_opcode_format(self.bytecode, ip, True)
470 if f == 1:
471 qst = self._unpack_qstr(ip + 1).qstr_id
472 extra = '' if sz == 3 else ' 0x%02x,' % self.bytecode[ip + 3]
473 print(' ', '0x%02x,' % self.bytecode[ip], qst, '& 0xff,', qst, '>> 8,', extra)
474 else:
475 print(' ', ''.join('0x%02x, ' % self.bytecode[ip + i] for i in range(sz)))
476 ip += sz
477 print('};')
478
479 self.freeze_constants()
480 self.freeze_module()
481
482class RawCodeNative(RawCode):
483 def __init__(self, code_kind, fun_data, prelude_offset, prelude, qstr_links, qstrs, objs, raw_codes, type_sig):
Damien George643d2a02019-04-08 11:21:18 +1000484 super(RawCodeNative, self).__init__(code_kind, fun_data, prelude_offset, qstrs, objs, raw_codes)
Damien Georgeea3c80a2019-02-21 15:18:59 +1100485 self.prelude = prelude
486 self.qstr_links = qstr_links
487 self.type_sig = type_sig
488 if config.native_arch in (MP_NATIVE_ARCH_X86, MP_NATIVE_ARCH_X64):
489 self.fun_data_attributes = '__attribute__((section(".text,\\"ax\\",@progbits # ")))'
490 else:
491 self.fun_data_attributes = '__attribute__((section(".text,\\"ax\\",%progbits @ ")))'
492
Jim Mussared4ab51562019-08-17 00:32:04 +1000493 # Allow single-byte alignment by default for x86/x64/xtensa, but on ARM we need halfword- or word- alignment.
494 if config.native_arch == MP_NATIVE_ARCH_ARMV6:
495 # ARMV6 -- four byte align.
496 self.fun_data_attributes += ' __attribute__ ((aligned (4)))'
497 elif MP_NATIVE_ARCH_ARMV6M <= config.native_arch <= MP_NATIVE_ARCH_ARMV7EMDP:
498 # ARMVxxM -- two byte align.
499 self.fun_data_attributes += ' __attribute__ ((aligned (2)))'
500
Damien Georgeea3c80a2019-02-21 15:18:59 +1100501 def _asm_thumb_rewrite_mov(self, pc, val):
502 print(' (%u & 0xf0) | (%s >> 12),' % (self.bytecode[pc], val), end='')
503 print(' (%u & 0xfb) | (%s >> 9 & 0x04),' % (self.bytecode[pc + 1], val), end='')
504 print(' (%s & 0xff),' % (val,), end='')
505 print(' (%u & 0x07) | (%s >> 4 & 0x70),' % (self.bytecode[pc + 3], val))
506
507 def _link_qstr(self, pc, kind, qst):
508 if kind == 0:
Damien Georgefaf3d3e2019-06-04 22:13:32 +1000509 # Generic 16-bit link
Damien Georgeea3c80a2019-02-21 15:18:59 +1100510 print(' %s & 0xff, %s >> 8,' % (qst, qst))
Damien George9d3031c2019-06-11 11:36:39 +1000511 return 2
Damien Georgeea3c80a2019-02-21 15:18:59 +1100512 else:
Damien Georgefaf3d3e2019-06-04 22:13:32 +1000513 # Architecture-specific link
514 is_obj = kind == 2
515 if is_obj:
Damien Georgeea3c80a2019-02-21 15:18:59 +1100516 qst = '((uintptr_t)MP_OBJ_NEW_QSTR(%s))' % qst
517 if config.native_arch in (MP_NATIVE_ARCH_X86, MP_NATIVE_ARCH_X64):
518 print(' %s & 0xff, %s >> 8, 0, 0,' % (qst, qst))
Damien George9d3031c2019-06-11 11:36:39 +1000519 return 4
Damien Georgeea3c80a2019-02-21 15:18:59 +1100520 elif MP_NATIVE_ARCH_ARMV6M <= config.native_arch <= MP_NATIVE_ARCH_ARMV7EMDP:
521 if is_obj:
Damien Georgefaf3d3e2019-06-04 22:13:32 +1000522 # qstr object, movw and movt
523 self._asm_thumb_rewrite_mov(pc, qst)
524 self._asm_thumb_rewrite_mov(pc + 4, '(%s >> 16)' % qst)
Damien George9d3031c2019-06-11 11:36:39 +1000525 return 8
Damien Georgeea3c80a2019-02-21 15:18:59 +1100526 else:
Damien Georgefaf3d3e2019-06-04 22:13:32 +1000527 # qstr number, movw instruction
528 self._asm_thumb_rewrite_mov(pc, qst)
Damien George9d3031c2019-06-11 11:36:39 +1000529 return 4
Damien Georgeea3c80a2019-02-21 15:18:59 +1100530 else:
531 assert 0
532
533 def freeze(self, parent_name):
534 self.freeze_children(parent_name)
535
536 # generate native code data
537 print()
538 if self.code_kind == MP_CODE_NATIVE_PY:
539 print('// frozen native code for file %s, scope %s%s' % (self.source_file.str, parent_name, self.simple_name.str))
540 elif self.code_kind == MP_CODE_NATIVE_VIPER:
541 print('// frozen viper code for scope %s' % (parent_name,))
542 else:
543 print('// frozen assembler code for scope %s' % (parent_name,))
544 print('STATIC const byte fun_data_%s[%u] %s = {' % (self.escaped_name, len(self.bytecode), self.fun_data_attributes))
545
546 if self.code_kind == MP_CODE_NATIVE_PY:
547 i_top = self.prelude_offset
548 else:
549 i_top = len(self.bytecode)
550 i = 0
551 qi = 0
552 while i < i_top:
553 if qi < len(self.qstr_links) and i == self.qstr_links[qi][0]:
554 # link qstr
555 qi_off, qi_kind, qi_val = self.qstr_links[qi]
556 qst = global_qstrs[qi_val].qstr_id
Damien George9d3031c2019-06-11 11:36:39 +1000557 i += self._link_qstr(i, qi_kind, qst)
Damien Georgeea3c80a2019-02-21 15:18:59 +1100558 qi += 1
559 else:
560 # copy machine code (max 16 bytes)
561 i16 = min(i + 16, i_top)
562 if qi < len(self.qstr_links):
563 i16 = min(i16, self.qstr_links[qi][0])
564 print(' ', end='')
565 for ii in range(i, i16):
566 print(' 0x%02x,' % self.bytecode[ii], end='')
567 print()
568 i = i16
569
570 if self.code_kind == MP_CODE_NATIVE_PY:
571 print(' ', end='')
572 for i in range(self.prelude_offset, self.ip2):
573 print(' 0x%02x,' % self.bytecode[i], end='')
574 print()
575
576 print(' ', self.simple_name.qstr_id, '& 0xff,', self.simple_name.qstr_id, '>> 8,')
577 print(' ', self.source_file.qstr_id, '& 0xff,', self.source_file.qstr_id, '>> 8,')
578
579 print(' ', end='')
580 for i in range(self.ip2 + 4, self.ip):
581 print(' 0x%02x,' % self.bytecode[i], end='')
582 print()
583
584 print('};')
585
586 self.freeze_constants()
587 self.freeze_module(self.qstr_links, self.type_sig)
588
Damien George992a6e12019-03-01 14:03:10 +1100589class BytecodeBuffer:
590 def __init__(self, size):
591 self.buf = bytearray(size)
592 self.idx = 0
593
594 def is_full(self):
595 return self.idx == len(self.buf)
596
597 def append(self, b):
598 self.buf[self.idx] = b
599 self.idx += 1
600
601def read_byte(f, out=None):
602 b = bytes_cons(f.read(1))[0]
603 if out is not None:
604 out.append(b)
605 return b
606
607def read_uint(f, out=None):
Damien George0699c6b2016-01-31 21:45:22 +0000608 i = 0
609 while True:
Damien George992a6e12019-03-01 14:03:10 +1100610 b = read_byte(f, out)
Damien George0699c6b2016-01-31 21:45:22 +0000611 i = (i << 7) | (b & 0x7f)
612 if b & 0x80 == 0:
613 break
614 return i
615
Damien George5996eeb2019-02-25 23:15:51 +1100616def read_qstr(f, qstr_win):
Damien George0699c6b2016-01-31 21:45:22 +0000617 ln = read_uint(f)
Damien George4f0931b2019-03-01 14:33:03 +1100618 if ln == 0:
619 # static qstr
620 return bytes_cons(f.read(1))[0]
Damien George5996eeb2019-02-25 23:15:51 +1100621 if ln & 1:
622 # qstr in table
623 return qstr_win.access(ln >> 1)
624 ln >>= 1
Damien Georgec3beb162016-04-15 11:56:10 +0100625 data = str_cons(f.read(ln), 'utf8')
Damien George4f0931b2019-03-01 14:33:03 +1100626 global_qstrs.append(QStrType(data))
Damien George5996eeb2019-02-25 23:15:51 +1100627 qstr_win.push(len(global_qstrs) - 1)
Damien George0699c6b2016-01-31 21:45:22 +0000628 return len(global_qstrs) - 1
629
630def read_obj(f):
631 obj_type = f.read(1)
632 if obj_type == b'e':
633 return Ellipsis
634 else:
635 buf = f.read(read_uint(f))
636 if obj_type == b's':
Damien Georgec3beb162016-04-15 11:56:10 +0100637 return str_cons(buf, 'utf8')
Damien George0699c6b2016-01-31 21:45:22 +0000638 elif obj_type == b'b':
Damien Georgec3beb162016-04-15 11:56:10 +0100639 return bytes_cons(buf)
Damien George0699c6b2016-01-31 21:45:22 +0000640 elif obj_type == b'i':
Damien Georgec3beb162016-04-15 11:56:10 +0100641 return int(str_cons(buf, 'ascii'), 10)
Damien George0699c6b2016-01-31 21:45:22 +0000642 elif obj_type == b'f':
Damien Georgec3beb162016-04-15 11:56:10 +0100643 return float(str_cons(buf, 'ascii'))
Damien George0699c6b2016-01-31 21:45:22 +0000644 elif obj_type == b'c':
Damien Georgec3beb162016-04-15 11:56:10 +0100645 return complex(str_cons(buf, 'ascii'))
Damien George0699c6b2016-01-31 21:45:22 +0000646 else:
647 assert 0
648
Damien George992a6e12019-03-01 14:03:10 +1100649def read_prelude(f, bytecode):
650 n_state = read_uint(f, bytecode)
651 n_exc_stack = read_uint(f, bytecode)
652 scope_flags = read_byte(f, bytecode)
653 n_pos_args = read_byte(f, bytecode)
654 n_kwonly_args = read_byte(f, bytecode)
655 n_def_pos_args = read_byte(f, bytecode)
656 l1 = bytecode.idx
657 code_info_size = read_uint(f, bytecode)
658 l2 = bytecode.idx
659 for _ in range(code_info_size - (l2 - l1)):
660 read_byte(f, bytecode)
661 while read_byte(f, bytecode) != 255:
662 pass
663 return l2, (n_state, n_exc_stack, scope_flags, n_pos_args, n_kwonly_args, n_def_pos_args, code_info_size)
Damien George0699c6b2016-01-31 21:45:22 +0000664
Damien George992a6e12019-03-01 14:03:10 +1100665def read_qstr_and_pack(f, bytecode, qstr_win):
666 qst = read_qstr(f, qstr_win)
667 bytecode.append(qst & 0xff)
668 bytecode.append(qst >> 8)
669
670def read_bytecode(file, bytecode, qstr_win):
671 while not bytecode.is_full():
672 op = read_byte(file, bytecode)
673 f, sz = mp_opcode_format(bytecode.buf, bytecode.idx - 1, False)
674 sz -= 1
675 if f == MP_OPCODE_QSTR:
676 read_qstr_and_pack(file, bytecode, qstr_win)
677 sz -= 2
678 elif f == MP_OPCODE_VAR_UINT:
679 while read_byte(file, bytecode) & 0x80:
680 pass
681 for _ in range(sz):
682 read_byte(file, bytecode)
Damien George0699c6b2016-01-31 21:45:22 +0000683
Damien George5996eeb2019-02-25 23:15:51 +1100684def read_raw_code(f, qstr_win):
Damien Georgeea3c80a2019-02-21 15:18:59 +1100685 kind_len = read_uint(f)
686 kind = (kind_len & 3) + MP_CODE_BYTECODE
687 fun_data_len = kind_len >> 2
688 fun_data = BytecodeBuffer(fun_data_len)
689
690 if kind == MP_CODE_BYTECODE:
691 name_idx, prelude = read_prelude(f, fun_data)
692 read_bytecode(f, fun_data, qstr_win)
693 else:
694 fun_data.buf[:] = f.read(fun_data_len)
695
696 qstr_links = []
697 if kind in (MP_CODE_NATIVE_PY, MP_CODE_NATIVE_VIPER):
698 # load qstr link table
699 n_qstr_link = read_uint(f)
700 for _ in range(n_qstr_link):
Damien Georgefaf3d3e2019-06-04 22:13:32 +1000701 off = read_uint(f)
Damien Georgeea3c80a2019-02-21 15:18:59 +1100702 qst = read_qstr(f, qstr_win)
703 qstr_links.append((off >> 2, off & 3, qst))
704
705 type_sig = 0
706 if kind == MP_CODE_NATIVE_PY:
707 prelude_offset = read_uint(f)
708 _, name_idx, prelude = extract_prelude(fun_data.buf, prelude_offset)
709 else:
710 prelude_offset = None
711 scope_flags = read_uint(f)
712 n_pos_args = 0
713 if kind == MP_CODE_NATIVE_ASM:
714 n_pos_args = read_uint(f)
715 type_sig = read_uint(f)
716 prelude = (None, None, scope_flags, n_pos_args, 0)
717
718 if kind in (MP_CODE_BYTECODE, MP_CODE_NATIVE_PY):
719 fun_data.idx = name_idx # rewind to where qstrs are in prelude
720 read_qstr_and_pack(f, fun_data, qstr_win) # simple_name
721 read_qstr_and_pack(f, fun_data, qstr_win) # source_file
722
723 qstrs = []
724 objs = []
725 raw_codes = []
726 if kind != MP_CODE_NATIVE_ASM:
727 # load constant table
728 n_obj = read_uint(f)
729 n_raw_code = read_uint(f)
730 qstrs = [read_qstr(f, qstr_win) for _ in range(prelude[3] + prelude[4])]
731 if kind != MP_CODE_BYTECODE:
732 objs.append(MPFunTable)
733 objs.extend([read_obj(f) for _ in range(n_obj)])
734 raw_codes = [read_raw_code(f, qstr_win) for _ in range(n_raw_code)]
735
736 if kind == MP_CODE_BYTECODE:
737 return RawCodeBytecode(fun_data.buf, qstrs, objs, raw_codes)
738 else:
739 return RawCodeNative(kind, fun_data.buf, prelude_offset, prelude, qstr_links, qstrs, objs, raw_codes, type_sig)
Damien George0699c6b2016-01-31 21:45:22 +0000740
741def read_mpy(filename):
742 with open(filename, 'rb') as f:
Damien Georgec3beb162016-04-15 11:56:10 +0100743 header = bytes_cons(f.read(4))
Damien George0699c6b2016-01-31 21:45:22 +0000744 if header[0] != ord('M'):
745 raise Exception('not a valid .mpy file')
Damien George6a110482017-02-17 00:19:34 +1100746 if header[1] != config.MPY_VERSION:
747 raise Exception('incompatible .mpy version')
Damien George5996eeb2019-02-25 23:15:51 +1100748 feature_byte = header[2]
749 qw_size = read_uint(f)
750 config.MICROPY_OPT_CACHE_MAP_LOOKUP_IN_BYTECODE = (feature_byte & 1) != 0
751 config.MICROPY_PY_BUILTINS_STR_UNICODE = (feature_byte & 2) != 0
Damien Georgefaf3d3e2019-06-04 22:13:32 +1000752 mpy_native_arch = feature_byte >> 2
753 if mpy_native_arch != MP_NATIVE_ARCH_NONE:
754 if config.native_arch == MP_NATIVE_ARCH_NONE:
755 config.native_arch = mpy_native_arch
756 elif config.native_arch != mpy_native_arch:
757 raise Exception('native architecture mismatch')
Damien George0699c6b2016-01-31 21:45:22 +0000758 config.mp_small_int_bits = header[3]
Damien George5996eeb2019-02-25 23:15:51 +1100759 qstr_win = QStrWindow(qw_size)
760 return read_raw_code(f, qstr_win)
Damien George0699c6b2016-01-31 21:45:22 +0000761
762def dump_mpy(raw_codes):
763 for rc in raw_codes:
764 rc.dump()
765
Damien Georgeb4790af2016-09-02 15:09:21 +1000766def freeze_mpy(base_qstrs, raw_codes):
Damien George0699c6b2016-01-31 21:45:22 +0000767 # add to qstrs
768 new = {}
769 for q in global_qstrs:
770 # don't add duplicates
Damien George4f0931b2019-03-01 14:33:03 +1100771 if q is None or q.qstr_esc in base_qstrs or q.qstr_esc in new:
Damien George0699c6b2016-01-31 21:45:22 +0000772 continue
773 new[q.qstr_esc] = (len(new), q.qstr_esc, q.str)
774 new = sorted(new.values(), key=lambda x: x[0])
775
776 print('#include "py/mpconfig.h"')
777 print('#include "py/objint.h"')
778 print('#include "py/objstr.h"')
779 print('#include "py/emitglue.h"')
780 print()
781
Damien George98458a42017-01-05 15:52:52 +1100782 print('#if MICROPY_OPT_CACHE_MAP_LOOKUP_IN_BYTECODE != %u' % config.MICROPY_OPT_CACHE_MAP_LOOKUP_IN_BYTECODE)
783 print('#error "incompatible MICROPY_OPT_CACHE_MAP_LOOKUP_IN_BYTECODE"')
Damien George99b47192016-05-16 23:13:30 +0100784 print('#endif')
785 print()
786
787 print('#if MICROPY_LONGINT_IMPL != %u' % config.MICROPY_LONGINT_IMPL)
788 print('#error "incompatible MICROPY_LONGINT_IMPL"')
789 print('#endif')
790 print()
791
792 if config.MICROPY_LONGINT_IMPL == config.MICROPY_LONGINT_IMPL_MPZ:
793 print('#if MPZ_DIG_SIZE != %u' % config.MPZ_DIG_SIZE)
794 print('#error "incompatible MPZ_DIG_SIZE"')
795 print('#endif')
796 print()
797
798
Damien George0699c6b2016-01-31 21:45:22 +0000799 print('#if MICROPY_PY_BUILTINS_FLOAT')
800 print('typedef struct _mp_obj_float_t {')
801 print(' mp_obj_base_t base;')
802 print(' mp_float_t value;')
803 print('} mp_obj_float_t;')
804 print('#endif')
805 print()
806
Damien Georgec51c8832016-09-03 00:19:02 +1000807 print('#if MICROPY_PY_BUILTINS_COMPLEX')
808 print('typedef struct _mp_obj_complex_t {')
809 print(' mp_obj_base_t base;')
810 print(' mp_float_t real;')
811 print(' mp_float_t imag;')
812 print('} mp_obj_complex_t;')
813 print('#endif')
814 print()
815
Dave Hylands39eef272018-12-11 14:55:26 -0800816 if len(new) > 0:
817 print('enum {')
818 for i in range(len(new)):
819 if i == 0:
820 print(' MP_QSTR_%s = MP_QSTRnumber_of,' % new[i][1])
821 else:
822 print(' MP_QSTR_%s,' % new[i][1])
823 print('};')
Damien George0699c6b2016-01-31 21:45:22 +0000824
Rich Barlow6e5a40c2018-07-19 12:42:26 +0100825 # As in qstr.c, set so that the first dynamically allocated pool is twice this size; must be <= the len
826 qstr_pool_alloc = min(len(new), 10)
827
Damien George0699c6b2016-01-31 21:45:22 +0000828 print()
829 print('extern const qstr_pool_t mp_qstr_const_pool;');
830 print('const qstr_pool_t mp_qstr_frozen_const_pool = {')
831 print(' (qstr_pool_t*)&mp_qstr_const_pool, // previous pool')
832 print(' MP_QSTRnumber_of, // previous pool size')
Rich Barlow6e5a40c2018-07-19 12:42:26 +0100833 print(' %u, // allocated entries' % qstr_pool_alloc)
Damien George0699c6b2016-01-31 21:45:22 +0000834 print(' %u, // used entries' % len(new))
835 print(' {')
836 for _, _, qstr in new:
Damien Georgeb4790af2016-09-02 15:09:21 +1000837 print(' %s,'
838 % qstrutil.make_bytes(config.MICROPY_QSTR_BYTES_IN_LEN, config.MICROPY_QSTR_BYTES_IN_HASH, qstr))
Damien George0699c6b2016-01-31 21:45:22 +0000839 print(' },')
840 print('};')
841
842 for rc in raw_codes:
843 rc.freeze(rc.source_file.str.replace('/', '_')[:-3] + '_')
844
845 print()
846 print('const char mp_frozen_mpy_names[] = {')
847 for rc in raw_codes:
Damien George9b4c0132016-05-23 12:46:02 +0100848 module_name = rc.source_file.str
Damien George0699c6b2016-01-31 21:45:22 +0000849 print('"%s\\0"' % module_name)
850 print('"\\0"};')
851
852 print('const mp_raw_code_t *const mp_frozen_mpy_content[] = {')
853 for rc in raw_codes:
854 print(' &raw_code_%s,' % rc.escaped_name)
855 print('};')
856
857def main():
858 import argparse
859 cmd_parser = argparse.ArgumentParser(description='A tool to work with MicroPython .mpy files.')
860 cmd_parser.add_argument('-d', '--dump', action='store_true',
861 help='dump contents of files')
862 cmd_parser.add_argument('-f', '--freeze', action='store_true',
863 help='freeze files')
864 cmd_parser.add_argument('-q', '--qstr-header',
865 help='qstr header file to freeze against')
866 cmd_parser.add_argument('-mlongint-impl', choices=['none', 'longlong', 'mpz'], default='mpz',
867 help='long-int implementation used by target (default mpz)')
868 cmd_parser.add_argument('-mmpz-dig-size', metavar='N', type=int, default=16,
869 help='mpz digit size used by target (default 16)')
870 cmd_parser.add_argument('files', nargs='+',
871 help='input .mpy files')
872 args = cmd_parser.parse_args()
873
874 # set config values relevant to target machine
875 config.MICROPY_LONGINT_IMPL = {
876 'none':config.MICROPY_LONGINT_IMPL_NONE,
877 'longlong':config.MICROPY_LONGINT_IMPL_LONGLONG,
878 'mpz':config.MICROPY_LONGINT_IMPL_MPZ,
879 }[args.mlongint_impl]
880 config.MPZ_DIG_SIZE = args.mmpz_dig_size
Damien Georgefaf3d3e2019-06-04 22:13:32 +1000881 config.native_arch = MP_NATIVE_ARCH_NONE
Damien George0699c6b2016-01-31 21:45:22 +0000882
Damien Georgeb4790af2016-09-02 15:09:21 +1000883 # set config values for qstrs, and get the existing base set of qstrs
Damien George0699c6b2016-01-31 21:45:22 +0000884 if args.qstr_header:
885 qcfgs, base_qstrs = qstrutil.parse_input_headers([args.qstr_header])
Damien Georgeb4790af2016-09-02 15:09:21 +1000886 config.MICROPY_QSTR_BYTES_IN_LEN = int(qcfgs['BYTES_IN_LEN'])
887 config.MICROPY_QSTR_BYTES_IN_HASH = int(qcfgs['BYTES_IN_HASH'])
Damien George0699c6b2016-01-31 21:45:22 +0000888 else:
Damien Georgeb4790af2016-09-02 15:09:21 +1000889 config.MICROPY_QSTR_BYTES_IN_LEN = 1
890 config.MICROPY_QSTR_BYTES_IN_HASH = 1
891 base_qstrs = {}
Damien George0699c6b2016-01-31 21:45:22 +0000892
893 raw_codes = [read_mpy(file) for file in args.files]
894
895 if args.dump:
896 dump_mpy(raw_codes)
897 elif args.freeze:
898 try:
Damien Georgeb4790af2016-09-02 15:09:21 +1000899 freeze_mpy(base_qstrs, raw_codes)
Damien George0699c6b2016-01-31 21:45:22 +0000900 except FreezeError as er:
901 print(er, file=sys.stderr)
902 sys.exit(1)
903
904if __name__ == '__main__':
905 main()