blob: 99b01f8e2721c91b174c70793d7cd460127f5a24 [file] [log] [blame]
Damien George6810f2c2016-11-16 11:55:41 +11001/*
2 * This file is part of the MicroPython project, http://micropython.org/
3 *
4 * The MIT License (MIT)
5 *
6 * Copyright (c) 2013-2016 Damien P. George
7 *
8 * Permission is hereby granted, free of charge, to any person obtaining a copy
9 * of this software and associated documentation files (the "Software"), to deal
10 * in the Software without restriction, including without limitation the rights
11 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
12 * copies of the Software, and to permit persons to whom the Software is
13 * furnished to do so, subject to the following conditions:
14 *
15 * The above copyright notice and this permission notice shall be included in
16 * all copies or substantial portions of the Software.
17 *
18 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
19 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
20 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
21 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
22 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
23 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
24 * THE SOFTWARE.
25 */
26
27#include <stdint.h>
28#include <stdio.h>
29#include <string.h>
30#include <assert.h>
31
Damien George6b239c22016-11-16 16:04:57 +110032#include "py/reader.h"
Damien George6810f2c2016-11-16 11:55:41 +110033#include "py/emitglue.h"
34#include "py/persistentcode.h"
35#include "py/bc.h"
36
37#if MICROPY_PERSISTENT_CODE_LOAD || MICROPY_PERSISTENT_CODE_SAVE
38
39#include "py/smallint.h"
40
41// The feature flags byte encodes the compile-time config options that
42// affect the generate bytecode.
43#define MPY_FEATURE_FLAGS ( \
44 ((MICROPY_OPT_CACHE_MAP_LOOKUP_IN_BYTECODE) << 0) \
45 | ((MICROPY_PY_BUILTINS_STR_UNICODE) << 1) \
46 )
47// This is a version of the flags that can be configured at runtime.
48#define MPY_FEATURE_FLAGS_DYNAMIC ( \
49 ((MICROPY_OPT_CACHE_MAP_LOOKUP_IN_BYTECODE_DYNAMIC) << 0) \
50 | ((MICROPY_PY_BUILTINS_STR_UNICODE_DYNAMIC) << 1) \
51 )
52
53#if MICROPY_PERSISTENT_CODE_LOAD || (MICROPY_PERSISTENT_CODE_SAVE && !MICROPY_DYNAMIC_COMPILER)
54// The bytecode will depend on the number of bits in a small-int, and
55// this function computes that (could make it a fixed constant, but it
56// would need to be defined in mpconfigport.h).
57STATIC int mp_small_int_bits(void) {
58 mp_int_t i = MP_SMALL_INT_MAX;
59 int n = 1;
60 while (i != 0) {
61 i >>= 1;
62 ++n;
63 }
64 return n;
65}
66#endif
67
68typedef struct _bytecode_prelude_t {
69 uint n_state;
70 uint n_exc_stack;
71 uint scope_flags;
72 uint n_pos_args;
73 uint n_kwonly_args;
74 uint n_def_pos_args;
75 uint code_info_size;
76} bytecode_prelude_t;
77
78// ip will point to start of opcodes
79// ip2 will point to simple_name, source_file qstrs
80STATIC void extract_prelude(const byte **ip, const byte **ip2, bytecode_prelude_t *prelude) {
81 prelude->n_state = mp_decode_uint(ip);
82 prelude->n_exc_stack = mp_decode_uint(ip);
83 prelude->scope_flags = *(*ip)++;
84 prelude->n_pos_args = *(*ip)++;
85 prelude->n_kwonly_args = *(*ip)++;
86 prelude->n_def_pos_args = *(*ip)++;
87 *ip2 = *ip;
88 prelude->code_info_size = mp_decode_uint(ip2);
89 *ip += prelude->code_info_size;
90 while (*(*ip)++ != 255) {
91 }
92}
93
94#endif // MICROPY_PERSISTENT_CODE_LOAD || MICROPY_PERSISTENT_CODE_SAVE
95
96#if MICROPY_PERSISTENT_CODE_LOAD
97
98#include "py/parsenum.h"
99#include "py/bc0.h"
100
101STATIC int read_byte(mp_reader_t *reader) {
Damien George6b239c22016-11-16 16:04:57 +1100102 return reader->readbyte(reader->data);
Damien George6810f2c2016-11-16 11:55:41 +1100103}
104
105STATIC void read_bytes(mp_reader_t *reader, byte *buf, size_t len) {
106 while (len-- > 0) {
Damien George6b239c22016-11-16 16:04:57 +1100107 *buf++ = reader->readbyte(reader->data);
Damien George6810f2c2016-11-16 11:55:41 +1100108 }
109}
110
111STATIC mp_uint_t read_uint(mp_reader_t *reader) {
112 mp_uint_t unum = 0;
113 for (;;) {
Damien George6b239c22016-11-16 16:04:57 +1100114 byte b = reader->readbyte(reader->data);
Damien George6810f2c2016-11-16 11:55:41 +1100115 unum = (unum << 7) | (b & 0x7f);
116 if ((b & 0x80) == 0) {
117 break;
118 }
119 }
120 return unum;
121}
122
123STATIC qstr load_qstr(mp_reader_t *reader) {
124 mp_uint_t len = read_uint(reader);
125 char *str = m_new(char, len);
126 read_bytes(reader, (byte*)str, len);
127 qstr qst = qstr_from_strn(str, len);
128 m_del(char, str, len);
129 return qst;
130}
131
132STATIC mp_obj_t load_obj(mp_reader_t *reader) {
133 byte obj_type = read_byte(reader);
134 if (obj_type == 'e') {
135 return MP_OBJ_FROM_PTR(&mp_const_ellipsis_obj);
136 } else {
137 size_t len = read_uint(reader);
138 vstr_t vstr;
139 vstr_init_len(&vstr, len);
140 read_bytes(reader, (byte*)vstr.buf, len);
141 if (obj_type == 's' || obj_type == 'b') {
142 return mp_obj_new_str_from_vstr(obj_type == 's' ? &mp_type_str : &mp_type_bytes, &vstr);
143 } else if (obj_type == 'i') {
144 return mp_parse_num_integer(vstr.buf, vstr.len, 10, NULL);
145 } else {
146 assert(obj_type == 'f' || obj_type == 'c');
147 return mp_parse_num_decimal(vstr.buf, vstr.len, obj_type == 'c', false, NULL);
148 }
149 }
150}
151
152STATIC void load_bytecode_qstrs(mp_reader_t *reader, byte *ip, byte *ip_top) {
153 while (ip < ip_top) {
154 size_t sz;
155 uint f = mp_opcode_format(ip, &sz);
156 if (f == MP_OPCODE_QSTR) {
157 qstr qst = load_qstr(reader);
158 ip[1] = qst;
159 ip[2] = qst >> 8;
160 }
161 ip += sz;
162 }
163}
164
165STATIC mp_raw_code_t *load_raw_code(mp_reader_t *reader) {
166 // load bytecode
167 mp_uint_t bc_len = read_uint(reader);
168 byte *bytecode = m_new(byte, bc_len);
169 read_bytes(reader, bytecode, bc_len);
170
171 // extract prelude
172 const byte *ip = bytecode;
173 const byte *ip2;
174 bytecode_prelude_t prelude;
175 extract_prelude(&ip, &ip2, &prelude);
176
177 // load qstrs and link global qstr ids into bytecode
178 qstr simple_name = load_qstr(reader);
179 qstr source_file = load_qstr(reader);
180 ((byte*)ip2)[0] = simple_name; ((byte*)ip2)[1] = simple_name >> 8;
181 ((byte*)ip2)[2] = source_file; ((byte*)ip2)[3] = source_file >> 8;
182 load_bytecode_qstrs(reader, (byte*)ip, bytecode + bc_len);
183
184 // load constant table
185 mp_uint_t n_obj = read_uint(reader);
186 mp_uint_t n_raw_code = read_uint(reader);
187 mp_uint_t *const_table = m_new(mp_uint_t, prelude.n_pos_args + prelude.n_kwonly_args + n_obj + n_raw_code);
188 mp_uint_t *ct = const_table;
189 for (mp_uint_t i = 0; i < prelude.n_pos_args + prelude.n_kwonly_args; ++i) {
190 *ct++ = (mp_uint_t)MP_OBJ_NEW_QSTR(load_qstr(reader));
191 }
192 for (mp_uint_t i = 0; i < n_obj; ++i) {
193 *ct++ = (mp_uint_t)load_obj(reader);
194 }
195 for (mp_uint_t i = 0; i < n_raw_code; ++i) {
196 *ct++ = (mp_uint_t)(uintptr_t)load_raw_code(reader);
197 }
198
199 // create raw_code and return it
200 mp_raw_code_t *rc = mp_emit_glue_new_raw_code();
201 mp_emit_glue_assign_bytecode(rc, bytecode, bc_len, const_table,
202 #if MICROPY_PERSISTENT_CODE_SAVE
203 n_obj, n_raw_code,
204 #endif
205 prelude.scope_flags);
206 return rc;
207}
208
209mp_raw_code_t *mp_raw_code_load(mp_reader_t *reader) {
210 byte header[4];
211 read_bytes(reader, header, sizeof(header));
212 if (strncmp((char*)header, "M\x00", 2) != 0) {
213 mp_raise_ValueError("invalid .mpy file");
214 }
215 if (header[2] != MPY_FEATURE_FLAGS || header[3] > mp_small_int_bits()) {
216 mp_raise_ValueError("incompatible .mpy file");
217 }
Damien George6b239c22016-11-16 16:04:57 +1100218 mp_raw_code_t *rc = load_raw_code(reader);
219 reader->close(reader->data);
220 return rc;
Damien George6810f2c2016-11-16 11:55:41 +1100221}
222
223mp_raw_code_t *mp_raw_code_load_mem(const byte *buf, size_t len) {
Damien George6b239c22016-11-16 16:04:57 +1100224 mp_reader_t reader;
225 if (!mp_reader_new_mem(&reader, buf, len, 0)) {
226 m_malloc_fail(BYTES_PER_WORD); // we need to raise a MemoryError
227 }
Damien George6810f2c2016-11-16 11:55:41 +1100228 return mp_raw_code_load(&reader);
229}
230
Damien George6810f2c2016-11-16 11:55:41 +1100231mp_raw_code_t *mp_raw_code_load_file(const char *filename) {
Damien George6810f2c2016-11-16 11:55:41 +1100232 mp_reader_t reader;
Damien George6b239c22016-11-16 16:04:57 +1100233 int ret = mp_reader_new_file(&reader, filename);
234 if (ret != 0) {
235 mp_raise_OSError(ret);
Damien George6810f2c2016-11-16 11:55:41 +1100236 }
Damien George6b239c22016-11-16 16:04:57 +1100237 return mp_raw_code_load(&reader);
Damien George6810f2c2016-11-16 11:55:41 +1100238}
239
Damien George6810f2c2016-11-16 11:55:41 +1100240#endif // MICROPY_PERSISTENT_CODE_LOAD
241
242#if MICROPY_PERSISTENT_CODE_SAVE
243
244#include "py/objstr.h"
245
246STATIC void mp_print_bytes(mp_print_t *print, const byte *data, size_t len) {
247 print->print_strn(print->data, (const char*)data, len);
248}
249
250#define BYTES_FOR_INT ((BYTES_PER_WORD * 8 + 6) / 7)
251STATIC void mp_print_uint(mp_print_t *print, mp_uint_t n) {
252 byte buf[BYTES_FOR_INT];
253 byte *p = buf + sizeof(buf);
254 *--p = n & 0x7f;
255 n >>= 7;
256 for (; n != 0; n >>= 7) {
257 *--p = 0x80 | (n & 0x7f);
258 }
259 print->print_strn(print->data, (char*)p, buf + sizeof(buf) - p);
260}
261
262STATIC void save_qstr(mp_print_t *print, qstr qst) {
263 size_t len;
264 const byte *str = qstr_data(qst, &len);
265 mp_print_uint(print, len);
266 mp_print_bytes(print, str, len);
267}
268
269STATIC void save_obj(mp_print_t *print, mp_obj_t o) {
270 if (MP_OBJ_IS_STR_OR_BYTES(o)) {
271 byte obj_type;
272 if (MP_OBJ_IS_STR(o)) {
273 obj_type = 's';
274 } else {
275 obj_type = 'b';
276 }
277 mp_uint_t len;
278 const char *str = mp_obj_str_get_data(o, &len);
279 mp_print_bytes(print, &obj_type, 1);
280 mp_print_uint(print, len);
281 mp_print_bytes(print, (const byte*)str, len);
282 } else if (MP_OBJ_TO_PTR(o) == &mp_const_ellipsis_obj) {
283 byte obj_type = 'e';
284 mp_print_bytes(print, &obj_type, 1);
285 } else {
286 // we save numbers using a simplistic text representation
287 // TODO could be improved
288 byte obj_type;
289 if (MP_OBJ_IS_TYPE(o, &mp_type_int)) {
290 obj_type = 'i';
291 } else if (mp_obj_is_float(o)) {
292 obj_type = 'f';
293 } else {
294 assert(MP_OBJ_IS_TYPE(o, &mp_type_complex));
295 obj_type = 'c';
296 }
297 vstr_t vstr;
298 mp_print_t pr;
299 vstr_init_print(&vstr, 10, &pr);
300 mp_obj_print_helper(&pr, o, PRINT_REPR);
301 mp_print_bytes(print, &obj_type, 1);
302 mp_print_uint(print, vstr.len);
303 mp_print_bytes(print, (const byte*)vstr.buf, vstr.len);
304 vstr_clear(&vstr);
305 }
306}
307
308STATIC void save_bytecode_qstrs(mp_print_t *print, const byte *ip, const byte *ip_top) {
309 while (ip < ip_top) {
310 size_t sz;
311 uint f = mp_opcode_format(ip, &sz);
312 if (f == MP_OPCODE_QSTR) {
313 qstr qst = ip[1] | (ip[2] << 8);
314 save_qstr(print, qst);
315 }
316 ip += sz;
317 }
318}
319
320STATIC void save_raw_code(mp_print_t *print, mp_raw_code_t *rc) {
321 if (rc->kind != MP_CODE_BYTECODE) {
322 mp_raise_ValueError("can only save bytecode");
323 }
324
325 // save bytecode
326 mp_print_uint(print, rc->data.u_byte.bc_len);
327 mp_print_bytes(print, rc->data.u_byte.bytecode, rc->data.u_byte.bc_len);
328
329 // extract prelude
330 const byte *ip = rc->data.u_byte.bytecode;
331 const byte *ip2;
332 bytecode_prelude_t prelude;
333 extract_prelude(&ip, &ip2, &prelude);
334
335 // save qstrs
336 save_qstr(print, ip2[0] | (ip2[1] << 8)); // simple_name
337 save_qstr(print, ip2[2] | (ip2[3] << 8)); // source_file
338 save_bytecode_qstrs(print, ip, rc->data.u_byte.bytecode + rc->data.u_byte.bc_len);
339
340 // save constant table
341 mp_print_uint(print, rc->data.u_byte.n_obj);
342 mp_print_uint(print, rc->data.u_byte.n_raw_code);
343 const mp_uint_t *const_table = rc->data.u_byte.const_table;
344 for (uint i = 0; i < prelude.n_pos_args + prelude.n_kwonly_args; ++i) {
345 mp_obj_t o = (mp_obj_t)*const_table++;
346 save_qstr(print, MP_OBJ_QSTR_VALUE(o));
347 }
348 for (uint i = 0; i < rc->data.u_byte.n_obj; ++i) {
349 save_obj(print, (mp_obj_t)*const_table++);
350 }
351 for (uint i = 0; i < rc->data.u_byte.n_raw_code; ++i) {
352 save_raw_code(print, (mp_raw_code_t*)(uintptr_t)*const_table++);
353 }
354}
355
356void mp_raw_code_save(mp_raw_code_t *rc, mp_print_t *print) {
357 // header contains:
358 // byte 'M'
359 // byte version
360 // byte feature flags
361 // byte number of bits in a small int
362 byte header[4] = {'M', 0, MPY_FEATURE_FLAGS_DYNAMIC,
363 #if MICROPY_DYNAMIC_COMPILER
364 mp_dynamic_compiler.small_int_bits,
365 #else
366 mp_small_int_bits(),
367 #endif
368 };
369 mp_print_bytes(print, header, sizeof(header));
370
371 save_raw_code(print, rc);
372}
373
374// here we define mp_raw_code_save_file depending on the port
375// TODO abstract this away properly
376
377#if defined(__i386__) || defined(__x86_64__) || (defined(__arm__) && (defined(__unix__)))
378
379#include <unistd.h>
380#include <sys/stat.h>
381#include <fcntl.h>
382
383STATIC void fd_print_strn(void *env, const char *str, size_t len) {
384 int fd = (intptr_t)env;
385 ssize_t ret = write(fd, str, len);
386 (void)ret;
387}
388
389void mp_raw_code_save_file(mp_raw_code_t *rc, const char *filename) {
390 int fd = open(filename, O_WRONLY | O_CREAT | O_TRUNC, 0644);
391 mp_print_t fd_print = {(void*)(intptr_t)fd, fd_print_strn};
392 mp_raw_code_save(rc, &fd_print);
393 close(fd);
394}
395
396#else
397#error mp_raw_code_save_file not implemented for this platform
398#endif
399
400#endif // MICROPY_PERSISTENT_CODE_SAVE