main.c 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683
  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. *
  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. #include <stdint.h>
  27. #include <stdbool.h>
  28. #include <stdio.h>
  29. #include <string.h>
  30. #include <stdlib.h>
  31. #include <stdarg.h>
  32. #include <unistd.h>
  33. #include <ctype.h>
  34. #include <sys/stat.h>
  35. #include <sys/types.h>
  36. #include <errno.h>
  37. #include <signal.h>
  38. #include "py/compile.h"
  39. #include "py/runtime.h"
  40. #include "py/builtin.h"
  41. #include "py/repl.h"
  42. #include "py/gc.h"
  43. #include "py/stackctrl.h"
  44. #include "py/mphal.h"
  45. #include "py/mpthread.h"
  46. #include "extmod/misc.h"
  47. #include "extmod/vfs.h"
  48. #include "extmod/vfs_posix.h"
  49. #include "genhdr/mpversion.h"
  50. #include "input.h"
  51. // Command line options, with their defaults
  52. STATIC bool compile_only = false;
  53. STATIC uint emit_opt = MP_EMIT_OPT_NONE;
  54. #if MICROPY_ENABLE_GC
  55. // Heap size of GC heap (if enabled)
  56. // Make it larger on a 64 bit machine, because pointers are larger.
  57. long heap_size = 1024*1024 * (sizeof(mp_uint_t) / 4);
  58. #endif
  59. STATIC void stderr_print_strn(void *env, const char *str, size_t len) {
  60. (void)env;
  61. ssize_t dummy = write(STDERR_FILENO, str, len);
  62. mp_uos_dupterm_tx_strn(str, len);
  63. (void)dummy;
  64. }
  65. const mp_print_t mp_stderr_print = {NULL, stderr_print_strn};
  66. #define FORCED_EXIT (0x100)
  67. // If exc is SystemExit, return value where FORCED_EXIT bit set,
  68. // and lower 8 bits are SystemExit value. For all other exceptions,
  69. // return 1.
  70. STATIC int handle_uncaught_exception(mp_obj_base_t *exc) {
  71. // check for SystemExit
  72. if (mp_obj_is_subclass_fast(MP_OBJ_FROM_PTR(exc->type), MP_OBJ_FROM_PTR(&mp_type_SystemExit))) {
  73. // None is an exit value of 0; an int is its value; anything else is 1
  74. mp_obj_t exit_val = mp_obj_exception_get_value(MP_OBJ_FROM_PTR(exc));
  75. mp_int_t val = 0;
  76. if (exit_val != mp_const_none && !mp_obj_get_int_maybe(exit_val, &val)) {
  77. val = 1;
  78. }
  79. return FORCED_EXIT | (val & 255);
  80. }
  81. // Report all other exceptions
  82. mp_obj_print_exception(&mp_stderr_print, MP_OBJ_FROM_PTR(exc));
  83. return 1;
  84. }
  85. #define LEX_SRC_STR (1)
  86. #define LEX_SRC_VSTR (2)
  87. #define LEX_SRC_FILENAME (3)
  88. #define LEX_SRC_STDIN (4)
  89. // Returns standard error codes: 0 for success, 1 for all other errors,
  90. // except if FORCED_EXIT bit is set then script raised SystemExit and the
  91. // value of the exit is in the lower 8 bits of the return value
  92. STATIC int execute_from_lexer(int source_kind, const void *source, mp_parse_input_kind_t input_kind, bool is_repl) {
  93. mp_hal_set_interrupt_char(CHAR_CTRL_C);
  94. nlr_buf_t nlr;
  95. if (nlr_push(&nlr) == 0) {
  96. // create lexer based on source kind
  97. mp_lexer_t *lex;
  98. if (source_kind == LEX_SRC_STR) {
  99. const char *line = source;
  100. lex = mp_lexer_new_from_str_len(MP_QSTR__lt_stdin_gt_, line, strlen(line), false);
  101. } else if (source_kind == LEX_SRC_VSTR) {
  102. const vstr_t *vstr = source;
  103. lex = mp_lexer_new_from_str_len(MP_QSTR__lt_stdin_gt_, vstr->buf, vstr->len, false);
  104. } else if (source_kind == LEX_SRC_FILENAME) {
  105. lex = mp_lexer_new_from_file((const char*)source);
  106. } else { // LEX_SRC_STDIN
  107. lex = mp_lexer_new_from_fd(MP_QSTR__lt_stdin_gt_, 0, false);
  108. }
  109. qstr source_name = lex->source_name;
  110. #if MICROPY_PY___FILE__
  111. if (input_kind == MP_PARSE_FILE_INPUT) {
  112. mp_store_global(MP_QSTR___file__, MP_OBJ_NEW_QSTR(source_name));
  113. }
  114. #endif
  115. mp_parse_tree_t parse_tree = mp_parse(lex, input_kind);
  116. #if defined(MICROPY_UNIX_COVERAGE)
  117. // allow to print the parse tree in the coverage build
  118. if (mp_verbose_flag >= 3) {
  119. printf("----------------\n");
  120. mp_parse_node_print(parse_tree.root, 0);
  121. printf("----------------\n");
  122. }
  123. #endif
  124. mp_obj_t module_fun = mp_compile(&parse_tree, source_name, emit_opt, is_repl);
  125. if (!compile_only) {
  126. // execute it
  127. mp_call_function_0(module_fun);
  128. // check for pending exception
  129. if (MP_STATE_VM(mp_pending_exception) != MP_OBJ_NULL) {
  130. mp_obj_t obj = MP_STATE_VM(mp_pending_exception);
  131. MP_STATE_VM(mp_pending_exception) = MP_OBJ_NULL;
  132. nlr_raise(obj);
  133. }
  134. }
  135. mp_hal_set_interrupt_char(-1);
  136. nlr_pop();
  137. return 0;
  138. } else {
  139. // uncaught exception
  140. mp_hal_set_interrupt_char(-1);
  141. return handle_uncaught_exception(nlr.ret_val);
  142. }
  143. }
  144. #if MICROPY_USE_READLINE == 1
  145. #include "lib/mp-readline/readline.h"
  146. #else
  147. STATIC char *strjoin(const char *s1, int sep_char, const char *s2) {
  148. int l1 = strlen(s1);
  149. int l2 = strlen(s2);
  150. char *s = malloc(l1 + l2 + 2);
  151. memcpy(s, s1, l1);
  152. if (sep_char != 0) {
  153. s[l1] = sep_char;
  154. l1 += 1;
  155. }
  156. memcpy(s + l1, s2, l2);
  157. s[l1 + l2] = 0;
  158. return s;
  159. }
  160. #endif
  161. STATIC int do_repl(void) {
  162. mp_hal_stdout_tx_str("MicroPython " MICROPY_GIT_TAG " on " MICROPY_BUILD_DATE "; "
  163. MICROPY_PY_SYS_PLATFORM " version\nUse Ctrl-D to exit, Ctrl-E for paste mode\n");
  164. #if MICROPY_USE_READLINE == 1
  165. // use MicroPython supplied readline
  166. vstr_t line;
  167. vstr_init(&line, 16);
  168. for (;;) {
  169. mp_hal_stdio_mode_raw();
  170. input_restart:
  171. vstr_reset(&line);
  172. int ret = readline(&line, ">>> ");
  173. mp_parse_input_kind_t parse_input_kind = MP_PARSE_SINGLE_INPUT;
  174. if (ret == CHAR_CTRL_C) {
  175. // cancel input
  176. mp_hal_stdout_tx_str("\r\n");
  177. goto input_restart;
  178. } else if (ret == CHAR_CTRL_D) {
  179. // EOF
  180. printf("\n");
  181. mp_hal_stdio_mode_orig();
  182. vstr_clear(&line);
  183. return 0;
  184. } else if (ret == CHAR_CTRL_E) {
  185. // paste mode
  186. mp_hal_stdout_tx_str("\npaste mode; Ctrl-C to cancel, Ctrl-D to finish\n=== ");
  187. vstr_reset(&line);
  188. for (;;) {
  189. char c = mp_hal_stdin_rx_chr();
  190. if (c == CHAR_CTRL_C) {
  191. // cancel everything
  192. mp_hal_stdout_tx_str("\n");
  193. goto input_restart;
  194. } else if (c == CHAR_CTRL_D) {
  195. // end of input
  196. mp_hal_stdout_tx_str("\n");
  197. break;
  198. } else {
  199. // add char to buffer and echo
  200. vstr_add_byte(&line, c);
  201. if (c == '\r') {
  202. mp_hal_stdout_tx_str("\n=== ");
  203. } else {
  204. mp_hal_stdout_tx_strn(&c, 1);
  205. }
  206. }
  207. }
  208. parse_input_kind = MP_PARSE_FILE_INPUT;
  209. } else if (line.len == 0) {
  210. if (ret != 0) {
  211. printf("\n");
  212. }
  213. goto input_restart;
  214. } else {
  215. // got a line with non-zero length, see if it needs continuing
  216. while (mp_repl_continue_with_input(vstr_null_terminated_str(&line))) {
  217. vstr_add_byte(&line, '\n');
  218. ret = readline(&line, "... ");
  219. if (ret == CHAR_CTRL_C) {
  220. // cancel everything
  221. printf("\n");
  222. goto input_restart;
  223. } else if (ret == CHAR_CTRL_D) {
  224. // stop entering compound statement
  225. break;
  226. }
  227. }
  228. }
  229. mp_hal_stdio_mode_orig();
  230. ret = execute_from_lexer(LEX_SRC_VSTR, &line, parse_input_kind, true);
  231. if (ret & FORCED_EXIT) {
  232. return ret;
  233. }
  234. }
  235. #else
  236. // use simple readline
  237. for (;;) {
  238. char *line = prompt(">>> ");
  239. if (line == NULL) {
  240. // EOF
  241. return 0;
  242. }
  243. while (mp_repl_continue_with_input(line)) {
  244. char *line2 = prompt("... ");
  245. if (line2 == NULL) {
  246. break;
  247. }
  248. char *line3 = strjoin(line, '\n', line2);
  249. free(line);
  250. free(line2);
  251. line = line3;
  252. }
  253. int ret = execute_from_lexer(LEX_SRC_STR, line, MP_PARSE_SINGLE_INPUT, true);
  254. if (ret & FORCED_EXIT) {
  255. return ret;
  256. }
  257. free(line);
  258. }
  259. #endif
  260. }
  261. STATIC int do_file(const char *file) {
  262. return execute_from_lexer(LEX_SRC_FILENAME, file, MP_PARSE_FILE_INPUT, false);
  263. }
  264. STATIC int do_str(const char *str) {
  265. return execute_from_lexer(LEX_SRC_STR, str, MP_PARSE_FILE_INPUT, false);
  266. }
  267. STATIC int usage(char **argv) {
  268. printf(
  269. "usage: %s [<opts>] [-X <implopt>] [-c <command>] [<filename>]\n"
  270. "Options:\n"
  271. "-v : verbose (trace various operations); can be multiple\n"
  272. "-O[N] : apply bytecode optimizations of level N\n"
  273. "\n"
  274. "Implementation specific options (-X):\n", argv[0]
  275. );
  276. int impl_opts_cnt = 0;
  277. printf(
  278. " compile-only -- parse and compile only\n"
  279. " emit={bytecode,native,viper} -- set the default code emitter\n"
  280. );
  281. impl_opts_cnt++;
  282. #if MICROPY_ENABLE_GC
  283. printf(
  284. " heapsize=<n>[w][K|M] -- set the heap size for the GC (default %ld)\n"
  285. , heap_size);
  286. impl_opts_cnt++;
  287. #endif
  288. if (impl_opts_cnt == 0) {
  289. printf(" (none)\n");
  290. }
  291. return 1;
  292. }
  293. // Process options which set interpreter init options
  294. STATIC void pre_process_options(int argc, char **argv) {
  295. for (int a = 1; a < argc; a++) {
  296. if (argv[a][0] == '-') {
  297. if (strcmp(argv[a], "-X") == 0) {
  298. if (a + 1 >= argc) {
  299. exit(usage(argv));
  300. }
  301. if (0) {
  302. } else if (strcmp(argv[a + 1], "compile-only") == 0) {
  303. compile_only = true;
  304. } else if (strcmp(argv[a + 1], "emit=bytecode") == 0) {
  305. emit_opt = MP_EMIT_OPT_BYTECODE;
  306. } else if (strcmp(argv[a + 1], "emit=native") == 0) {
  307. emit_opt = MP_EMIT_OPT_NATIVE_PYTHON;
  308. } else if (strcmp(argv[a + 1], "emit=viper") == 0) {
  309. emit_opt = MP_EMIT_OPT_VIPER;
  310. #if MICROPY_ENABLE_GC
  311. } else if (strncmp(argv[a + 1], "heapsize=", sizeof("heapsize=") - 1) == 0) {
  312. char *end;
  313. heap_size = strtol(argv[a + 1] + sizeof("heapsize=") - 1, &end, 0);
  314. // Don't bring unneeded libc dependencies like tolower()
  315. // If there's 'w' immediately after number, adjust it for
  316. // target word size. Note that it should be *before* size
  317. // suffix like K or M, to avoid confusion with kilowords,
  318. // etc. the size is still in bytes, just can be adjusted
  319. // for word size (taking 32bit as baseline).
  320. bool word_adjust = false;
  321. if ((*end | 0x20) == 'w') {
  322. word_adjust = true;
  323. end++;
  324. }
  325. if ((*end | 0x20) == 'k') {
  326. heap_size *= 1024;
  327. } else if ((*end | 0x20) == 'm') {
  328. heap_size *= 1024 * 1024;
  329. } else {
  330. // Compensate for ++ below
  331. --end;
  332. }
  333. if (*++end != 0) {
  334. goto invalid_arg;
  335. }
  336. if (word_adjust) {
  337. heap_size = heap_size * BYTES_PER_WORD / 4;
  338. }
  339. // If requested size too small, we'll crash anyway
  340. if (heap_size < 700) {
  341. goto invalid_arg;
  342. }
  343. #endif
  344. } else {
  345. invalid_arg:
  346. printf("Invalid option\n");
  347. exit(usage(argv));
  348. }
  349. a++;
  350. }
  351. }
  352. }
  353. }
  354. STATIC void set_sys_argv(char *argv[], int argc, int start_arg) {
  355. for (int i = start_arg; i < argc; i++) {
  356. mp_obj_list_append(mp_sys_argv, MP_OBJ_NEW_QSTR(qstr_from_str(argv[i])));
  357. }
  358. }
  359. #ifdef _WIN32
  360. #define PATHLIST_SEP_CHAR ';'
  361. #else
  362. #define PATHLIST_SEP_CHAR ':'
  363. #endif
  364. MP_NOINLINE int main_(int argc, char **argv);
  365. int main(int argc, char **argv) {
  366. #if MICROPY_PY_THREAD
  367. mp_thread_init();
  368. #endif
  369. // We should capture stack top ASAP after start, and it should be
  370. // captured guaranteedly before any other stack variables are allocated.
  371. // For this, actual main (renamed main_) should not be inlined into
  372. // this function. main_() itself may have other functions inlined (with
  373. // their own stack variables), that's why we need this main/main_ split.
  374. mp_stack_ctrl_init();
  375. return main_(argc, argv);
  376. }
  377. MP_NOINLINE int main_(int argc, char **argv) {
  378. #ifdef SIGPIPE
  379. // Do not raise SIGPIPE, instead return EPIPE. Otherwise, e.g. writing
  380. // to peer-closed socket will lead to sudden termination of MicroPython
  381. // process. SIGPIPE is particularly nasty, because unix shell doesn't
  382. // print anything for it, so the above looks like completely sudden and
  383. // silent termination for unknown reason. Ignoring SIGPIPE is also what
  384. // CPython does. Note that this may lead to problems using MicroPython
  385. // scripts as pipe filters, but again, that's what CPython does. So,
  386. // scripts which want to follow unix shell pipe semantics (where SIGPIPE
  387. // means "pipe was requested to terminate, it's not an error"), should
  388. // catch EPIPE themselves.
  389. signal(SIGPIPE, SIG_IGN);
  390. #endif
  391. mp_stack_set_limit(40000 * (BYTES_PER_WORD / 4));
  392. pre_process_options(argc, argv);
  393. #if MICROPY_ENABLE_GC
  394. char *heap = malloc(heap_size);
  395. gc_init(heap, heap + heap_size);
  396. #endif
  397. #if MICROPY_ENABLE_PYSTACK
  398. static mp_obj_t pystack[1024];
  399. mp_pystack_init(pystack, &pystack[MP_ARRAY_SIZE(pystack)]);
  400. #endif
  401. mp_init();
  402. #if MICROPY_VFS_POSIX
  403. {
  404. // Mount the host FS at the root of our internal VFS
  405. mp_obj_t args[2] = {
  406. mp_type_vfs_posix.make_new(&mp_type_vfs_posix, 0, 0, NULL),
  407. MP_OBJ_NEW_QSTR(MP_QSTR__slash_),
  408. };
  409. mp_vfs_mount(2, args, (mp_map_t*)&mp_const_empty_map);
  410. MP_STATE_VM(vfs_cur) = MP_STATE_VM(vfs_mount_table);
  411. }
  412. #endif
  413. char *home = getenv("HOME");
  414. char *path = getenv("MICROPYPATH");
  415. if (path == NULL) {
  416. #ifdef MICROPY_PY_SYS_PATH_DEFAULT
  417. path = MICROPY_PY_SYS_PATH_DEFAULT;
  418. #else
  419. path = "~/.micropython/lib:/usr/lib/micropython";
  420. #endif
  421. }
  422. size_t path_num = 1; // [0] is for current dir (or base dir of the script)
  423. if (*path == ':') {
  424. path_num++;
  425. }
  426. for (char *p = path; p != NULL; p = strchr(p, PATHLIST_SEP_CHAR)) {
  427. path_num++;
  428. if (p != NULL) {
  429. p++;
  430. }
  431. }
  432. mp_obj_list_init(MP_OBJ_TO_PTR(mp_sys_path), path_num);
  433. mp_obj_t *path_items;
  434. mp_obj_list_get(mp_sys_path, &path_num, &path_items);
  435. path_items[0] = MP_OBJ_NEW_QSTR(MP_QSTR_);
  436. {
  437. char *p = path;
  438. for (mp_uint_t i = 1; i < path_num; i++) {
  439. char *p1 = strchr(p, PATHLIST_SEP_CHAR);
  440. if (p1 == NULL) {
  441. p1 = p + strlen(p);
  442. }
  443. if (p[0] == '~' && p[1] == '/' && home != NULL) {
  444. // Expand standalone ~ to $HOME
  445. int home_l = strlen(home);
  446. vstr_t vstr;
  447. vstr_init(&vstr, home_l + (p1 - p - 1) + 1);
  448. vstr_add_strn(&vstr, home, home_l);
  449. vstr_add_strn(&vstr, p + 1, p1 - p - 1);
  450. path_items[i] = mp_obj_new_str_from_vstr(&mp_type_str, &vstr);
  451. } else {
  452. path_items[i] = mp_obj_new_str_via_qstr(p, p1 - p);
  453. }
  454. p = p1 + 1;
  455. }
  456. }
  457. mp_obj_list_init(MP_OBJ_TO_PTR(mp_sys_argv), 0);
  458. #if defined(MICROPY_UNIX_COVERAGE)
  459. {
  460. MP_DECLARE_CONST_FUN_OBJ_0(extra_coverage_obj);
  461. mp_store_global(QSTR_FROM_STR_STATIC("extra_coverage"), MP_OBJ_FROM_PTR(&extra_coverage_obj));
  462. }
  463. #endif
  464. // Here is some example code to create a class and instance of that class.
  465. // First is the Python, then the C code.
  466. //
  467. // class TestClass:
  468. // pass
  469. // test_obj = TestClass()
  470. // test_obj.attr = 42
  471. //
  472. // mp_obj_t test_class_type, test_class_instance;
  473. // test_class_type = mp_obj_new_type(QSTR_FROM_STR_STATIC("TestClass"), mp_const_empty_tuple, mp_obj_new_dict(0));
  474. // mp_store_name(QSTR_FROM_STR_STATIC("test_obj"), test_class_instance = mp_call_function_0(test_class_type));
  475. // mp_store_attr(test_class_instance, QSTR_FROM_STR_STATIC("attr"), mp_obj_new_int(42));
  476. /*
  477. printf("bytes:\n");
  478. printf(" total %d\n", m_get_total_bytes_allocated());
  479. printf(" cur %d\n", m_get_current_bytes_allocated());
  480. printf(" peak %d\n", m_get_peak_bytes_allocated());
  481. */
  482. const int NOTHING_EXECUTED = -2;
  483. int ret = NOTHING_EXECUTED;
  484. bool inspect = false;
  485. for (int a = 1; a < argc; a++) {
  486. if (argv[a][0] == '-') {
  487. if (strcmp(argv[a], "-i") == 0) {
  488. inspect = true;
  489. } else if (strcmp(argv[a], "-c") == 0) {
  490. if (a + 1 >= argc) {
  491. return usage(argv);
  492. }
  493. ret = do_str(argv[a + 1]);
  494. if (ret & FORCED_EXIT) {
  495. break;
  496. }
  497. a += 1;
  498. } else if (strcmp(argv[a], "-m") == 0) {
  499. if (a + 1 >= argc) {
  500. return usage(argv);
  501. }
  502. mp_obj_t import_args[4];
  503. import_args[0] = mp_obj_new_str(argv[a + 1], strlen(argv[a + 1]));
  504. import_args[1] = import_args[2] = mp_const_none;
  505. // Ask __import__ to handle imported module specially - set its __name__
  506. // to __main__, and also return this leaf module, not top-level package
  507. // containing it.
  508. import_args[3] = mp_const_false;
  509. // TODO: https://docs.python.org/3/using/cmdline.html#cmdoption-m :
  510. // "the first element of sys.argv will be the full path to
  511. // the module file (while the module file is being located,
  512. // the first element will be set to "-m")."
  513. set_sys_argv(argv, argc, a + 1);
  514. mp_obj_t mod;
  515. nlr_buf_t nlr;
  516. bool subpkg_tried = false;
  517. reimport:
  518. if (nlr_push(&nlr) == 0) {
  519. mod = mp_builtin___import__(MP_ARRAY_SIZE(import_args), import_args);
  520. nlr_pop();
  521. } else {
  522. // uncaught exception
  523. return handle_uncaught_exception(nlr.ret_val) & 0xff;
  524. }
  525. if (mp_obj_is_package(mod) && !subpkg_tried) {
  526. subpkg_tried = true;
  527. vstr_t vstr;
  528. int len = strlen(argv[a + 1]);
  529. vstr_init(&vstr, len + sizeof(".__main__"));
  530. vstr_add_strn(&vstr, argv[a + 1], len);
  531. vstr_add_strn(&vstr, ".__main__", sizeof(".__main__") - 1);
  532. import_args[0] = mp_obj_new_str_from_vstr(&mp_type_str, &vstr);
  533. goto reimport;
  534. }
  535. ret = 0;
  536. break;
  537. } else if (strcmp(argv[a], "-X") == 0) {
  538. a += 1;
  539. #if MICROPY_DEBUG_PRINTERS
  540. } else if (strcmp(argv[a], "-v") == 0) {
  541. mp_verbose_flag++;
  542. #endif
  543. } else if (strncmp(argv[a], "-O", 2) == 0) {
  544. if (unichar_isdigit(argv[a][2])) {
  545. MP_STATE_VM(mp_optimise_value) = argv[a][2] & 0xf;
  546. } else {
  547. MP_STATE_VM(mp_optimise_value) = 0;
  548. for (char *p = argv[a] + 1; *p && *p == 'O'; p++, MP_STATE_VM(mp_optimise_value)++);
  549. }
  550. } else {
  551. return usage(argv);
  552. }
  553. } else {
  554. char *pathbuf = malloc(PATH_MAX);
  555. char *basedir = realpath(argv[a], pathbuf);
  556. if (basedir == NULL) {
  557. mp_printf(&mp_stderr_print, "%s: can't open file '%s': [Errno %d] %s\n", argv[0], argv[a], errno, strerror(errno));
  558. // CPython exits with 2 in such case
  559. ret = 2;
  560. break;
  561. }
  562. // Set base dir of the script as first entry in sys.path
  563. char *p = strrchr(basedir, '/');
  564. path_items[0] = mp_obj_new_str_via_qstr(basedir, p - basedir);
  565. free(pathbuf);
  566. set_sys_argv(argv, argc, a);
  567. ret = do_file(argv[a]);
  568. break;
  569. }
  570. }
  571. if (ret == NOTHING_EXECUTED || inspect) {
  572. if (isatty(0)) {
  573. prompt_read_history();
  574. ret = do_repl();
  575. prompt_write_history();
  576. } else {
  577. ret = execute_from_lexer(LEX_SRC_STDIN, NULL, MP_PARSE_FILE_INPUT, false);
  578. }
  579. }
  580. #if MICROPY_PY_MICROPYTHON_MEM_INFO
  581. if (mp_verbose_flag) {
  582. mp_micropython_mem_info(0, NULL);
  583. }
  584. #endif
  585. #if defined(MICROPY_UNIX_COVERAGE)
  586. gc_sweep_all();
  587. #endif
  588. mp_deinit();
  589. #if MICROPY_ENABLE_GC && !defined(NDEBUG)
  590. // We don't really need to free memory since we are about to exit the
  591. // process, but doing so helps to find memory leaks.
  592. free(heap);
  593. #endif
  594. //printf("total bytes = %d\n", m_get_total_bytes_allocated());
  595. return ret & 0xff;
  596. }
  597. #if !MICROPY_VFS
  598. uint mp_import_stat(const char *path) {
  599. struct stat st;
  600. if (stat(path, &st) == 0) {
  601. if (S_ISDIR(st.st_mode)) {
  602. return MP_IMPORT_STAT_DIR;
  603. } else if (S_ISREG(st.st_mode)) {
  604. return MP_IMPORT_STAT_FILE;
  605. }
  606. }
  607. return MP_IMPORT_STAT_NO_EXIST;
  608. }
  609. #endif
  610. void nlr_jump_fail(void *val) {
  611. printf("FATAL: uncaught NLR %p\n", val);
  612. exit(1);
  613. }