builtinimport.c 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511
  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. *
  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. #include <stdio.h>
  28. #include <string.h>
  29. #include <assert.h>
  30. #include "py/compile.h"
  31. #include "py/objmodule.h"
  32. #include "py/persistentcode.h"
  33. #include "py/runtime.h"
  34. #include "py/builtin.h"
  35. #include "py/frozenmod.h"
  36. #if MICROPY_DEBUG_VERBOSE // print debugging info
  37. #define DEBUG_PRINT (1)
  38. #define DEBUG_printf DEBUG_printf
  39. #else // don't print debugging info
  40. #define DEBUG_PRINT (0)
  41. #define DEBUG_printf(...) (void)0
  42. #endif
  43. #if MICROPY_ENABLE_EXTERNAL_IMPORT
  44. #define PATH_SEP_CHAR '/'
  45. bool mp_obj_is_package(mp_obj_t module) {
  46. mp_obj_t dest[2];
  47. mp_load_method_maybe(module, MP_QSTR___path__, dest);
  48. return dest[0] != MP_OBJ_NULL;
  49. }
  50. // Stat either frozen or normal module by a given path
  51. // (whatever is available, if at all).
  52. STATIC mp_import_stat_t mp_import_stat_any(const char *path) {
  53. #if MICROPY_MODULE_FROZEN
  54. mp_import_stat_t st = mp_frozen_stat(path);
  55. if (st != MP_IMPORT_STAT_NO_EXIST) {
  56. return st;
  57. }
  58. #endif
  59. return mp_import_stat(path);
  60. }
  61. STATIC mp_import_stat_t stat_file_py_or_mpy(vstr_t *path) {
  62. mp_import_stat_t stat = mp_import_stat_any(vstr_null_terminated_str(path));
  63. if (stat == MP_IMPORT_STAT_FILE) {
  64. return stat;
  65. }
  66. #if MICROPY_PERSISTENT_CODE_LOAD
  67. vstr_ins_byte(path, path->len - 2, 'm');
  68. stat = mp_import_stat_any(vstr_null_terminated_str(path));
  69. if (stat == MP_IMPORT_STAT_FILE) {
  70. return stat;
  71. }
  72. #endif
  73. return MP_IMPORT_STAT_NO_EXIST;
  74. }
  75. STATIC mp_import_stat_t stat_dir_or_file(vstr_t *path) {
  76. mp_import_stat_t stat = mp_import_stat_any(vstr_null_terminated_str(path));
  77. DEBUG_printf("stat %s: %d\n", vstr_str(path), stat);
  78. if (stat == MP_IMPORT_STAT_DIR) {
  79. return stat;
  80. }
  81. // not a directory, add .py and try as a file
  82. vstr_add_str(path, ".py");
  83. return stat_file_py_or_mpy(path);
  84. }
  85. STATIC mp_import_stat_t find_file(const char *file_str, uint file_len, vstr_t *dest) {
  86. #if MICROPY_PY_SYS
  87. // extract the list of paths
  88. size_t path_num;
  89. mp_obj_t *path_items;
  90. mp_obj_list_get(mp_sys_path, &path_num, &path_items);
  91. if (path_num != 0) {
  92. // go through each path looking for a directory or file
  93. for (size_t i = 0; i < path_num; i++) {
  94. vstr_reset(dest);
  95. size_t p_len;
  96. const char *p = mp_obj_str_get_data(path_items[i], &p_len);
  97. if (p_len > 0) {
  98. vstr_add_strn(dest, p, p_len);
  99. vstr_add_char(dest, PATH_SEP_CHAR);
  100. }
  101. vstr_add_strn(dest, file_str, file_len);
  102. mp_import_stat_t stat = stat_dir_or_file(dest);
  103. if (stat != MP_IMPORT_STAT_NO_EXIST) {
  104. return stat;
  105. }
  106. }
  107. // could not find a directory or file
  108. return MP_IMPORT_STAT_NO_EXIST;
  109. }
  110. #endif
  111. // mp_sys_path is empty, so just use the given file name
  112. vstr_add_strn(dest, file_str, file_len);
  113. return stat_dir_or_file(dest);
  114. }
  115. #if MICROPY_MODULE_FROZEN_STR || MICROPY_ENABLE_COMPILER
  116. STATIC void do_load_from_lexer(mp_obj_t module_obj, mp_lexer_t *lex) {
  117. #if MICROPY_PY___FILE__
  118. qstr source_name = lex->source_name;
  119. mp_store_attr(module_obj, MP_QSTR___file__, MP_OBJ_NEW_QSTR(source_name));
  120. #endif
  121. // parse, compile and execute the module in its context
  122. mp_obj_dict_t *mod_globals = mp_obj_module_get_globals(module_obj);
  123. mp_parse_compile_execute(lex, MP_PARSE_FILE_INPUT, mod_globals, mod_globals);
  124. }
  125. #endif
  126. #if MICROPY_PERSISTENT_CODE_LOAD || MICROPY_MODULE_FROZEN_MPY
  127. STATIC void do_execute_raw_code(mp_obj_t module_obj, mp_raw_code_t *raw_code, const char *source_name) {
  128. (void)source_name;
  129. #if MICROPY_PY___FILE__
  130. mp_store_attr(module_obj, MP_QSTR___file__, MP_OBJ_NEW_QSTR(qstr_from_str(source_name)));
  131. #endif
  132. // execute the module in its context
  133. mp_obj_dict_t *mod_globals = mp_obj_module_get_globals(module_obj);
  134. // save context
  135. mp_obj_dict_t *volatile old_globals = mp_globals_get();
  136. mp_obj_dict_t *volatile old_locals = mp_locals_get();
  137. // set new context
  138. mp_globals_set(mod_globals);
  139. mp_locals_set(mod_globals);
  140. nlr_buf_t nlr;
  141. if (nlr_push(&nlr) == 0) {
  142. mp_obj_t module_fun = mp_make_function_from_raw_code(raw_code, MP_OBJ_NULL, MP_OBJ_NULL);
  143. mp_call_function_0(module_fun);
  144. // finish nlr block, restore context
  145. nlr_pop();
  146. mp_globals_set(old_globals);
  147. mp_locals_set(old_locals);
  148. } else {
  149. // exception; restore context and re-raise same exception
  150. mp_globals_set(old_globals);
  151. mp_locals_set(old_locals);
  152. nlr_jump(nlr.ret_val);
  153. }
  154. }
  155. #endif
  156. STATIC void do_load(mp_obj_t module_obj, vstr_t *file) {
  157. #if MICROPY_MODULE_FROZEN || MICROPY_ENABLE_COMPILER || (MICROPY_PERSISTENT_CODE_LOAD && MICROPY_HAS_FILE_READER)
  158. char *file_str = vstr_null_terminated_str(file);
  159. #endif
  160. // If we support frozen modules (either as str or mpy) then try to find the
  161. // requested filename in the list of frozen module filenames.
  162. #if MICROPY_MODULE_FROZEN
  163. void *modref;
  164. int frozen_type = mp_find_frozen_module(file_str, file->len, &modref);
  165. #endif
  166. // If we support frozen str modules and the compiler is enabled, and we
  167. // found the filename in the list of frozen files, then load and execute it.
  168. #if MICROPY_MODULE_FROZEN_STR
  169. if (frozen_type == MP_FROZEN_STR) {
  170. do_load_from_lexer(module_obj, modref);
  171. return;
  172. }
  173. #endif
  174. // If we support frozen mpy modules and we found a corresponding file (and
  175. // its data) in the list of frozen files, execute it.
  176. #if MICROPY_MODULE_FROZEN_MPY
  177. if (frozen_type == MP_FROZEN_MPY) {
  178. do_execute_raw_code(module_obj, modref, file_str);
  179. return;
  180. }
  181. #endif
  182. // If we support loading .mpy files then check if the file extension is of
  183. // the correct format and, if so, load and execute the file.
  184. #if MICROPY_HAS_FILE_READER && MICROPY_PERSISTENT_CODE_LOAD
  185. if (file_str[file->len - 3] == 'm') {
  186. mp_raw_code_t *raw_code = mp_raw_code_load_file(file_str);
  187. do_execute_raw_code(module_obj, raw_code, file_str);
  188. return;
  189. }
  190. #endif
  191. // If we can compile scripts then load the file and compile and execute it.
  192. #if MICROPY_ENABLE_COMPILER
  193. {
  194. mp_lexer_t *lex = mp_lexer_new_from_file(file_str);
  195. do_load_from_lexer(module_obj, lex);
  196. return;
  197. }
  198. #else
  199. // If we get here then the file was not frozen and we can't compile scripts.
  200. mp_raise_msg(&mp_type_ImportError, MP_ERROR_TEXT("script compilation not supported"));
  201. #endif
  202. }
  203. STATIC void chop_component(const char *start, const char **end) {
  204. const char *p = *end;
  205. while (p > start) {
  206. if (*--p == '.') {
  207. *end = p;
  208. return;
  209. }
  210. }
  211. *end = p;
  212. }
  213. mp_obj_t mp_builtin___import__(size_t n_args, const mp_obj_t *args) {
  214. #if DEBUG_PRINT
  215. DEBUG_printf("__import__:\n");
  216. for (size_t i = 0; i < n_args; i++) {
  217. DEBUG_printf(" ");
  218. mp_obj_print(args[i], PRINT_REPR);
  219. DEBUG_printf("\n");
  220. }
  221. #endif
  222. mp_obj_t module_name = args[0];
  223. mp_obj_t fromtuple = mp_const_none;
  224. mp_int_t level = 0;
  225. if (n_args >= 4) {
  226. fromtuple = args[3];
  227. if (n_args >= 5) {
  228. level = MP_OBJ_SMALL_INT_VALUE(args[4]);
  229. if (level < 0) {
  230. mp_raise_ValueError(NULL);
  231. }
  232. }
  233. }
  234. size_t mod_len;
  235. const char *mod_str = mp_obj_str_get_data(module_name, &mod_len);
  236. if (level != 0) {
  237. // What we want to do here is to take name of current module,
  238. // chop <level> trailing components, and concatenate with passed-in
  239. // module name, thus resolving relative import name into absolute.
  240. // This even appears to be correct per
  241. // http://legacy.python.org/dev/peps/pep-0328/#relative-imports-and-name
  242. // "Relative imports use a module's __name__ attribute to determine that
  243. // module's position in the package hierarchy."
  244. level--;
  245. mp_obj_t this_name_q = mp_obj_dict_get(MP_OBJ_FROM_PTR(mp_globals_get()), MP_OBJ_NEW_QSTR(MP_QSTR___name__));
  246. assert(this_name_q != MP_OBJ_NULL);
  247. #if MICROPY_CPYTHON_COMPAT
  248. if (MP_OBJ_QSTR_VALUE(this_name_q) == MP_QSTR___main__) {
  249. // This is a module run by -m command-line switch, get its real name from backup attribute
  250. this_name_q = mp_obj_dict_get(MP_OBJ_FROM_PTR(mp_globals_get()), MP_OBJ_NEW_QSTR(MP_QSTR___main__));
  251. }
  252. #endif
  253. mp_map_t *globals_map = &mp_globals_get()->map;
  254. mp_map_elem_t *elem = mp_map_lookup(globals_map, MP_OBJ_NEW_QSTR(MP_QSTR___path__), MP_MAP_LOOKUP);
  255. bool is_pkg = (elem != NULL);
  256. #if DEBUG_PRINT
  257. DEBUG_printf("Current module/package: ");
  258. mp_obj_print(this_name_q, PRINT_REPR);
  259. DEBUG_printf(", is_package: %d", is_pkg);
  260. DEBUG_printf("\n");
  261. #endif
  262. size_t this_name_l;
  263. const char *this_name = mp_obj_str_get_data(this_name_q, &this_name_l);
  264. const char *p = this_name + this_name_l;
  265. if (!is_pkg) {
  266. // We have module, but relative imports are anchored at package, so
  267. // go there.
  268. chop_component(this_name, &p);
  269. }
  270. while (level--) {
  271. chop_component(this_name, &p);
  272. }
  273. // We must have some component left over to import from
  274. if (p == this_name) {
  275. mp_raise_ValueError(MP_ERROR_TEXT("can't perform relative import"));
  276. }
  277. uint new_mod_l = (mod_len == 0 ? (size_t)(p - this_name) : (size_t)(p - this_name) + 1 + mod_len);
  278. char *new_mod = mp_local_alloc(new_mod_l);
  279. memcpy(new_mod, this_name, p - this_name);
  280. if (mod_len != 0) {
  281. new_mod[p - this_name] = '.';
  282. memcpy(new_mod + (p - this_name) + 1, mod_str, mod_len);
  283. }
  284. qstr new_mod_q = qstr_from_strn(new_mod, new_mod_l);
  285. mp_local_free(new_mod);
  286. DEBUG_printf("Resolved base name for relative import: '%s'\n", qstr_str(new_mod_q));
  287. module_name = MP_OBJ_NEW_QSTR(new_mod_q);
  288. mod_str = qstr_str(new_mod_q);
  289. mod_len = new_mod_l;
  290. }
  291. if (mod_len == 0) {
  292. mp_raise_ValueError(NULL);
  293. }
  294. // check if module already exists
  295. qstr module_name_qstr = mp_obj_str_get_qstr(module_name);
  296. mp_obj_t module_obj = mp_module_get(module_name_qstr);
  297. if (module_obj != MP_OBJ_NULL) {
  298. DEBUG_printf("Module already loaded\n");
  299. // If it's not a package, return module right away
  300. char *p = strchr(mod_str, '.');
  301. if (p == NULL) {
  302. return module_obj;
  303. }
  304. // If fromlist is not empty, return leaf module
  305. if (fromtuple != mp_const_none) {
  306. return module_obj;
  307. }
  308. // Otherwise, we need to return top-level package
  309. qstr pkg_name = qstr_from_strn(mod_str, p - mod_str);
  310. return mp_module_get(pkg_name);
  311. }
  312. DEBUG_printf("Module not yet loaded\n");
  313. uint last = 0;
  314. VSTR_FIXED(path, MICROPY_ALLOC_PATH_MAX)
  315. module_obj = MP_OBJ_NULL;
  316. mp_obj_t top_module_obj = MP_OBJ_NULL;
  317. mp_obj_t outer_module_obj = MP_OBJ_NULL;
  318. uint i;
  319. for (i = 1; i <= mod_len; i++) {
  320. if (i == mod_len || mod_str[i] == '.') {
  321. // create a qstr for the module name up to this depth
  322. qstr mod_name = qstr_from_strn(mod_str, i);
  323. DEBUG_printf("Processing module: %s\n", qstr_str(mod_name));
  324. DEBUG_printf("Previous path: =%.*s=\n", vstr_len(&path), vstr_str(&path));
  325. // find the file corresponding to the module name
  326. mp_import_stat_t stat;
  327. if (vstr_len(&path) == 0) {
  328. // first module in the dotted-name; search for a directory or file
  329. stat = find_file(mod_str, i, &path);
  330. } else {
  331. // latter module in the dotted-name; append to path
  332. vstr_add_char(&path, PATH_SEP_CHAR);
  333. vstr_add_strn(&path, mod_str + last, i - last);
  334. stat = stat_dir_or_file(&path);
  335. }
  336. DEBUG_printf("Current path: %.*s\n", vstr_len(&path), vstr_str(&path));
  337. if (stat == MP_IMPORT_STAT_NO_EXIST) {
  338. module_obj = MP_OBJ_NULL;
  339. #if MICROPY_MODULE_WEAK_LINKS
  340. // check if there is a weak link to this module
  341. if (i == mod_len) {
  342. module_obj = mp_module_search_umodule(mod_str);
  343. if (module_obj != MP_OBJ_NULL) {
  344. // found weak linked module
  345. mp_module_call_init(mod_name, module_obj);
  346. }
  347. }
  348. #endif
  349. if (module_obj == MP_OBJ_NULL) {
  350. // couldn't find the file, so fail
  351. #if MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE
  352. mp_raise_msg(&mp_type_ImportError, MP_ERROR_TEXT("module not found"));
  353. #else
  354. mp_raise_msg_varg(&mp_type_ImportError, MP_ERROR_TEXT("no module named '%q'"), mod_name);
  355. #endif
  356. }
  357. } else {
  358. // found the file, so get the module
  359. module_obj = mp_module_get(mod_name);
  360. }
  361. if (module_obj == MP_OBJ_NULL) {
  362. // module not already loaded, so load it!
  363. module_obj = mp_obj_new_module(mod_name);
  364. // if args[3] (fromtuple) has magic value False, set up
  365. // this module for command-line "-m" option (set module's
  366. // name to __main__ instead of real name). Do this only
  367. // for *modules* however - packages never have their names
  368. // replaced, instead they're -m'ed using a special __main__
  369. // submodule in them. (This all apparently is done to not
  370. // touch package name itself, which is important for future
  371. // imports).
  372. if (i == mod_len && fromtuple == mp_const_false && stat != MP_IMPORT_STAT_DIR) {
  373. mp_obj_module_t *o = MP_OBJ_TO_PTR(module_obj);
  374. mp_obj_dict_store(MP_OBJ_FROM_PTR(o->globals), MP_OBJ_NEW_QSTR(MP_QSTR___name__), MP_OBJ_NEW_QSTR(MP_QSTR___main__));
  375. #if MICROPY_CPYTHON_COMPAT
  376. // Store module as "__main__" in the dictionary of loaded modules (returned by sys.modules).
  377. mp_obj_dict_store(MP_OBJ_FROM_PTR(&MP_STATE_VM(mp_loaded_modules_dict)), MP_OBJ_NEW_QSTR(MP_QSTR___main__), module_obj);
  378. // Store real name in "__main__" attribute. Chosen semi-randonly, to reuse existing qstr's.
  379. mp_obj_dict_store(MP_OBJ_FROM_PTR(o->globals), MP_OBJ_NEW_QSTR(MP_QSTR___main__), MP_OBJ_NEW_QSTR(mod_name));
  380. #endif
  381. }
  382. if (stat == MP_IMPORT_STAT_DIR) {
  383. DEBUG_printf("%.*s is dir\n", vstr_len(&path), vstr_str(&path));
  384. // https://docs.python.org/3/reference/import.html
  385. // "Specifically, any module that contains a __path__ attribute is considered a package."
  386. mp_store_attr(module_obj, MP_QSTR___path__, mp_obj_new_str(vstr_str(&path), vstr_len(&path)));
  387. size_t orig_path_len = path.len;
  388. vstr_add_char(&path, PATH_SEP_CHAR);
  389. vstr_add_str(&path, "__init__.py");
  390. if (stat_file_py_or_mpy(&path) != MP_IMPORT_STAT_FILE) {
  391. // mp_warning("%s is imported as namespace package", vstr_str(&path));
  392. } else {
  393. do_load(module_obj, &path);
  394. }
  395. path.len = orig_path_len;
  396. } else { // MP_IMPORT_STAT_FILE
  397. do_load(module_obj, &path);
  398. // This should be the last component in the import path. If there are
  399. // remaining components then it's an ImportError because the current path
  400. // (the module that was just loaded) is not a package. This will be caught
  401. // on the next iteration because the file will not exist.
  402. }
  403. }
  404. if (outer_module_obj != MP_OBJ_NULL) {
  405. qstr s = qstr_from_strn(mod_str + last, i - last);
  406. mp_store_attr(outer_module_obj, s, module_obj);
  407. }
  408. outer_module_obj = module_obj;
  409. if (top_module_obj == MP_OBJ_NULL) {
  410. top_module_obj = module_obj;
  411. }
  412. last = i + 1;
  413. }
  414. }
  415. // If fromlist is not empty, return leaf module
  416. if (fromtuple != mp_const_none) {
  417. return module_obj;
  418. }
  419. // Otherwise, we need to return top-level package
  420. return top_module_obj;
  421. }
  422. #else // MICROPY_ENABLE_EXTERNAL_IMPORT
  423. mp_obj_t mp_builtin___import__(size_t n_args, const mp_obj_t *args) {
  424. // Check that it's not a relative import
  425. if (n_args >= 5 && MP_OBJ_SMALL_INT_VALUE(args[4]) != 0) {
  426. mp_raise_NotImplementedError(MP_ERROR_TEXT("relative import"));
  427. }
  428. // Check if module already exists, and return it if it does
  429. qstr module_name_qstr = mp_obj_str_get_qstr(args[0]);
  430. mp_obj_t module_obj = mp_module_get(module_name_qstr);
  431. if (module_obj != MP_OBJ_NULL) {
  432. return module_obj;
  433. }
  434. #if MICROPY_MODULE_WEAK_LINKS
  435. // Check if there is a weak link to this module
  436. module_obj = mp_module_search_umodule(qstr_str(module_name_qstr));
  437. if (module_obj != MP_OBJ_NULL) {
  438. // Found weak-linked module
  439. mp_module_call_init(module_name_qstr, module_obj);
  440. return module_obj;
  441. }
  442. #endif
  443. // Couldn't find the module, so fail
  444. #if MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE
  445. mp_raise_msg(&mp_type_ImportError, MP_ERROR_TEXT("module not found"));
  446. #else
  447. mp_raise_msg_varg(&mp_type_ImportError, MP_ERROR_TEXT("no module named '%q'"), module_name_qstr);
  448. #endif
  449. }
  450. #endif // MICROPY_ENABLE_EXTERNAL_IMPORT
  451. MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(mp_builtin___import___obj, 1, 5, mp_builtin___import__);