LCOV - code coverage report
Current view: top level - ports/unix - main.c (source / functions) Hit Total Coverage
Test: unix_coverage_v1.22.0-333-g49ce7a607.info Lines: 224 303 73.9 %
Date: 2024-04-22 10:07:55 Functions: 11 14 78.6 %
Branches: 101 154 65.6 %

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

Generated by: LCOV version 1.15-5-g462f71d