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-2019 Damien P. George
7 : : * Copyright (c) 2014 Paul Sokolovsky
8 : : * Copyright (c) 2021 Jim Mussared
9 : : *
10 : : * Permission is hereby granted, free of charge, to any person obtaining a copy
11 : : * of this software and associated documentation files (the "Software"), to deal
12 : : * in the Software without restriction, including without limitation the rights
13 : : * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
14 : : * copies of the Software, and to permit persons to whom the Software is
15 : : * furnished to do so, subject to the following conditions:
16 : : *
17 : : * The above copyright notice and this permission notice shall be included in
18 : : * all copies or substantial portions of the Software.
19 : : *
20 : : * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
21 : : * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
22 : : * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
23 : : * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
24 : : * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
25 : : * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
26 : : * THE SOFTWARE.
27 : : */
28 : :
29 : : #include <stdio.h>
30 : : #include <string.h>
31 : : #include <assert.h>
32 : :
33 : : #include "py/compile.h"
34 : : #include "py/objmodule.h"
35 : : #include "py/persistentcode.h"
36 : : #include "py/runtime.h"
37 : : #include "py/builtin.h"
38 : : #include "py/frozenmod.h"
39 : :
40 : : #if MICROPY_DEBUG_VERBOSE // print debugging info
41 : : #define DEBUG_PRINT (1)
42 : : #define DEBUG_printf DEBUG_printf
43 : : #else // don't print debugging info
44 : : #define DEBUG_PRINT (0)
45 : : #define DEBUG_printf(...) (void)0
46 : : #endif
47 : :
48 : : #if MICROPY_ENABLE_EXTERNAL_IMPORT
49 : :
50 : : // Must be a string of one byte.
51 : : #define PATH_SEP_CHAR "/"
52 : :
53 : : // Virtual sys.path entry that maps to the frozen modules.
54 : : #define MP_FROZEN_PATH_PREFIX ".frozen/"
55 : :
56 : : // Wrapper for mp_import_stat (which is provided by the port, and typically
57 : : // uses mp_vfs_import_stat) to also search frozen modules. Given an exact
58 : : // path to a file or directory (e.g. "foo/bar", foo/bar.py" or "foo/bar.mpy"),
59 : : // will return whether the path is a file, directory, or doesn't exist.
60 : 12398 : STATIC mp_import_stat_t stat_path(const char *path) {
61 : : #if MICROPY_MODULE_FROZEN
62 : : // Only try and load as a frozen module if it starts with .frozen/.
63 : 12398 : const int frozen_path_prefix_len = strlen(MP_FROZEN_PATH_PREFIX);
64 [ + + ]: 12398 : if (strncmp(path, MP_FROZEN_PATH_PREFIX, frozen_path_prefix_len) == 0) {
65 : : // Just stat (which is the return value), don't get the data.
66 : 2683 : return mp_find_frozen_module(path + frozen_path_prefix_len, NULL, NULL);
67 : : }
68 : : #endif
69 : 9715 : return mp_import_stat(path);
70 : : }
71 : :
72 : : // Stat a given filesystem path to a .py file. If the file does not exist,
73 : : // then attempt to stat the corresponding .mpy file, and update the path
74 : : // argument. This is the logic that makes .py files take precedent over .mpy
75 : : // files. This uses stat_path above, rather than mp_import_stat directly, so
76 : : // that the .frozen path prefix is handled.
77 : 4221 : STATIC mp_import_stat_t stat_file_py_or_mpy(vstr_t *path) {
78 : 4221 : mp_import_stat_t stat = stat_path(vstr_null_terminated_str(path));
79 [ + + ]: 4221 : if (stat == MP_IMPORT_STAT_FILE) {
80 : : return stat;
81 : : }
82 : :
83 : : #if MICROPY_PERSISTENT_CODE_LOAD
84 : : // Didn't find .py -- try the .mpy instead by inserting an 'm' into the '.py'.
85 : : // Note: There's no point doing this if it's a frozen path, but adding the check
86 : : // would be extra code, and no harm letting mp_find_frozen_module fail instead.
87 : 3956 : vstr_ins_byte(path, path->len - 2, 'm');
88 : 3956 : stat = stat_path(vstr_null_terminated_str(path));
89 [ + + ]: 3956 : if (stat == MP_IMPORT_STAT_FILE) {
90 : 1343 : return stat;
91 : : }
92 : : #endif
93 : :
94 : : return MP_IMPORT_STAT_NO_EXIST;
95 : : }
96 : :
97 : : // Given an import path (e.g. "foo/bar"), try and find "foo/bar" (a directory)
98 : : // or "foo/bar.(m)py" in either the filesystem or frozen modules. If the
99 : : // result is a file, the path argument will be updated to include the file
100 : : // extension.
101 : 4221 : STATIC mp_import_stat_t stat_module(vstr_t *path) {
102 : 4221 : mp_import_stat_t stat = stat_path(vstr_null_terminated_str(path));
103 : 4221 : DEBUG_printf("stat %s: %d\n", vstr_str(path), stat);
104 [ + + ]: 4221 : if (stat == MP_IMPORT_STAT_DIR) {
105 : : return stat;
106 : : }
107 : :
108 : : // Not a directory, add .py and try as a file.
109 : 4123 : vstr_add_str(path, ".py");
110 : 4123 : return stat_file_py_or_mpy(path);
111 : : }
112 : :
113 : : // Given a top-level module name, try and find it in each of the sys.path
114 : : // entries. Note: On success, the dest argument will be updated to the matching
115 : : // path (i.e. "<entry>/mod_name(.py)").
116 : 2276 : STATIC mp_import_stat_t stat_top_level(qstr mod_name, vstr_t *dest) {
117 : 2276 : DEBUG_printf("stat_top_level: '%s'\n", qstr_str(mod_name));
118 : : #if MICROPY_PY_SYS
119 : 2276 : size_t path_num;
120 : 2276 : mp_obj_t *path_items;
121 : 2276 : mp_obj_get_array(mp_sys_path, &path_num, &path_items);
122 : :
123 : : // go through each sys.path entry, trying to import "<entry>/<mod_name>".
124 [ + + ]: 4879 : for (size_t i = 0; i < path_num; i++) {
125 : 4092 : vstr_reset(dest);
126 : 4092 : size_t p_len;
127 : 4092 : const char *p = mp_obj_str_get_data(path_items[i], &p_len);
128 [ + + ]: 4092 : if (p_len > 0) {
129 : : // Add the path separator (unless the entry is "", i.e. cwd).
130 : 2618 : vstr_add_strn(dest, p, p_len);
131 : 2618 : vstr_add_char(dest, PATH_SEP_CHAR[0]);
132 : : }
133 : 4092 : vstr_add_str(dest, qstr_str(mod_name));
134 : 4092 : mp_import_stat_t stat = stat_module(dest);
135 [ + + ]: 4092 : if (stat != MP_IMPORT_STAT_NO_EXIST) {
136 : 1489 : return stat;
137 : : }
138 : : }
139 : :
140 : : // sys.path was empty or no matches, do not search the filesystem or
141 : : // frozen code.
142 : : return MP_IMPORT_STAT_NO_EXIST;
143 : :
144 : : #else
145 : :
146 : : // mp_sys_path is not enabled, so just stat the given path directly.
147 : : vstr_add_str(dest, qstr_str(mod_name));
148 : : return stat_module(dest);
149 : :
150 : : #endif
151 : : }
152 : :
153 : : #if MICROPY_MODULE_FROZEN_STR || MICROPY_ENABLE_COMPILER
154 : 251 : STATIC void do_load_from_lexer(mp_module_context_t *context, mp_lexer_t *lex) {
155 : : #if MICROPY_PY___FILE__
156 : 251 : qstr source_name = lex->source_name;
157 : 251 : mp_store_attr(MP_OBJ_FROM_PTR(&context->module), MP_QSTR___file__, MP_OBJ_NEW_QSTR(source_name));
158 : : #endif
159 : :
160 : : // parse, compile and execute the module in its context
161 : 251 : mp_obj_dict_t *mod_globals = context->module.globals;
162 : 251 : mp_parse_compile_execute(lex, MP_PARSE_FILE_INPUT, mod_globals, mod_globals);
163 : 241 : }
164 : : #endif
165 : :
166 : : #if (MICROPY_HAS_FILE_READER && MICROPY_PERSISTENT_CODE_LOAD) || MICROPY_MODULE_FROZEN_MPY
167 : 1339 : STATIC void do_execute_raw_code(const mp_module_context_t *context, const mp_raw_code_t *rc, qstr source_name) {
168 : : #if MICROPY_PY___FILE__
169 : 1339 : mp_store_attr(MP_OBJ_FROM_PTR(&context->module), MP_QSTR___file__, MP_OBJ_NEW_QSTR(source_name));
170 : : #else
171 : : (void)source_name;
172 : : #endif
173 : :
174 : : // execute the module in its context
175 : 1339 : mp_obj_dict_t *mod_globals = context->module.globals;
176 : :
177 : : // save context
178 : 1339 : nlr_jump_callback_node_globals_locals_t ctx;
179 : 1339 : ctx.globals = mp_globals_get();
180 : 1339 : ctx.locals = mp_locals_get();
181 : :
182 : : // set new context
183 : 1339 : mp_globals_set(mod_globals);
184 : 1339 : mp_locals_set(mod_globals);
185 : :
186 : : // set exception handler to restore context if an exception is raised
187 : 1339 : nlr_push_jump_callback(&ctx.callback, mp_globals_locals_set_from_nlr_jump_callback);
188 : :
189 : : // make and execute the function
190 : 1339 : mp_obj_t module_fun = mp_make_function_from_raw_code(rc, context, NULL);
191 : 1339 : mp_call_function_0(module_fun);
192 : :
193 : : // deregister exception handler and restore context
194 : 1333 : nlr_pop_jump_callback(true);
195 : 1333 : }
196 : : #endif
197 : :
198 : 1608 : STATIC void do_load(mp_module_context_t *module_obj, vstr_t *file) {
199 : : #if MICROPY_MODULE_FROZEN || MICROPY_ENABLE_COMPILER || (MICROPY_PERSISTENT_CODE_LOAD && MICROPY_HAS_FILE_READER)
200 : 1608 : const char *file_str = vstr_null_terminated_str(file);
201 : : #endif
202 : :
203 : : // If we support frozen modules (either as str or mpy) then try to find the
204 : : // requested filename in the list of frozen module filenames.
205 : : #if MICROPY_MODULE_FROZEN
206 : 1608 : void *modref;
207 : 1608 : int frozen_type;
208 : 1608 : const int frozen_path_prefix_len = strlen(MP_FROZEN_PATH_PREFIX);
209 [ + + ]: 1608 : if (strncmp(file_str, MP_FROZEN_PATH_PREFIX, frozen_path_prefix_len) == 0) {
210 : 20 : mp_find_frozen_module(file_str + frozen_path_prefix_len, &frozen_type, &modref);
211 : :
212 : : // If we support frozen str modules and the compiler is enabled, and we
213 : : // found the filename in the list of frozen files, then load and execute it.
214 : : #if MICROPY_MODULE_FROZEN_STR
215 [ + + ]: 20 : if (frozen_type == MP_FROZEN_STR) {
216 : 6 : do_load_from_lexer(module_obj, modref);
217 : 6 : return;
218 : : }
219 : : #endif
220 : :
221 : : // If we support frozen mpy modules and we found a corresponding file (and
222 : : // its data) in the list of frozen files, execute it.
223 : : #if MICROPY_MODULE_FROZEN_MPY
224 [ + - ]: 14 : if (frozen_type == MP_FROZEN_MPY) {
225 : 14 : const mp_frozen_module_t *frozen = modref;
226 : 14 : module_obj->constants = frozen->constants;
227 : : #if MICROPY_PY___FILE__
228 : 14 : qstr frozen_file_qstr = qstr_from_str(file_str + frozen_path_prefix_len);
229 : : #else
230 : : qstr frozen_file_qstr = MP_QSTRnull;
231 : : #endif
232 : 14 : do_execute_raw_code(module_obj, frozen->rc, frozen_file_qstr);
233 : 14 : return;
234 : : }
235 : : #endif
236 : : }
237 : :
238 : : #endif // MICROPY_MODULE_FROZEN
239 : :
240 : 1588 : qstr file_qstr = qstr_from_str(file_str);
241 : :
242 : : // If we support loading .mpy files then check if the file extension is of
243 : : // the correct format and, if so, load and execute the file.
244 : : #if MICROPY_HAS_FILE_READER && MICROPY_PERSISTENT_CODE_LOAD
245 [ + + ]: 1588 : if (file_str[file->len - 3] == 'm') {
246 : 1343 : mp_compiled_module_t cm;
247 : 1343 : cm.context = module_obj;
248 : 1343 : mp_raw_code_load_file(file_qstr, &cm);
249 : 1325 : do_execute_raw_code(cm.context, cm.rc, file_qstr);
250 : 1321 : return;
251 : : }
252 : : #endif
253 : :
254 : : // If we can compile scripts then load the file and compile and execute it.
255 : : #if MICROPY_ENABLE_COMPILER
256 : : {
257 : 245 : mp_lexer_t *lex = mp_lexer_new_from_file(file_qstr);
258 : 245 : do_load_from_lexer(module_obj, lex);
259 : 245 : return;
260 : : }
261 : : #else
262 : : // If we get here then the file was not frozen and we can't compile scripts.
263 : : mp_raise_msg(&mp_type_ImportError, MP_ERROR_TEXT("script compilation not supported"));
264 : : #endif
265 : : }
266 : :
267 : : // Convert a relative (to the current module) import, going up "level" levels,
268 : : // into an absolute import.
269 : 110 : STATIC void evaluate_relative_import(mp_int_t level, const char **module_name, size_t *module_name_len) {
270 : : // What we want to do here is to take the name of the current module,
271 : : // remove <level> trailing components, and concatenate the passed-in
272 : : // module name.
273 : : // For example, level=3, module_name="foo.bar", __name__="a.b.c.d" --> "a.foo.bar"
274 : : // "Relative imports use a module's __name__ attribute to determine that
275 : : // module's position in the package hierarchy."
276 : : // http://legacy.python.org/dev/peps/pep-0328/#relative-imports-and-name
277 : :
278 : 110 : mp_obj_t current_module_name_obj = mp_obj_dict_get(MP_OBJ_FROM_PTR(mp_globals_get()), MP_OBJ_NEW_QSTR(MP_QSTR___name__));
279 [ - + ]: 110 : assert(current_module_name_obj != MP_OBJ_NULL);
280 : :
281 : : #if MICROPY_MODULE_OVERRIDE_MAIN_IMPORT && MICROPY_CPYTHON_COMPAT
282 [ + + ]: 110 : if (MP_OBJ_QSTR_VALUE(current_module_name_obj) == MP_QSTR___main__) {
283 : : // This is a module loaded by -m command-line switch (e.g. unix port),
284 : : // and so its __name__ has been set to "__main__". Get its real name
285 : : // that we stored during import in the __main__ attribute.
286 : 2 : current_module_name_obj = mp_obj_dict_get(MP_OBJ_FROM_PTR(mp_globals_get()), MP_OBJ_NEW_QSTR(MP_QSTR___main__));
287 : : }
288 : : #endif
289 : :
290 : : // If we have a __path__ in the globals dict, then we're a package.
291 : 108 : bool is_pkg = mp_map_lookup(&mp_globals_get()->map, MP_OBJ_NEW_QSTR(MP_QSTR___path__), MP_MAP_LOOKUP);
292 : :
293 : : #if DEBUG_PRINT
294 : : DEBUG_printf("Current module/package: ");
295 : : mp_obj_print_helper(MICROPY_DEBUG_PRINTER, current_module_name_obj, PRINT_REPR);
296 : : DEBUG_printf(", is_package: %d", is_pkg);
297 : : DEBUG_printf("\n");
298 : : #endif
299 : :
300 : 108 : size_t current_module_name_len;
301 : 108 : const char *current_module_name = mp_obj_str_get_data(current_module_name_obj, ¤t_module_name_len);
302 : :
303 : 108 : const char *p = current_module_name + current_module_name_len;
304 [ + + ]: 108 : if (is_pkg) {
305 : : // If we're evaluating relative to a package, then take off one fewer
306 : : // level (i.e. the relative search starts inside the package, rather
307 : : // than as a sibling of the package).
308 : 77 : --level;
309 : : }
310 : :
311 : : // Walk back 'level' dots (or run out of path).
312 [ + + ]: 401 : while (level && p > current_module_name) {
313 [ + + ]: 293 : if (*--p == '.') {
314 : 45 : --level;
315 : : }
316 : : }
317 : :
318 : : // We must have some component left over to import from.
319 [ + + ]: 108 : if (p == current_module_name) {
320 : 2 : mp_raise_msg(&mp_type_ImportError, MP_ERROR_TEXT("can't perform relative import"));
321 : : }
322 : :
323 : : // New length is len("<chopped path>.<module_name>"). Note: might be one byte
324 : : // more than we need if module_name is empty (for the extra . we will
325 : : // append).
326 : 106 : uint new_module_name_len = (size_t)(p - current_module_name) + 1 + *module_name_len;
327 : 106 : char *new_mod = mp_local_alloc(new_module_name_len);
328 : 106 : memcpy(new_mod, current_module_name, p - current_module_name);
329 : :
330 : : // Only append ".<module_name>" if there was one).
331 [ + + ]: 106 : if (*module_name_len != 0) {
332 : 81 : new_mod[p - current_module_name] = '.';
333 : 81 : memcpy(new_mod + (p - current_module_name) + 1, *module_name, *module_name_len);
334 : : } else {
335 : : --new_module_name_len;
336 : : }
337 : :
338 : : // Copy into a QSTR.
339 : 106 : qstr new_mod_q = qstr_from_strn(new_mod, new_module_name_len);
340 : 106 : mp_local_free(new_mod);
341 : :
342 : 106 : DEBUG_printf("Resolved base name for relative import: '%s'\n", qstr_str(new_mod_q));
343 : 106 : *module_name = qstr_str(new_mod_q);
344 : 106 : *module_name_len = new_module_name_len;
345 : 106 : }
346 : :
347 : : typedef struct _nlr_jump_callback_node_unregister_module_t {
348 : : nlr_jump_callback_node_t callback;
349 : : qstr name;
350 : : } nlr_jump_callback_node_unregister_module_t;
351 : :
352 : 34 : STATIC void unregister_module_from_nlr_jump_callback(void *ctx_in) {
353 : 34 : nlr_jump_callback_node_unregister_module_t *ctx = ctx_in;
354 : 34 : mp_map_t *mp_loaded_modules_map = &MP_STATE_VM(mp_loaded_modules_dict).map;
355 : 34 : mp_map_lookup(mp_loaded_modules_map, MP_OBJ_NEW_QSTR(ctx->name), MP_MAP_LOOKUP_REMOVE_IF_FOUND);
356 : 34 : }
357 : :
358 : : // Load a module at the specified absolute path, possibly as a submodule of the given outer module.
359 : : // full_mod_name: The full absolute path up to this level (e.g. "foo.bar.baz").
360 : : // level_mod_name: The final component of the path (e.g. "baz").
361 : : // outer_module_obj: The parent module (we need to store this module as an
362 : : // attribute on it) (or MP_OBJ_NULL for top-level).
363 : : // override_main: Whether to set the __name__ to "__main__" (and use __main__
364 : : // for the actual path).
365 : 3319 : STATIC mp_obj_t process_import_at_level(qstr full_mod_name, qstr level_mod_name, mp_obj_t outer_module_obj, bool override_main) {
366 : : // Immediately return if the module at this level is already loaded.
367 : 3319 : mp_map_elem_t *elem;
368 : :
369 : : #if MICROPY_PY_SYS
370 : : // If sys.path is empty, the intention is to force using a built-in. This
371 : : // means we should also ignore any loaded modules with the same name
372 : : // which may have come from the filesystem.
373 : 3319 : size_t path_num;
374 : 3319 : mp_obj_t *path_items;
375 : 3319 : mp_obj_get_array(mp_sys_path, &path_num, &path_items);
376 [ + + ]: 3319 : if (path_num)
377 : : #endif
378 : : {
379 : 3317 : elem = mp_map_lookup(&MP_STATE_VM(mp_loaded_modules_dict).map, MP_OBJ_NEW_QSTR(full_mod_name), MP_MAP_LOOKUP);
380 [ + + ]: 3317 : if (elem) {
381 : 178 : return elem->value;
382 : : }
383 : : }
384 : :
385 : 3141 : VSTR_FIXED(path, MICROPY_ALLOC_PATH_MAX);
386 : 3141 : mp_import_stat_t stat = MP_IMPORT_STAT_NO_EXIST;
387 : 3141 : mp_obj_t module_obj;
388 : :
389 [ + + ]: 3141 : if (outer_module_obj == MP_OBJ_NULL) {
390 : : // First module in the dotted-name path.
391 : 3008 : DEBUG_printf("Searching for top-level module\n");
392 : :
393 : : // An import of a non-extensible built-in will always bypass the
394 : : // filesystem. e.g. `import micropython` or `import pyb`. So try and
395 : : // match a non-extensible built-ins first.
396 : 3008 : module_obj = mp_module_get_builtin(level_mod_name, false);
397 [ + + ]: 3008 : if (module_obj != MP_OBJ_NULL) {
398 : : return module_obj;
399 : : }
400 : :
401 : : // Next try the filesystem. Search for a directory or file relative to
402 : : // all the locations in sys.path.
403 : 2276 : stat = stat_top_level(level_mod_name, &path);
404 : :
405 : : // If filesystem failed, now try and see if it matches an extensible
406 : : // built-in module.
407 [ + + ]: 2276 : if (stat == MP_IMPORT_STAT_NO_EXIST) {
408 : 787 : module_obj = mp_module_get_builtin(level_mod_name, true);
409 [ + + ]: 787 : if (module_obj != MP_OBJ_NULL) {
410 : : return module_obj;
411 : : }
412 : : }
413 : : } else {
414 : 133 : DEBUG_printf("Searching for sub-module\n");
415 : :
416 : : #if MICROPY_MODULE_BUILTIN_SUBPACKAGES
417 : : // If the outer module is a built-in (because its map is in ROM), then
418 : : // treat it like a package if it contains this submodule in its
419 : : // globals dict.
420 : 133 : mp_obj_module_t *mod = MP_OBJ_TO_PTR(outer_module_obj);
421 [ + + ]: 133 : if (mod->globals->map.is_fixed) {
422 : 4 : elem = mp_map_lookup(&mod->globals->map, MP_OBJ_NEW_QSTR(level_mod_name), MP_MAP_LOOKUP);
423 : : // Also verify that the entry in the globals dict is in fact a module.
424 [ + - - + : 4 : if (elem && mp_obj_is_type(elem->value, &mp_type_module)) {
- + - + -
+ + - +
- ]
425 : 4 : return elem->value;
426 : : }
427 : : }
428 : : #endif
429 : :
430 : : // If the outer module is a package, it will have __path__ set.
431 : : // We can use that as the path to search inside.
432 : 129 : mp_obj_t dest[2];
433 : 129 : mp_load_method_maybe(outer_module_obj, MP_QSTR___path__, dest);
434 [ - + ]: 129 : if (dest[0] != MP_OBJ_NULL) {
435 : : // e.g. __path__ will be "<matched search path>/foo/bar"
436 : 129 : vstr_add_str(&path, mp_obj_str_get_str(dest[0]));
437 : :
438 : : // Add the level module name to the path to get "<matched search path>/foo/bar/baz".
439 : 129 : vstr_add_char(&path, PATH_SEP_CHAR[0]);
440 : 129 : vstr_add_str(&path, qstr_str(level_mod_name));
441 : :
442 : 129 : stat = stat_module(&path);
443 : : }
444 : : }
445 : :
446 : : // Not already loaded, and not a built-in, so look at the stat result from the filesystem/frozen.
447 : :
448 [ + + ]: 151 : if (stat == MP_IMPORT_STAT_NO_EXIST) {
449 : : // Not found -- fail.
450 : : #if MICROPY_ERROR_REPORTING <= MICROPY_ERROR_REPORTING_TERSE
451 : : mp_raise_msg(&mp_type_ImportError, MP_ERROR_TEXT("module not found"));
452 : : #else
453 : 22 : mp_raise_msg_varg(&mp_type_ImportError, MP_ERROR_TEXT("no module named '%q'"), full_mod_name);
454 : : #endif
455 : : }
456 : :
457 : : // Module was found on the filesystem/frozen, try and load it.
458 : 1618 : DEBUG_printf("Found path to load: %.*s\n", (int)vstr_len(&path), vstr_str(&path));
459 : :
460 : : // Prepare for loading from the filesystem. Create a new shell module
461 : : // and register it in sys.modules. Also make sure we remove it if
462 : : // there is any problem below.
463 : 1618 : module_obj = mp_obj_new_module(full_mod_name);
464 : 1618 : nlr_jump_callback_node_unregister_module_t ctx;
465 : 1618 : ctx.name = full_mod_name;
466 : 1618 : nlr_push_jump_callback(&ctx.callback, unregister_module_from_nlr_jump_callback);
467 : :
468 : : #if MICROPY_MODULE_OVERRIDE_MAIN_IMPORT
469 : : // If this module is being loaded via -m on unix, then
470 : : // override __name__ to "__main__". Do this only for *modules*
471 : : // however - packages never have their names replaced, instead
472 : : // they're -m'ed using a special __main__ submodule in them. (This all
473 : : // apparently is done to not touch the package name itself, which is
474 : : // important for future imports).
475 [ + + ]: 1618 : if (override_main && stat != MP_IMPORT_STAT_DIR) {
476 : 1313 : mp_obj_module_t *o = MP_OBJ_TO_PTR(module_obj);
477 : 1313 : mp_obj_dict_store(MP_OBJ_FROM_PTR(o->globals), MP_OBJ_NEW_QSTR(MP_QSTR___name__), MP_OBJ_NEW_QSTR(MP_QSTR___main__));
478 : : #if MICROPY_CPYTHON_COMPAT
479 : : // Store module as "__main__" in the dictionary of loaded modules (returned by sys.modules).
480 : 1313 : mp_obj_dict_store(MP_OBJ_FROM_PTR(&MP_STATE_VM(mp_loaded_modules_dict)), MP_OBJ_NEW_QSTR(MP_QSTR___main__), module_obj);
481 : : // Store real name in "__main__" attribute. Need this for
482 : : // resolving relative imports later. "__main__ was chosen
483 : : // semi-randonly, to reuse existing qstr's.
484 : 1313 : mp_obj_dict_store(MP_OBJ_FROM_PTR(o->globals), MP_OBJ_NEW_QSTR(MP_QSTR___main__), MP_OBJ_NEW_QSTR(full_mod_name));
485 : : #endif
486 : : }
487 : : #endif // MICROPY_MODULE_OVERRIDE_MAIN_IMPORT
488 : :
489 [ + + ]: 1618 : if (stat == MP_IMPORT_STAT_DIR) {
490 : : // Directory (i.e. a package).
491 : 98 : DEBUG_printf("%.*s is dir\n", (int)vstr_len(&path), vstr_str(&path));
492 : :
493 : : // Store the __path__ attribute onto this module.
494 : : // https://docs.python.org/3/reference/import.html
495 : : // "Specifically, any module that contains a __path__ attribute is considered a package."
496 : : // This gets used later to locate any subpackages of this module.
497 : 98 : mp_store_attr(module_obj, MP_QSTR___path__, mp_obj_new_str(vstr_str(&path), vstr_len(&path)));
498 : 98 : size_t orig_path_len = path.len;
499 : 98 : vstr_add_str(&path, PATH_SEP_CHAR "__init__.py");
500 : :
501 : : // execute "path/__init__.py" (if available).
502 [ + + ]: 98 : if (stat_file_py_or_mpy(&path) == MP_IMPORT_STAT_FILE) {
503 : 88 : do_load(MP_OBJ_TO_PTR(module_obj), &path);
504 : : } else {
505 : : // No-op. Nothing to load.
506 : : // mp_warning("%s is imported as namespace package", vstr_str(&path));
507 : 98 : }
508 : : // Remove /__init__.py suffix from path.
509 : 98 : path.len = orig_path_len;
510 : : } else { // MP_IMPORT_STAT_FILE
511 : : // File -- execute "path.(m)py".
512 : 1520 : do_load(MP_OBJ_TO_PTR(module_obj), &path);
513 : : // Note: This should be the last component in the import path. If
514 : : // there are remaining components then in the next call to
515 : : // process_import_at_level will detect that it doesn't have
516 : : // a __path__ attribute, and not attempt to stat it.
517 : : }
518 : :
519 [ + + ]: 1584 : if (outer_module_obj != MP_OBJ_NULL) {
520 : : // If it's a sub-module then make it available on the parent module.
521 : 121 : mp_store_attr(outer_module_obj, level_mod_name, module_obj);
522 : : }
523 : :
524 : 1584 : nlr_pop_jump_callback(false);
525 : :
526 : 1584 : return module_obj;
527 : : }
528 : :
529 : 3184 : mp_obj_t mp_builtin___import___default(size_t n_args, const mp_obj_t *args) {
530 : : #if DEBUG_PRINT
531 : : DEBUG_printf("__import__:\n");
532 : : for (size_t i = 0; i < n_args; i++) {
533 : : DEBUG_printf(" ");
534 : : mp_obj_print_helper(MICROPY_DEBUG_PRINTER, args[i], PRINT_REPR);
535 : : DEBUG_printf("\n");
536 : : }
537 : : #endif
538 : :
539 : : // This is the import path, with any leading dots stripped.
540 : : // "import foo.bar" --> module_name="foo.bar"
541 : : // "from foo.bar import baz" --> module_name="foo.bar"
542 : : // "from . import foo" --> module_name=""
543 : : // "from ...foo.bar import baz" --> module_name="foo.bar"
544 : 3184 : mp_obj_t module_name_obj = args[0];
545 : :
546 : : // These are the imported names.
547 : : // i.e. "from foo.bar import baz, zap" --> fromtuple=("baz", "zap",)
548 : : // Note: There's a special case on the Unix port, where this is set to mp_const_false which means that it's __main__.
549 : 3184 : mp_obj_t fromtuple = mp_const_none;
550 : :
551 : : // Level is the number of leading dots in a relative import.
552 : : // i.e. "from . import foo" --> level=1
553 : : // i.e. "from ...foo.bar import baz" --> level=3
554 : 3184 : mp_int_t level = 0;
555 [ + + ]: 3184 : if (n_args >= 4) {
556 : 3136 : fromtuple = args[3];
557 [ + + ]: 3136 : if (n_args >= 5) {
558 : 1819 : level = MP_OBJ_SMALL_INT_VALUE(args[4]);
559 [ + + ]: 1819 : if (level < 0) {
560 : 2 : mp_raise_ValueError(NULL);
561 : : }
562 : : }
563 : : }
564 : :
565 : 3182 : size_t module_name_len;
566 : 3182 : const char *module_name = mp_obj_str_get_data(module_name_obj, &module_name_len);
567 : :
568 [ + + ]: 3180 : if (level != 0) {
569 : : // Turn "foo.bar" with level=3 into "<current module 3 components>.foo.bar".
570 : : // Current module name is extracted from globals().__name__.
571 : 110 : evaluate_relative_import(level, &module_name, &module_name_len);
572 : : // module_name is now an absolute module path.
573 : : }
574 : :
575 [ + + ]: 3176 : if (module_name_len == 0) {
576 : 2 : mp_raise_ValueError(NULL);
577 : : }
578 : :
579 : : DEBUG_printf("Starting module search for '%s'\n", module_name);
580 : :
581 : : mp_obj_t top_module_obj = MP_OBJ_NULL;
582 : : mp_obj_t outer_module_obj = MP_OBJ_NULL;
583 : :
584 : : // Iterate the absolute path, finding the end of each component of the path.
585 : : // foo.bar.baz
586 : : // ^ ^ ^
587 : : size_t current_component_start = 0;
588 [ + + ]: 31098 : for (size_t i = 1; i <= module_name_len; i++) {
589 [ + + + + ]: 27986 : if (i == module_name_len || module_name[i] == '.') {
590 : : // The module name up to this depth (e.g. foo.bar.baz).
591 : 3325 : qstr full_mod_name = qstr_from_strn(module_name, i);
592 : : // The current level name (e.g. baz).
593 : 3319 : qstr level_mod_name = qstr_from_strn(module_name + current_component_start, i - current_component_start);
594 : :
595 : 3319 : DEBUG_printf("Processing module: '%s' at level '%s'\n", qstr_str(full_mod_name), qstr_str(level_mod_name));
596 : :
597 : : #if MICROPY_MODULE_OVERRIDE_MAIN_IMPORT
598 : : // On unix, if this is being loaded via -m (indicated by sentinel
599 : : // fromtuple=mp_const_false), then handle that if it's the final
600 : : // component.
601 [ + + + + ]: 3319 : bool override_main = (i == module_name_len && fromtuple == mp_const_false);
602 : : #else
603 : : bool override_main = false;
604 : : #endif
605 : :
606 : : // Import this module.
607 : 3319 : mp_obj_t module_obj = process_import_at_level(full_mod_name, level_mod_name, outer_module_obj, override_main);
608 : :
609 : : // Set this as the parent module, and remember the top-level module if it's the first.
610 : 3263 : outer_module_obj = module_obj;
611 [ + + ]: 3263 : if (top_module_obj == MP_OBJ_NULL) {
612 : 3120 : top_module_obj = module_obj;
613 : : }
614 : :
615 : 3263 : current_component_start = i + 1;
616 : : }
617 : : }
618 : :
619 [ + + ]: 3112 : if (fromtuple != mp_const_none) {
620 : : // If fromtuple is not empty, return leaf module
621 : : return outer_module_obj;
622 : : } else {
623 : : // Otherwise, we need to return top-level package
624 : 1325 : return top_module_obj;
625 : : }
626 : : }
627 : :
628 : : #else // MICROPY_ENABLE_EXTERNAL_IMPORT
629 : :
630 : : mp_obj_t mp_builtin___import___default(size_t n_args, const mp_obj_t *args) {
631 : : // Check that it's not a relative import.
632 : : if (n_args >= 5 && MP_OBJ_SMALL_INT_VALUE(args[4]) != 0) {
633 : : mp_raise_NotImplementedError(MP_ERROR_TEXT("relative import"));
634 : : }
635 : :
636 : : // Check if the module is already loaded.
637 : : mp_map_elem_t *elem = mp_map_lookup(&MP_STATE_VM(mp_loaded_modules_dict).map, args[0], MP_MAP_LOOKUP);
638 : : if (elem) {
639 : : return elem->value;
640 : : }
641 : :
642 : : // Try the name directly as a non-extensible built-in (e.g. `micropython`).
643 : : qstr module_name_qstr = mp_obj_str_get_qstr(args[0]);
644 : : mp_obj_t module_obj = mp_module_get_builtin(module_name_qstr, false);
645 : : if (module_obj != MP_OBJ_NULL) {
646 : : return module_obj;
647 : : }
648 : : // Now try as an extensible built-in (e.g. `time`).
649 : : module_obj = mp_module_get_builtin(module_name_qstr, true);
650 : : if (module_obj != MP_OBJ_NULL) {
651 : : return module_obj;
652 : : }
653 : :
654 : : // Couldn't find the module, so fail
655 : : #if MICROPY_ERROR_REPORTING <= MICROPY_ERROR_REPORTING_TERSE
656 : : mp_raise_msg(&mp_type_ImportError, MP_ERROR_TEXT("module not found"));
657 : : #else
658 : : mp_raise_msg_varg(&mp_type_ImportError, MP_ERROR_TEXT("no module named '%q'"), module_name_qstr);
659 : : #endif
660 : : }
661 : :
662 : : #endif // MICROPY_ENABLE_EXTERNAL_IMPORT
663 : :
664 : : MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(mp_builtin___import___obj, 1, 5, mp_builtin___import__);
|