builtinimport.c 19 KB

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