Branch data Line data Source code
1 : : /*
2 : : * This file is part of the MicroPython project, http://micropython.org/
3 : : *
4 : : * The MIT License (MIT)
5 : : *
6 : : * Copyright (c) 2013, 2014 Damien P. George
7 : : * Copyright (c) 2014-2017 Paul Sokolovsky
8 : : *
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 : : */
27 : :
28 : : #include <stdint.h>
29 : : #include <stdbool.h>
30 : : #include <stdio.h>
31 : : #include <string.h>
32 : : #include <stdlib.h>
33 : : #include <stdarg.h>
34 : : #include <unistd.h>
35 : : #include <ctype.h>
36 : : #include <sys/stat.h>
37 : : #include <sys/types.h>
38 : : #include <errno.h>
39 : : #include <signal.h>
40 : :
41 : : #include "py/compile.h"
42 : : #include "py/runtime.h"
43 : : #include "py/builtin.h"
44 : : #include "py/repl.h"
45 : : #include "py/gc.h"
46 : : #include "py/objstr.h"
47 : : #include "py/cstack.h"
48 : : #include "py/mperrno.h"
49 : : #include "py/mphal.h"
50 : : #include "py/mpthread.h"
51 : : #include "extmod/misc.h"
52 : : #include "extmod/modplatform.h"
53 : : #include "extmod/vfs.h"
54 : : #include "extmod/vfs_posix.h"
55 : : #include "genhdr/mpversion.h"
56 : : #include "input.h"
57 : :
58 : : // Command line options, with their defaults
59 : : static bool compile_only = false;
60 : : static uint emit_opt = MP_EMIT_OPT_NONE;
61 : :
62 : : #if MICROPY_ENABLE_GC
63 : : // Heap size of GC heap (if enabled)
64 : : // Make it larger on a 64 bit machine, because pointers are larger.
65 : : long heap_size = 1024 * 1024 * (sizeof(mp_uint_t) / 4);
66 : : #endif
67 : :
68 : : // Number of heaps to assign by default if MICROPY_GC_SPLIT_HEAP=1
69 : : #ifndef MICROPY_GC_SPLIT_HEAP_N_HEAPS
70 : : #define MICROPY_GC_SPLIT_HEAP_N_HEAPS (1)
71 : : #endif
72 : :
73 : : #if !MICROPY_PY_SYS_PATH
74 : : #error "The unix port requires MICROPY_PY_SYS_PATH=1"
75 : : #endif
76 : :
77 : : #if !MICROPY_PY_SYS_ARGV
78 : : #error "The unix port requires MICROPY_PY_SYS_ARGV=1"
79 : : #endif
80 : :
81 : 246 : static void stderr_print_strn(void *env, const char *str, size_t len) {
82 : 246 : (void)env;
83 : 246 : ssize_t ret;
84 [ - + - - ]: 246 : MP_HAL_RETRY_SYSCALL(ret, write(STDERR_FILENO, str, len), {});
85 : 246 : mp_os_dupterm_tx_strn(str, len);
86 : 246 : }
87 : :
88 : : const mp_print_t mp_stderr_print = {NULL, stderr_print_strn};
89 : :
90 : : #define FORCED_EXIT (0x100)
91 : : // If exc is SystemExit, return value where FORCED_EXIT bit set,
92 : : // and lower 8 bits are SystemExit value. For all other exceptions,
93 : : // return 1.
94 : 57 : static int handle_uncaught_exception(mp_obj_base_t *exc) {
95 : : // check for SystemExit
96 [ + + ]: 57 : if (mp_obj_is_subclass_fast(MP_OBJ_FROM_PTR(exc->type), MP_OBJ_FROM_PTR(&mp_type_SystemExit))) {
97 : : // None is an exit value of 0; an int is its value; anything else is 1
98 : 42 : mp_obj_t exit_val = mp_obj_exception_get_value(MP_OBJ_FROM_PTR(exc));
99 : 42 : mp_int_t val = 0;
100 [ - + - - ]: 42 : if (exit_val != mp_const_none && !mp_obj_get_int_maybe(exit_val, &val)) {
101 : 0 : val = 1;
102 : : }
103 : 42 : return FORCED_EXIT | (val & 255);
104 : : }
105 : :
106 : : // Report all other exceptions
107 : 15 : mp_obj_print_exception(&mp_stderr_print, MP_OBJ_FROM_PTR(exc));
108 : 15 : return 1;
109 : : }
110 : :
111 : : #define LEX_SRC_STR (1)
112 : : #define LEX_SRC_VSTR (2)
113 : : #define LEX_SRC_FILENAME (3)
114 : : #define LEX_SRC_STDIN (4)
115 : :
116 : : // Returns standard error codes: 0 for success, 1 for all other errors,
117 : : // except if FORCED_EXIT bit is set then script raised SystemExit and the
118 : : // value of the exit is in the lower 8 bits of the return value
119 : 2278 : static int execute_from_lexer(int source_kind, const void *source, mp_parse_input_kind_t input_kind, bool is_repl) {
120 : 2278 : mp_hal_set_interrupt_char(CHAR_CTRL_C);
121 : :
122 : 2278 : nlr_buf_t nlr;
123 [ + + ]: 2278 : if (nlr_push(&nlr) == 0) {
124 : : // create lexer based on source kind
125 : 2278 : mp_lexer_t *lex;
126 [ + + ]: 2278 : if (source_kind == LEX_SRC_STR) {
127 : 2 : const char *line = source;
128 : 2 : lex = mp_lexer_new_from_str_len(MP_QSTR__lt_stdin_gt_, line, strlen(line), false);
129 [ + + ]: 2276 : } else if (source_kind == LEX_SRC_VSTR) {
130 : 211 : const vstr_t *vstr = source;
131 : 211 : lex = mp_lexer_new_from_str_len(MP_QSTR__lt_stdin_gt_, vstr->buf, vstr->len, false);
132 [ + + ]: 2065 : } else if (source_kind == LEX_SRC_FILENAME) {
133 : 2064 : const char *filename = (const char *)source;
134 : 2064 : lex = mp_lexer_new_from_file(qstr_from_str(filename));
135 : : } else { // LEX_SRC_STDIN
136 : 1 : lex = mp_lexer_new_from_fd(MP_QSTR__lt_stdin_gt_, 0, false);
137 : : }
138 : :
139 : 2278 : qstr source_name = lex->source_name;
140 : :
141 : : #if MICROPY_PY___FILE__
142 [ + + ]: 2278 : if (input_kind == MP_PARSE_FILE_INPUT) {
143 : 2067 : mp_store_global(MP_QSTR___file__, MP_OBJ_NEW_QSTR(source_name));
144 : : }
145 : : #endif
146 : :
147 : 2278 : mp_parse_tree_t parse_tree = mp_parse(lex, input_kind);
148 : :
149 : : #if defined(MICROPY_UNIX_COVERAGE)
150 : : // allow to print the parse tree in the coverage build
151 [ + + ]: 2278 : if (mp_verbose_flag >= 3) {
152 : 2 : printf("----------------\n");
153 : 2 : mp_parse_node_print(&mp_plat_print, parse_tree.root, 0);
154 : 2 : printf("----------------\n");
155 : : }
156 : : #endif
157 : :
158 : 2278 : mp_obj_t module_fun = mp_compile(&parse_tree, source_name, is_repl);
159 : :
160 [ + - ]: 2263 : if (!compile_only) {
161 : : // execute it
162 : 2263 : mp_call_function_0(module_fun);
163 : : }
164 : :
165 : 2228 : mp_hal_set_interrupt_char(-1);
166 : 2228 : mp_handle_pending(true);
167 : 2228 : nlr_pop();
168 : 2228 : return 0;
169 : :
170 : : } else {
171 : : // uncaught exception
172 : 50 : mp_hal_set_interrupt_char(-1);
173 : 50 : mp_handle_pending(false);
174 : 50 : return handle_uncaught_exception(nlr.ret_val);
175 : : }
176 : : }
177 : :
178 : : #if MICROPY_USE_READLINE == 1
179 : : #include "shared/readline/readline.h"
180 : : #else
181 : : static char *strjoin(const char *s1, int sep_char, const char *s2) {
182 : : int l1 = strlen(s1);
183 : : int l2 = strlen(s2);
184 : : char *s = malloc(l1 + l2 + 2);
185 : : memcpy(s, s1, l1);
186 : : if (sep_char != 0) {
187 : : s[l1] = sep_char;
188 : : l1 += 1;
189 : : }
190 : : memcpy(s + l1, s2, l2);
191 : : s[l1 + l2] = 0;
192 : : return s;
193 : : }
194 : : #endif
195 : :
196 : 28 : static int do_repl(void) {
197 : 28 : mp_hal_stdout_tx_str(MICROPY_BANNER_NAME_AND_VERSION);
198 : 28 : mp_hal_stdout_tx_str("; " MICROPY_BANNER_MACHINE);
199 : 28 : mp_hal_stdout_tx_str("\nUse Ctrl-D to exit, Ctrl-E for paste mode\n");
200 : :
201 : : #if MICROPY_USE_READLINE == 1
202 : :
203 : : // use MicroPython supplied readline
204 : :
205 : 28 : vstr_t line;
206 : 28 : vstr_init(&line, 16);
207 : 239 : for (;;) {
208 : 239 : mp_hal_stdio_mode_raw();
209 : :
210 : 10 : input_restart:
211 : 249 : vstr_reset(&line);
212 : 249 : int ret = readline(&line, mp_repl_get_ps1());
213 : 249 : mp_parse_input_kind_t parse_input_kind = MP_PARSE_SINGLE_INPUT;
214 : :
215 [ - + ]: 249 : if (ret == CHAR_CTRL_C) {
216 : : // cancel input
217 : 0 : mp_hal_stdout_tx_str("\r\n");
218 : 0 : goto input_restart;
219 [ + + ]: 249 : } else if (ret == CHAR_CTRL_D) {
220 : : // EOF
221 : 28 : printf("\n");
222 : 28 : mp_hal_stdio_mode_orig();
223 : 28 : vstr_clear(&line);
224 : 28 : return 0;
225 [ - + ]: 221 : } else if (ret == CHAR_CTRL_E) {
226 : : // paste mode
227 : 0 : mp_hal_stdout_tx_str("\npaste mode; Ctrl-C to cancel, Ctrl-D to finish\n=== ");
228 : 0 : vstr_reset(&line);
229 : 0 : for (;;) {
230 : 0 : char c = mp_hal_stdin_rx_chr();
231 [ # # ]: 0 : if (c == CHAR_CTRL_C) {
232 : : // cancel everything
233 : 0 : mp_hal_stdout_tx_str("\n");
234 : 0 : goto input_restart;
235 [ # # ]: 0 : } else if (c == CHAR_CTRL_D) {
236 : : // end of input
237 : 0 : mp_hal_stdout_tx_str("\n");
238 : 0 : break;
239 : : } else {
240 : : // add char to buffer and echo
241 : 0 : vstr_add_byte(&line, c);
242 [ # # ]: 0 : if (c == '\r') {
243 : 0 : mp_hal_stdout_tx_str("\n=== ");
244 : : } else {
245 : 0 : mp_hal_stdout_tx_strn(&c, 1);
246 : : }
247 : : }
248 : : }
249 : 0 : parse_input_kind = MP_PARSE_FILE_INPUT;
250 [ + + ]: 221 : } else if (line.len == 0) {
251 [ - + ]: 10 : if (ret != 0) {
252 : 0 : printf("\n");
253 : : }
254 : 10 : goto input_restart;
255 : : } else {
256 : : // got a line with non-zero length, see if it needs continuing
257 [ + + ]: 253 : while (mp_repl_continue_with_input(vstr_null_terminated_str(&line))) {
258 : 42 : vstr_add_byte(&line, '\n');
259 : 42 : ret = readline(&line, mp_repl_get_ps2());
260 [ - + ]: 42 : if (ret == CHAR_CTRL_C) {
261 : : // cancel everything
262 : 0 : printf("\n");
263 : 0 : goto input_restart;
264 [ + - ]: 42 : } else if (ret == CHAR_CTRL_D) {
265 : : // stop entering compound statement
266 : : break;
267 : : }
268 : : }
269 : : }
270 : :
271 : 211 : mp_hal_stdio_mode_orig();
272 : :
273 : 211 : ret = execute_from_lexer(LEX_SRC_VSTR, &line, parse_input_kind, true);
274 [ + - ]: 211 : if (ret & FORCED_EXIT) {
275 : : return ret;
276 : : }
277 : : }
278 : :
279 : : #else
280 : :
281 : : // use simple readline
282 : :
283 : : for (;;) {
284 : : char *line = prompt((char *)mp_repl_get_ps1());
285 : : if (line == NULL) {
286 : : // EOF
287 : : return 0;
288 : : }
289 : : while (mp_repl_continue_with_input(line)) {
290 : : char *line2 = prompt((char *)mp_repl_get_ps2());
291 : : if (line2 == NULL) {
292 : : break;
293 : : }
294 : : char *line3 = strjoin(line, '\n', line2);
295 : : free(line);
296 : : free(line2);
297 : : line = line3;
298 : : }
299 : :
300 : : int ret = execute_from_lexer(LEX_SRC_STR, line, MP_PARSE_SINGLE_INPUT, true);
301 : : free(line);
302 : : if (ret & FORCED_EXIT) {
303 : : return ret;
304 : : }
305 : : }
306 : :
307 : : #endif
308 : : }
309 : :
310 : 2064 : static int do_file(const char *file) {
311 : 2064 : return execute_from_lexer(LEX_SRC_FILENAME, file, MP_PARSE_FILE_INPUT, false);
312 : : }
313 : :
314 : 2 : static int do_str(const char *str) {
315 : 2 : return execute_from_lexer(LEX_SRC_STR, str, MP_PARSE_FILE_INPUT, false);
316 : : }
317 : :
318 : 0 : static void print_help(char **argv) {
319 : 0 : printf(
320 : : "usage: %s [<opts>] [-X <implopt>] [-c <command> | -m <module> | <filename>]\n"
321 : : "Options:\n"
322 : : "--version : show version information\n"
323 : : "-h : print this help message\n"
324 : : "-i : enable inspection via REPL after running command/module/file\n"
325 : : #if MICROPY_DEBUG_PRINTERS
326 : : "-v : verbose (trace various operations); can be multiple\n"
327 : : #endif
328 : : "-O[N] : apply bytecode optimizations of level N\n"
329 : : "\n"
330 : : "Implementation specific options (-X):\n", argv[0]
331 : : );
332 : 0 : int impl_opts_cnt = 0;
333 : 0 : printf(
334 : : " compile-only -- parse and compile only\n"
335 : : #if MICROPY_EMIT_NATIVE
336 : : " emit={bytecode,native,viper} -- set the default code emitter\n"
337 : : #else
338 : : " emit=bytecode -- set the default code emitter\n"
339 : : #endif
340 : : );
341 : 0 : impl_opts_cnt++;
342 : : #if MICROPY_ENABLE_GC
343 : 0 : printf(
344 : : " heapsize=<n>[w][K|M] -- set the heap size for the GC (default %ld)\n"
345 : : , heap_size);
346 : 0 : impl_opts_cnt++;
347 : : #endif
348 : : #if defined(__APPLE__)
349 : : printf(" realtime -- set thread priority to realtime\n");
350 : : impl_opts_cnt++;
351 : : #endif
352 : :
353 : 0 : if (impl_opts_cnt == 0) {
354 : : printf(" (none)\n");
355 : : }
356 : 0 : }
357 : :
358 : 0 : static int invalid_args(void) {
359 : 0 : fprintf(stderr, "Invalid command line arguments. Use -h option for help.\n");
360 : 0 : return 1;
361 : : }
362 : :
363 : : // Process options which set interpreter init options
364 : 3456 : static void pre_process_options(int argc, char **argv) {
365 [ + + ]: 6794 : for (int a = 1; a < argc; a++) {
366 [ + + ]: 6769 : if (argv[a][0] == '-') {
367 [ + + + + ]: 4705 : if (strcmp(argv[a], "-c") == 0 || strcmp(argv[a], "-m") == 0) {
368 : : break; // Everything after this is a command/module and arguments for it
369 : : }
370 [ - + ]: 3338 : if (strcmp(argv[a], "-h") == 0) {
371 : 0 : print_help(argv);
372 : 0 : exit(0);
373 : : }
374 [ - + ]: 3338 : if (strcmp(argv[a], "--version") == 0) {
375 : 0 : printf(MICROPY_BANNER_NAME_AND_VERSION "; " MICROPY_BANNER_MACHINE "\n");
376 : 0 : exit(0);
377 : : }
378 [ + + ]: 3338 : if (strcmp(argv[a], "-X") == 0) {
379 [ - + ]: 3312 : if (a + 1 >= argc) {
380 : 0 : exit(invalid_args());
381 : : }
382 : 3312 : if (0) {
383 [ - + ]: 3312 : } else if (strcmp(argv[a + 1], "compile-only") == 0) {
384 : 0 : compile_only = true;
385 [ + + ]: 3312 : } else if (strcmp(argv[a + 1], "emit=bytecode") == 0) {
386 : 1688 : emit_opt = MP_EMIT_OPT_BYTECODE;
387 : : #if MICROPY_EMIT_NATIVE
388 [ + - ]: 1624 : } else if (strcmp(argv[a + 1], "emit=native") == 0) {
389 : 1624 : emit_opt = MP_EMIT_OPT_NATIVE_PYTHON;
390 [ # # ]: 0 : } else if (strcmp(argv[a + 1], "emit=viper") == 0) {
391 : 0 : emit_opt = MP_EMIT_OPT_VIPER;
392 : : #endif
393 : : #if MICROPY_ENABLE_GC
394 [ # # ]: 0 : } else if (strncmp(argv[a + 1], "heapsize=", sizeof("heapsize=") - 1) == 0) {
395 : 0 : char *end;
396 : 0 : heap_size = strtol(argv[a + 1] + sizeof("heapsize=") - 1, &end, 0);
397 : : // Don't bring unneeded libc dependencies like tolower()
398 : : // If there's 'w' immediately after number, adjust it for
399 : : // target word size. Note that it should be *before* size
400 : : // suffix like K or M, to avoid confusion with kilowords,
401 : : // etc. the size is still in bytes, just can be adjusted
402 : : // for word size (taking 32bit as baseline).
403 : 0 : bool word_adjust = false;
404 [ # # ]: 0 : if ((*end | 0x20) == 'w') {
405 : 0 : word_adjust = true;
406 : 0 : end++;
407 : : }
408 [ # # ]: 0 : if ((*end | 0x20) == 'k') {
409 : 0 : heap_size *= 1024;
410 [ # # ]: 0 : } else if ((*end | 0x20) == 'm') {
411 : 0 : heap_size *= 1024 * 1024;
412 : : } else {
413 : : // Compensate for ++ below
414 : 0 : --end;
415 : : }
416 [ # # ]: 0 : if (*++end != 0) {
417 : 0 : goto invalid_arg;
418 : : }
419 [ # # ]: 0 : if (word_adjust) {
420 : 0 : heap_size = heap_size * MP_BYTES_PER_OBJ_WORD / 4;
421 : : }
422 : : // If requested size too small, we'll crash anyway
423 [ # # ]: 0 : if (heap_size < 700) {
424 : 0 : goto invalid_arg;
425 : : }
426 : : #endif
427 : : #if defined(__APPLE__)
428 : : } else if (strcmp(argv[a + 1], "realtime") == 0) {
429 : : #if MICROPY_PY_THREAD
430 : : mp_thread_is_realtime_enabled = true;
431 : : #endif
432 : : // main thread was already initialized before the option
433 : : // was parsed, so we have to enable realtime here.
434 : : mp_thread_set_realtime();
435 : : #endif
436 : : } else {
437 : 0 : invalid_arg:
438 : 0 : exit(invalid_args());
439 : : }
440 : : a++;
441 : : }
442 : : } else {
443 : : break; // Not an option but a file
444 : : }
445 : : }
446 : 3456 : }
447 : :
448 : 3433 : static void set_sys_argv(char *argv[], int argc, int start_arg) {
449 [ + + ]: 6864 : for (int i = start_arg; i < argc; i++) {
450 : 3431 : mp_obj_list_append(mp_sys_argv, MP_OBJ_NEW_QSTR(qstr_from_str(argv[i])));
451 : : }
452 : 3433 : }
453 : :
454 : : #if MICROPY_PY_SYS_EXECUTABLE
455 : : extern mp_obj_str_t mp_sys_executable_obj;
456 : : static char *executable_path = NULL;
457 : :
458 : 3456 : static void sys_set_excecutable(char *argv0) {
459 [ + - ]: 3456 : if (executable_path == NULL) {
460 : 3456 : executable_path = realpath(argv0, NULL);
461 : : }
462 [ + - ]: 3456 : if (executable_path != NULL) {
463 : 3456 : mp_obj_str_set_data(&mp_sys_executable_obj, (byte *)executable_path, strlen(executable_path));
464 : : }
465 : 3456 : }
466 : : #endif
467 : :
468 : : #ifdef _WIN32
469 : : #define PATHLIST_SEP_CHAR ';'
470 : : #else
471 : : #define PATHLIST_SEP_CHAR ':'
472 : : #endif
473 : :
474 : : MP_NOINLINE int main_(int argc, char **argv);
475 : :
476 : 3456 : int main(int argc, char **argv) {
477 : : #if MICROPY_PY_THREAD
478 : 3456 : mp_thread_init();
479 : : #endif
480 : :
481 : : // Define a reasonable stack limit to detect stack overflow.
482 : 3456 : mp_uint_t stack_size = 40000 * (sizeof(void *) / 4);
483 : : #if defined(__arm__) && !defined(__thumb2__)
484 : : // ARM (non-Thumb) architectures require more stack.
485 : : stack_size *= 2;
486 : : #endif
487 : :
488 : : // We should capture stack top ASAP after start, and it should be
489 : : // captured guaranteedly before any other stack variables are allocated.
490 : : // For this, actual main (renamed main_) should not be inlined into
491 : : // this function. main_() itself may have other functions inlined (with
492 : : // their own stack variables), that's why we need this main/main_ split.
493 : 3456 : mp_cstack_init_with_sp_here(stack_size);
494 : 3456 : return main_(argc, argv);
495 : : }
496 : :
497 : 3456 : MP_NOINLINE int main_(int argc, char **argv) {
498 : : #ifdef SIGPIPE
499 : : // Do not raise SIGPIPE, instead return EPIPE. Otherwise, e.g. writing
500 : : // to peer-closed socket will lead to sudden termination of MicroPython
501 : : // process. SIGPIPE is particularly nasty, because unix shell doesn't
502 : : // print anything for it, so the above looks like completely sudden and
503 : : // silent termination for unknown reason. Ignoring SIGPIPE is also what
504 : : // CPython does. Note that this may lead to problems using MicroPython
505 : : // scripts as pipe filters, but again, that's what CPython does. So,
506 : : // scripts which want to follow unix shell pipe semantics (where SIGPIPE
507 : : // means "pipe was requested to terminate, it's not an error"), should
508 : : // catch EPIPE themselves.
509 : 3456 : signal(SIGPIPE, SIG_IGN);
510 : : #endif
511 : :
512 : 3456 : pre_process_options(argc, argv);
513 : :
514 : : #if MICROPY_ENABLE_GC
515 : : #if !MICROPY_GC_SPLIT_HEAP
516 : : char *heap = malloc(heap_size);
517 : : gc_init(heap, heap + heap_size);
518 : : #else
519 : 3456 : assert(MICROPY_GC_SPLIT_HEAP_N_HEAPS > 0);
520 : 3456 : char *heaps[MICROPY_GC_SPLIT_HEAP_N_HEAPS];
521 : 3456 : long multi_heap_size = heap_size / MICROPY_GC_SPLIT_HEAP_N_HEAPS;
522 [ + + ]: 17280 : for (size_t i = 0; i < MICROPY_GC_SPLIT_HEAP_N_HEAPS; i++) {
523 : 13824 : heaps[i] = malloc(multi_heap_size);
524 [ + + ]: 13824 : if (i == 0) {
525 : 3456 : gc_init(heaps[i], heaps[i] + multi_heap_size);
526 : : } else {
527 : 10368 : gc_add(heaps[i], heaps[i] + multi_heap_size);
528 : : }
529 : : }
530 : : #endif
531 : : #endif
532 : :
533 : : #if MICROPY_ENABLE_PYSTACK
534 : : static mp_obj_t pystack[1024];
535 : : mp_pystack_init(pystack, &pystack[MP_ARRAY_SIZE(pystack)]);
536 : : #endif
537 : :
538 : 3456 : mp_init();
539 : :
540 : : #if MICROPY_EMIT_NATIVE
541 : : // Set default emitter options
542 : 3456 : MP_STATE_VM(default_emit_opt) = emit_opt;
543 : : #else
544 : : (void)emit_opt;
545 : : #endif
546 : :
547 : : #if MICROPY_VFS_POSIX
548 : : {
549 : : // Mount the host FS at the root of our internal VFS
550 : 6912 : mp_obj_t args[2] = {
551 : 3456 : MP_OBJ_TYPE_GET_SLOT(&mp_type_vfs_posix, make_new)(&mp_type_vfs_posix, 0, 0, NULL),
552 : : MP_OBJ_NEW_QSTR(MP_QSTR__slash_),
553 : : };
554 : 3456 : mp_vfs_mount(2, args, (mp_map_t *)&mp_const_empty_map);
555 : :
556 : : // Make sure the root that was just mounted is the current VFS (it's always at
557 : : // the end of the linked list). Can't use chdir('/') because that will change
558 : : // the current path within the VfsPosix object.
559 : 3456 : MP_STATE_VM(vfs_cur) = MP_STATE_VM(vfs_mount_table);
560 [ + + ]: 6912 : while (MP_STATE_VM(vfs_cur)->next != NULL) {
561 : 3456 : MP_STATE_VM(vfs_cur) = MP_STATE_VM(vfs_cur)->next;
562 : : }
563 : : }
564 : : #endif
565 : :
566 : : {
567 : : // sys.path starts as [""]
568 : 3456 : mp_sys_path = mp_obj_new_list(0, NULL);
569 : 3456 : mp_obj_list_append(mp_sys_path, MP_OBJ_NEW_QSTR(MP_QSTR_));
570 : :
571 : : // Add colon-separated entries from MICROPYPATH.
572 : 3456 : char *home = getenv("HOME");
573 : 3456 : char *path = getenv("MICROPYPATH");
574 [ + + ]: 3456 : if (path == NULL) {
575 : 21 : path = MICROPY_PY_SYS_PATH_DEFAULT;
576 : : }
577 [ - + ]: 3456 : if (*path == PATHLIST_SEP_CHAR) {
578 : : // First entry is empty. We've already added an empty entry to sys.path, so skip it.
579 : 0 : ++path;
580 : : }
581 : : // GCC targeting RISC-V 64 reports a warning about `path_remaining` being clobbered by
582 : : // either setjmp or vfork if that variable it is allocated on the stack. This may
583 : : // probably be a compiler error as it occurs on a few recent GCC releases (up to 14.1.0)
584 : : // but LLVM doesn't report any warnings.
585 : 3456 : static bool path_remaining;
586 : 3456 : path_remaining = *path;
587 [ + + ]: 13824 : while (path_remaining) {
588 : 10368 : char *path_entry_end = strchr(path, PATHLIST_SEP_CHAR);
589 [ + + ]: 10368 : if (path_entry_end == NULL) {
590 : 3456 : path_entry_end = path + strlen(path);
591 : 3456 : path_remaining = false;
592 : : }
593 [ + + + - : 10389 : if (path[0] == '~' && path[1] == '/' && home != NULL) {
+ - ]
594 : : // Expand standalone ~ to $HOME
595 : 21 : int home_l = strlen(home);
596 : 21 : vstr_t vstr;
597 : 21 : vstr_init(&vstr, home_l + (path_entry_end - path - 1) + 1);
598 : 21 : vstr_add_strn(&vstr, home, home_l);
599 : 21 : vstr_add_strn(&vstr, path + 1, path_entry_end - path - 1);
600 : 21 : mp_obj_list_append(mp_sys_path, mp_obj_new_str_from_vstr(&vstr));
601 : : } else {
602 : 10347 : mp_obj_list_append(mp_sys_path, mp_obj_new_str_via_qstr(path, path_entry_end - path));
603 : : }
604 : 10368 : path = path_entry_end + 1;
605 : : }
606 : : }
607 : :
608 : 3456 : mp_obj_list_init(MP_OBJ_TO_PTR(mp_sys_argv), 0);
609 : :
610 : : #if defined(MICROPY_UNIX_COVERAGE)
611 : : {
612 : 3456 : MP_DECLARE_CONST_FUN_OBJ_0(extra_coverage_obj);
613 : 3456 : MP_DECLARE_CONST_FUN_OBJ_0(extra_cpp_coverage_obj);
614 : 3456 : mp_store_global(MP_QSTR_extra_coverage, MP_OBJ_FROM_PTR(&extra_coverage_obj));
615 : 3456 : mp_store_global(MP_QSTR_extra_cpp_coverage, MP_OBJ_FROM_PTR(&extra_cpp_coverage_obj));
616 : : }
617 : : #endif
618 : :
619 : : // Here is some example code to create a class and instance of that class.
620 : : // First is the Python, then the C code.
621 : : //
622 : : // class TestClass:
623 : : // pass
624 : : // test_obj = TestClass()
625 : : // test_obj.attr = 42
626 : : //
627 : : // mp_obj_t test_class_type, test_class_instance;
628 : : // test_class_type = mp_obj_new_type(qstr_from_str("TestClass"), mp_const_empty_tuple, mp_obj_new_dict(0));
629 : : // mp_store_name(qstr_from_str("test_obj"), test_class_instance = mp_call_function_0(test_class_type));
630 : : // mp_store_attr(test_class_instance, qstr_from_str("attr"), mp_obj_new_int(42));
631 : :
632 : : /*
633 : : printf("bytes:\n");
634 : : printf(" total %d\n", m_get_total_bytes_allocated());
635 : : printf(" cur %d\n", m_get_current_bytes_allocated());
636 : : printf(" peak %d\n", m_get_peak_bytes_allocated());
637 : : */
638 : :
639 : : #if MICROPY_PY_SYS_EXECUTABLE
640 : 3456 : sys_set_excecutable(argv[0]);
641 : : #endif
642 : :
643 : 3456 : const int NOTHING_EXECUTED = -2;
644 : 3456 : int ret = NOTHING_EXECUTED;
645 : 3456 : bool inspect = false;
646 [ + + ]: 6794 : for (int a = 1; a < argc; a++) {
647 [ + + ]: 6769 : if (argv[a][0] == '-') {
648 [ + + ]: 4705 : if (strcmp(argv[a], "-i") == 0) {
649 : : inspect = true;
650 [ + + ]: 4703 : } else if (strcmp(argv[a], "-c") == 0) {
651 [ - + ]: 2 : if (a + 1 >= argc) {
652 : 0 : return invalid_args();
653 : : }
654 : 2 : set_sys_argv(argv, a + 1, a); // The -c becomes first item of sys.argv, as in CPython
655 : 2 : set_sys_argv(argv, argc, a + 2); // Then what comes after the command
656 : 2 : ret = do_str(argv[a + 1]);
657 : 2 : break;
658 [ + + ]: 4701 : } else if (strcmp(argv[a], "-m") == 0) {
659 [ - + ]: 1365 : if (a + 1 >= argc) {
660 : 7 : return invalid_args();
661 : : }
662 : 1365 : mp_obj_t import_args[4];
663 : 1365 : import_args[0] = mp_obj_new_str_from_cstr(argv[a + 1]);
664 : 1365 : import_args[1] = import_args[2] = mp_const_none;
665 : : // Ask __import__ to handle imported module specially - set its __name__
666 : : // to __main__, and also return this leaf module, not top-level package
667 : : // containing it.
668 : 1365 : import_args[3] = mp_const_false;
669 : : // TODO: https://docs.python.org/3/using/cmdline.html#cmdoption-m :
670 : : // "the first element of sys.argv will be the full path to
671 : : // the module file (while the module file is being located,
672 : : // the first element will be set to "-m")."
673 : 1365 : set_sys_argv(argv, argc, a + 1);
674 : :
675 : 1365 : mp_obj_t mod;
676 : 1365 : nlr_buf_t nlr;
677 : :
678 : : // Allocating subpkg_tried on the stack can lead to compiler warnings about this
679 : : // variable being clobbered when nlr is implemented using setjmp/longjmp. Its
680 : : // value must be preserved across calls to setjmp/longjmp.
681 : 1365 : static bool subpkg_tried;
682 : 1365 : subpkg_tried = false;
683 : :
684 : 1365 : reimport:
685 [ + + ]: 1365 : if (nlr_push(&nlr) == 0) {
686 : 1365 : mod = mp_builtin___import__(MP_ARRAY_SIZE(import_args), import_args);
687 : 1358 : nlr_pop();
688 : : } else {
689 : : // uncaught exception
690 : 7 : return handle_uncaught_exception(nlr.ret_val) & 0xff;
691 : : }
692 : :
693 : : // If this module is a package, see if it has a `__main__.py`.
694 : 1358 : mp_obj_t dest[2];
695 : 1358 : mp_load_method_protected(mod, MP_QSTR___path__, dest, true);
696 [ - + - - ]: 1358 : if (dest[0] != MP_OBJ_NULL && !subpkg_tried) {
697 : 0 : subpkg_tried = true;
698 : 0 : vstr_t vstr;
699 : 0 : int len = strlen(argv[a + 1]);
700 : 0 : vstr_init(&vstr, len + sizeof(".__main__"));
701 : 0 : vstr_add_strn(&vstr, argv[a + 1], len);
702 : 0 : vstr_add_strn(&vstr, ".__main__", sizeof(".__main__") - 1);
703 : 0 : import_args[0] = mp_obj_new_str_from_vstr(&vstr);
704 : 0 : goto reimport;
705 : : }
706 : :
707 : 1358 : ret = 0;
708 : 1358 : break;
709 [ + + ]: 3336 : } else if (strcmp(argv[a], "-X") == 0) {
710 : 3312 : a += 1;
711 : : #if MICROPY_DEBUG_PRINTERS
712 [ + + ]: 24 : } else if (strcmp(argv[a], "-v") == 0) {
713 : 22 : mp_verbose_flag++;
714 : : #endif
715 [ + - ]: 2 : } else if (strncmp(argv[a], "-O", 2) == 0) {
716 [ - + ]: 2 : if (unichar_isdigit(argv[a][2])) {
717 : 0 : MP_STATE_VM(mp_optimise_value) = argv[a][2] & 0xf;
718 : : } else {
719 : 2 : MP_STATE_VM(mp_optimise_value) = 0;
720 [ + + ]: 4 : for (char *p = argv[a] + 1; *p && *p == 'O'; p++, MP_STATE_VM(mp_optimise_value)++) {;
721 : : }
722 : : }
723 : : } else {
724 : 0 : return invalid_args();
725 : : }
726 : : } else {
727 : 2064 : char *basedir = realpath(argv[a], NULL);
728 [ - + ]: 2064 : if (basedir == NULL) {
729 : 0 : mp_printf(&mp_stderr_print, "%s: can't open file '%s': [Errno %d] %s\n", argv[0], argv[a], errno, strerror(errno));
730 : : // CPython exits with 2 in such case
731 : 0 : ret = 2;
732 : 0 : break;
733 : : }
734 : :
735 : : // Set base dir of the script as first entry in sys.path.
736 : 2064 : char *p = strrchr(basedir, '/');
737 : 2064 : mp_obj_list_store(mp_sys_path, MP_OBJ_NEW_SMALL_INT(0), mp_obj_new_str_via_qstr(basedir, p - basedir));
738 : 2064 : free(basedir);
739 : :
740 : 2064 : set_sys_argv(argv, argc, a);
741 : 2064 : ret = do_file(argv[a]);
742 : 2064 : break;
743 : : }
744 : : }
745 : :
746 : 3449 : const char *inspect_env = getenv("MICROPYINSPECT");
747 [ + + + - ]: 3449 : if (inspect_env && inspect_env[0] != '\0') {
748 : 2 : inspect = true;
749 : : }
750 [ + + ]: 3449 : if (ret == NOTHING_EXECUTED || inspect) {
751 [ + + - + ]: 29 : if (isatty(0) || inspect) {
752 : 28 : prompt_read_history();
753 : 28 : ret = do_repl();
754 : 28 : prompt_write_history();
755 : : } else {
756 : 1 : ret = execute_from_lexer(LEX_SRC_STDIN, NULL, MP_PARSE_FILE_INPUT, false);
757 : : }
758 : : }
759 : :
760 : : #if MICROPY_PY_SYS_SETTRACE
761 : : MP_STATE_THREAD(prof_trace_callback) = MP_OBJ_NULL;
762 : : #endif
763 : :
764 : : #if MICROPY_PY_SYS_ATEXIT
765 : : // Beware, the sys.settrace callback should be disabled before running sys.atexit.
766 [ + + ]: 3449 : if (mp_obj_is_callable(MP_STATE_VM(sys_exitfunc))) {
767 : 2 : mp_call_function_0(MP_STATE_VM(sys_exitfunc));
768 : : }
769 : : #endif
770 : :
771 : : #if MICROPY_PY_MICROPYTHON_MEM_INFO
772 [ + + ]: 3449 : if (mp_verbose_flag) {
773 : 10 : mp_micropython_mem_info(0, NULL);
774 : : }
775 : : #endif
776 : :
777 : : #if MICROPY_PY_BLUETOOTH
778 : : void mp_bluetooth_deinit(void);
779 : : mp_bluetooth_deinit();
780 : : #endif
781 : :
782 : : #if MICROPY_PY_THREAD
783 : 3449 : mp_thread_deinit();
784 : : #endif
785 : :
786 : : #if defined(MICROPY_UNIX_COVERAGE)
787 : 3449 : gc_sweep_all();
788 : : #endif
789 : :
790 : 3449 : mp_deinit();
791 : :
792 : : #if MICROPY_ENABLE_GC && !defined(NDEBUG)
793 : : // We don't really need to free memory since we are about to exit the
794 : : // process, but doing so helps to find memory leaks.
795 : : #if !MICROPY_GC_SPLIT_HEAP
796 : : free(heap);
797 : : #else
798 [ + + ]: 17245 : for (size_t i = 0; i < MICROPY_GC_SPLIT_HEAP_N_HEAPS; i++) {
799 : 13796 : free(heaps[i]);
800 : : }
801 : : #endif
802 : : #endif
803 : :
804 : : #if MICROPY_PY_SYS_EXECUTABLE && !defined(NDEBUG)
805 : : // Again, make memory leak detector happy
806 : 3449 : free(executable_path);
807 : : #endif
808 : :
809 : : // printf("total bytes = %d\n", m_get_total_bytes_allocated());
810 : 3449 : return ret & 0xff;
811 : : }
812 : :
813 : 0 : void nlr_jump_fail(void *val) {
814 : : #if MICROPY_USE_READLINE == 1
815 : 0 : mp_hal_stdio_mode_orig();
816 : : #endif
817 : 0 : fprintf(stderr, "FATAL: uncaught NLR %p\n", val);
818 : 0 : exit(1);
819 : : }
820 : :
821 : : #if MICROPY_VFS_ROM_IOCTL
822 : :
823 : : static uint8_t romfs_buf[4] = { 0xd2, 0xcd, 0x31, 0x00 }; // empty ROMFS
824 : : static const MP_DEFINE_MEMORYVIEW_OBJ(romfs_obj, 'B', 0, sizeof(romfs_buf), romfs_buf);
825 : :
826 : 3456 : mp_obj_t mp_vfs_rom_ioctl(size_t n_args, const mp_obj_t *args) {
827 [ + - - ]: 3456 : switch (mp_obj_get_int(args[0])) {
828 : : case MP_VFS_ROM_IOCTL_GET_NUMBER_OF_SEGMENTS:
829 : : return MP_OBJ_NEW_SMALL_INT(1);
830 : :
831 : 3456 : case MP_VFS_ROM_IOCTL_GET_SEGMENT:
832 : 3456 : return MP_OBJ_FROM_PTR(&romfs_obj);
833 : : }
834 : :
835 : 0 : return MP_OBJ_NEW_SMALL_INT(-MP_EINVAL);
836 : : }
837 : :
838 : : #endif
|