PageRenderTime 55ms CodeModel.GetById 17ms RepoModel.GetById 0ms app.codeStats 0ms

/pypy/module/imp/importing.py

https://bitbucket.org/pypy/pypy/
Python | 1099 lines | 947 code | 61 blank | 91 comment | 102 complexity | c381ef8159b932c14ede25ef92f9fafa MD5 | raw file
Possible License(s): AGPL-3.0, BSD-3-Clause, Apache-2.0
  1. """
  2. Implementation of the interpreter-level default import logic.
  3. """
  4. import sys, os, stat
  5. from pypy.interpreter.module import Module
  6. from pypy.interpreter.gateway import interp2app, unwrap_spec
  7. from pypy.interpreter.typedef import TypeDef, generic_new_descr
  8. from pypy.interpreter.error import OperationError, oefmt
  9. from pypy.interpreter.baseobjspace import W_Root, CannotHaveLock
  10. from pypy.interpreter.eval import Code
  11. from pypy.interpreter.pycode import PyCode
  12. from rpython.rlib import streamio, jit
  13. from rpython.rlib.streamio import StreamErrors
  14. from rpython.rlib.objectmodel import we_are_translated, specialize
  15. from pypy.module.sys.version import PYPY_VERSION
  16. _WIN32 = sys.platform == 'win32'
  17. SEARCH_ERROR = 0
  18. PY_SOURCE = 1
  19. PY_COMPILED = 2
  20. C_EXTENSION = 3
  21. # PY_RESOURCE = 4
  22. PKG_DIRECTORY = 5
  23. C_BUILTIN = 6
  24. PY_FROZEN = 7
  25. # PY_CODERESOURCE = 8
  26. IMP_HOOK = 9
  27. SO = '.pyd' if _WIN32 else '.so'
  28. # this used to change for every minor version, but no longer does: there
  29. # is little point any more, as the so's tend to be cross-version-
  30. # compatible, more so than between various versions of CPython. Be
  31. # careful if we need to update it again: it is now used for both cpyext
  32. # and cffi so's. If we do have to update it, we'd likely need a way to
  33. # split the two usages again.
  34. #DEFAULT_SOABI = 'pypy-%d%d' % PYPY_VERSION[:2]
  35. DEFAULT_SOABI = 'pypy-41'
  36. @specialize.memo()
  37. def get_so_extension(space):
  38. if space.config.objspace.soabi is not None:
  39. soabi = space.config.objspace.soabi
  40. else:
  41. soabi = DEFAULT_SOABI
  42. if not soabi:
  43. return SO
  44. if not space.config.translating:
  45. soabi += 'i'
  46. return '.' + soabi + SO
  47. def log_pyverbose(space, level, message):
  48. if space.sys.w_initialdict is None:
  49. return # sys module not initialised, avoid recursion
  50. verbose = space.sys.get_flag('verbose')
  51. if verbose >= level:
  52. w_stderr = space.sys.get('stderr')
  53. space.call_method(w_stderr, "write", space.wrap(message))
  54. def file_exists(path):
  55. """Tests whether the given path is an existing regular file."""
  56. return os.path.isfile(path) and case_ok(path)
  57. def has_so_extension(space):
  58. return (space.config.objspace.usemodules.cpyext or
  59. space.config.objspace.usemodules._cffi_backend)
  60. def find_modtype(space, filepart):
  61. """Check which kind of module to import for the given filepart,
  62. which is a path without extension. Returns PY_SOURCE, PY_COMPILED or
  63. SEARCH_ERROR.
  64. """
  65. # check the .py file
  66. pyfile = filepart + ".py"
  67. if file_exists(pyfile):
  68. return PY_SOURCE, ".py", "U"
  69. # on Windows, also check for a .pyw file
  70. if _WIN32:
  71. pyfile = filepart + ".pyw"
  72. if file_exists(pyfile):
  73. return PY_SOURCE, ".pyw", "U"
  74. # The .py file does not exist. By default on PyPy, lonepycfiles
  75. # is False: if a .py file does not exist, we don't even try to
  76. # look for a lone .pyc file.
  77. # The "imp" module does not respect this, and is allowed to find
  78. # lone .pyc files.
  79. # check the .pyc file
  80. if space.config.objspace.lonepycfiles:
  81. pycfile = filepart + ".pyc"
  82. if file_exists(pycfile):
  83. # existing .pyc file
  84. return PY_COMPILED, ".pyc", "rb"
  85. if has_so_extension(space):
  86. so_extension = get_so_extension(space)
  87. pydfile = filepart + so_extension
  88. if file_exists(pydfile):
  89. return C_EXTENSION, so_extension, "rb"
  90. return SEARCH_ERROR, None, None
  91. if sys.platform.startswith('linux') or 'freebsd' in sys.platform:
  92. def case_ok(filename):
  93. return True
  94. else:
  95. # XXX that's slow
  96. def case_ok(filename):
  97. index = filename.rfind(os.sep)
  98. if os.altsep is not None:
  99. index2 = filename.rfind(os.altsep)
  100. index = max(index, index2)
  101. if index < 0:
  102. directory = os.curdir
  103. else:
  104. directory = filename[:index+1]
  105. filename = filename[index+1:]
  106. try:
  107. return filename in os.listdir(directory)
  108. except OSError:
  109. return False
  110. def try_getattr(space, w_obj, w_name):
  111. try:
  112. return space.getattr(w_obj, w_name)
  113. except OperationError:
  114. # ugh, but blame CPython :-/ this is supposed to emulate
  115. # hasattr, which eats all exceptions.
  116. return None
  117. def check_sys_modules(space, w_modulename):
  118. return space.finditem(space.sys.get('modules'), w_modulename)
  119. def check_sys_modules_w(space, modulename):
  120. return space.finditem_str(space.sys.get('modules'), modulename)
  121. @jit.elidable
  122. def _get_dot_position(str, n):
  123. # return the index in str of the '.' such that there are n '.'-separated
  124. # strings after it
  125. result = len(str)
  126. while n > 0 and result >= 0:
  127. n -= 1
  128. result = str.rfind('.', 0, result)
  129. return result
  130. def _get_relative_name(space, modulename, level, w_globals):
  131. w = space.wrap
  132. ctxt_w_package = space.finditem_str(w_globals, '__package__')
  133. ctxt_w_package = jit.promote(ctxt_w_package)
  134. level = jit.promote(level)
  135. ctxt_package = None
  136. if ctxt_w_package is not None and ctxt_w_package is not space.w_None:
  137. try:
  138. ctxt_package = space.str0_w(ctxt_w_package)
  139. except OperationError as e:
  140. if not e.match(space, space.w_TypeError):
  141. raise
  142. raise oefmt(space.w_ValueError, "__package__ set to non-string")
  143. if ctxt_package is not None:
  144. # __package__ is set, so use it
  145. if ctxt_package == '' and level < 0:
  146. return None, 0
  147. dot_position = _get_dot_position(ctxt_package, level - 1)
  148. if dot_position < 0:
  149. if len(ctxt_package) == 0:
  150. where = "in non-package"
  151. else:
  152. where = "beyond toplevel package"
  153. raise oefmt(space.w_ValueError,
  154. "Attempted relative import %s", where)
  155. # Try to import parent package
  156. try:
  157. absolute_import(space, ctxt_package, 0, None, tentative=False)
  158. except OperationError as e:
  159. if not e.match(space, space.w_ImportError):
  160. raise
  161. if level > 0:
  162. raise oefmt(space.w_SystemError,
  163. "Parent module '%s' not loaded, cannot perform "
  164. "relative import", ctxt_package)
  165. else:
  166. msg = ("Parent module '%s' not found while handling absolute "
  167. "import" % ctxt_package)
  168. space.warn(space.wrap(msg), space.w_RuntimeWarning)
  169. rel_modulename = ctxt_package[:dot_position]
  170. rel_level = rel_modulename.count('.') + 1
  171. if modulename:
  172. rel_modulename += '.' + modulename
  173. else:
  174. # __package__ not set, so figure it out and set it
  175. ctxt_w_name = space.finditem_str(w_globals, '__name__')
  176. ctxt_w_path = space.finditem_str(w_globals, '__path__')
  177. ctxt_w_name = jit.promote(ctxt_w_name)
  178. ctxt_name = None
  179. if ctxt_w_name is not None:
  180. try:
  181. ctxt_name = space.str0_w(ctxt_w_name)
  182. except OperationError as e:
  183. if not e.match(space, space.w_TypeError):
  184. raise
  185. if not ctxt_name:
  186. return None, 0
  187. m = max(level - 1, 0)
  188. if ctxt_w_path is None: # plain module
  189. m += 1
  190. dot_position = _get_dot_position(ctxt_name, m)
  191. if dot_position < 0:
  192. if level > 0:
  193. raise oefmt(space.w_ValueError,
  194. "Attempted relative import in non-package")
  195. rel_modulename = ''
  196. rel_level = 0
  197. else:
  198. rel_modulename = ctxt_name[:dot_position]
  199. rel_level = rel_modulename.count('.') + 1
  200. if ctxt_w_path is not None:
  201. # __path__ is set, so __name__ is already the package name
  202. space.setitem(w_globals, w("__package__"), ctxt_w_name)
  203. else:
  204. # Normal module, so work out the package name if any
  205. last_dot_position = ctxt_name.rfind('.')
  206. if last_dot_position < 0:
  207. space.setitem(w_globals, w("__package__"), space.w_None)
  208. else:
  209. space.setitem(w_globals, w("__package__"),
  210. w(ctxt_name[:last_dot_position]))
  211. if modulename:
  212. if rel_modulename:
  213. rel_modulename += '.' + modulename
  214. else:
  215. rel_modulename = modulename
  216. return rel_modulename, rel_level
  217. @unwrap_spec(name='str0', level=int)
  218. def importhook(space, name, w_globals=None,
  219. w_locals=None, w_fromlist=None, level=-1):
  220. modulename = name
  221. if not modulename and level < 0:
  222. raise oefmt(space.w_ValueError, "Empty module name")
  223. w = space.wrap
  224. if w_fromlist is not None and space.is_true(w_fromlist):
  225. fromlist_w = space.fixedview(w_fromlist)
  226. else:
  227. fromlist_w = None
  228. rel_modulename = None
  229. if (level != 0 and w_globals is not None and
  230. space.isinstance_w(w_globals, space.w_dict)):
  231. rel_modulename, rel_level = _get_relative_name(space, modulename, level,
  232. w_globals)
  233. if rel_modulename:
  234. # if no level was set, ignore import errors, and
  235. # fall back to absolute import at the end of the
  236. # function.
  237. if level == -1:
  238. # This check is a fast path to avoid redoing the
  239. # following absolute_import() in the common case
  240. w_mod = check_sys_modules_w(space, rel_modulename)
  241. if w_mod is not None and space.is_w(w_mod, space.w_None):
  242. # if we already find space.w_None, it means that we
  243. # already tried and failed and fell back to the
  244. # end of this function.
  245. w_mod = None
  246. else:
  247. w_mod = absolute_import(space, rel_modulename, rel_level,
  248. fromlist_w, tentative=True)
  249. else:
  250. w_mod = absolute_import(space, rel_modulename, rel_level,
  251. fromlist_w, tentative=False)
  252. if w_mod is not None:
  253. return w_mod
  254. w_mod = absolute_import(space, modulename, 0, fromlist_w, tentative=0)
  255. if rel_modulename is not None:
  256. space.setitem(space.sys.get('modules'), w(rel_modulename), space.w_None)
  257. return w_mod
  258. def absolute_import(space, modulename, baselevel, fromlist_w, tentative):
  259. # Short path: check in sys.modules, but only if there is no conflict
  260. # on the import lock. In the situation of 'import' statements
  261. # inside tight loops, this should be true, and absolute_import_try()
  262. # should be followed by the JIT and turned into not much code. But
  263. # if the import lock is currently held by another thread, then we
  264. # have to wait, and so shouldn't use the fast path.
  265. if not getimportlock(space).lock_held_by_someone_else():
  266. w_mod = absolute_import_try(space, modulename, baselevel, fromlist_w)
  267. if w_mod is not None and not space.is_w(w_mod, space.w_None):
  268. return w_mod
  269. return absolute_import_with_lock(space, modulename, baselevel,
  270. fromlist_w, tentative)
  271. @jit.dont_look_inside
  272. def absolute_import_with_lock(space, modulename, baselevel,
  273. fromlist_w, tentative):
  274. lock = getimportlock(space)
  275. lock.acquire_lock()
  276. try:
  277. return _absolute_import(space, modulename, baselevel,
  278. fromlist_w, tentative)
  279. finally:
  280. lock.release_lock(silent_after_fork=True)
  281. @jit.unroll_safe
  282. def absolute_import_try(space, modulename, baselevel, fromlist_w):
  283. """ Only look up sys.modules, not actually try to load anything
  284. """
  285. w_path = None
  286. last_dot = 0
  287. if '.' not in modulename:
  288. w_mod = check_sys_modules_w(space, modulename)
  289. first = w_mod
  290. if fromlist_w is not None and w_mod is not None:
  291. w_path = try_getattr(space, w_mod, space.wrap('__path__'))
  292. else:
  293. level = 0
  294. first = None
  295. while last_dot >= 0:
  296. last_dot = modulename.find('.', last_dot + 1)
  297. if last_dot < 0:
  298. w_mod = check_sys_modules_w(space, modulename)
  299. else:
  300. w_mod = check_sys_modules_w(space, modulename[:last_dot])
  301. if w_mod is None or space.is_w(w_mod, space.w_None):
  302. return None
  303. if level == baselevel:
  304. first = w_mod
  305. if fromlist_w is not None:
  306. w_path = try_getattr(space, w_mod, space.wrap('__path__'))
  307. level += 1
  308. if fromlist_w is not None:
  309. if w_path is not None:
  310. if len(fromlist_w) == 1 and space.eq_w(fromlist_w[0],
  311. space.wrap('*')):
  312. w_all = try_getattr(space, w_mod, space.wrap('__all__'))
  313. if w_all is not None:
  314. fromlist_w = space.fixedview(w_all)
  315. else:
  316. fromlist_w = []
  317. # "from x import *" with x already imported and no x.__all__
  318. # always succeeds without doing more imports. It will
  319. # just copy everything from x.__dict__ as it is now.
  320. for w_name in fromlist_w:
  321. if try_getattr(space, w_mod, w_name) is None:
  322. return None
  323. return w_mod
  324. return first
  325. def _absolute_import(space, modulename, baselevel, fromlist_w, tentative):
  326. w = space.wrap
  327. if '/' in modulename or '\\' in modulename:
  328. raise oefmt(space.w_ImportError,
  329. "Import by filename is not supported.")
  330. w_mod = None
  331. parts = modulename.split('.')
  332. prefix = []
  333. w_path = None
  334. first = None
  335. level = 0
  336. for part in parts:
  337. w_mod = load_part(space, w_path, prefix, part, w_mod,
  338. tentative=tentative)
  339. if w_mod is None:
  340. return None
  341. if baselevel == level:
  342. first = w_mod
  343. tentative = 0
  344. prefix.append(part)
  345. w_path = try_getattr(space, w_mod, w('__path__'))
  346. level += 1
  347. if fromlist_w is not None:
  348. if w_path is not None:
  349. if len(fromlist_w) == 1 and space.eq_w(fromlist_w[0],w('*')):
  350. w_all = try_getattr(space, w_mod, w('__all__'))
  351. if w_all is not None:
  352. fromlist_w = space.fixedview(w_all)
  353. else:
  354. fromlist_w = []
  355. for w_name in fromlist_w:
  356. if try_getattr(space, w_mod, w_name) is None:
  357. load_part(space, w_path, prefix, space.str0_w(w_name),
  358. w_mod, tentative=1)
  359. return w_mod
  360. else:
  361. return first
  362. def find_in_meta_path(space, w_modulename, w_path):
  363. assert w_modulename is not None
  364. if w_path is None:
  365. w_path = space.w_None
  366. for w_hook in space.unpackiterable(space.sys.get("meta_path")):
  367. w_loader = space.call_method(w_hook, "find_module",
  368. w_modulename, w_path)
  369. if space.is_true(w_loader):
  370. return w_loader
  371. def _getimporter(space, w_pathitem):
  372. # the function 'imp._getimporter' is a pypy-only extension
  373. w_path_importer_cache = space.sys.get("path_importer_cache")
  374. w_importer = space.finditem(w_path_importer_cache, w_pathitem)
  375. if w_importer is None:
  376. space.setitem(w_path_importer_cache, w_pathitem, space.w_None)
  377. for w_hook in space.unpackiterable(space.sys.get("path_hooks")):
  378. try:
  379. w_importer = space.call_function(w_hook, w_pathitem)
  380. except OperationError as e:
  381. if not e.match(space, space.w_ImportError):
  382. raise
  383. else:
  384. break
  385. if w_importer is None:
  386. try:
  387. w_importer = space.call_function(
  388. space.gettypefor(W_NullImporter), w_pathitem
  389. )
  390. except OperationError as e:
  391. if e.match(space, space.w_ImportError):
  392. return None
  393. raise
  394. if space.is_true(w_importer):
  395. space.setitem(w_path_importer_cache, w_pathitem, w_importer)
  396. return w_importer
  397. def find_in_path_hooks(space, w_modulename, w_pathitem):
  398. w_importer = _getimporter(space, w_pathitem)
  399. if w_importer is not None and space.is_true(w_importer):
  400. try:
  401. w_loader = space.call_method(w_importer, "find_module", w_modulename)
  402. except OperationError as e:
  403. if e.match(space, space.w_ImportError):
  404. return None
  405. raise
  406. if space.is_true(w_loader):
  407. return w_loader
  408. class W_NullImporter(W_Root):
  409. def __init__(self, space):
  410. pass
  411. @unwrap_spec(path='str0')
  412. def descr_init(self, space, path):
  413. if not path:
  414. raise oefmt(space.w_ImportError, "empty pathname")
  415. # Directory should not exist
  416. try:
  417. st = os.stat(path)
  418. except OSError:
  419. pass
  420. else:
  421. if stat.S_ISDIR(st.st_mode):
  422. raise oefmt(space.w_ImportError, "existing directory")
  423. def find_module_w(self, space, __args__):
  424. return space.wrap(None)
  425. W_NullImporter.typedef = TypeDef(
  426. 'imp.NullImporter',
  427. __new__=generic_new_descr(W_NullImporter),
  428. __init__=interp2app(W_NullImporter.descr_init),
  429. find_module=interp2app(W_NullImporter.find_module_w),
  430. )
  431. class FindInfo:
  432. def __init__(self, modtype, filename, stream,
  433. suffix="", filemode="", w_loader=None):
  434. self.modtype = modtype
  435. self.filename = filename
  436. self.stream = stream
  437. self.suffix = suffix
  438. self.filemode = filemode
  439. self.w_loader = w_loader
  440. @staticmethod
  441. def fromLoader(w_loader):
  442. return FindInfo(IMP_HOOK, '', None, w_loader=w_loader)
  443. def find_module(space, modulename, w_modulename, partname, w_path,
  444. use_loader=True):
  445. # Examin importhooks (PEP302) before doing the import
  446. if use_loader:
  447. w_loader = find_in_meta_path(space, w_modulename, w_path)
  448. if w_loader:
  449. return FindInfo.fromLoader(w_loader)
  450. # XXX Check for frozen modules?
  451. # when w_path is a string
  452. delayed_builtin = None
  453. w_lib_extensions = None
  454. if w_path is None:
  455. # check the builtin modules
  456. if modulename in space.builtin_modules:
  457. delayed_builtin = FindInfo(C_BUILTIN, modulename, None)
  458. # a "real builtin module xx" shadows every file "xx.py" there
  459. # could possibly be; a "pseudo-extension module" does not, and
  460. # is only loaded at the point in sys.path where we find
  461. # '.../lib_pypy/__extensions__'.
  462. if modulename in space.MODULES_THAT_ALWAYS_SHADOW:
  463. return delayed_builtin
  464. w_lib_extensions = space.sys.get_state(space).w_lib_extensions
  465. w_path = space.sys.get('path')
  466. # XXX check frozen modules?
  467. # when w_path is null
  468. if w_path is not None:
  469. for w_pathitem in space.unpackiterable(w_path):
  470. # sys.path_hooks import hook
  471. if (w_lib_extensions is not None and
  472. space.eq_w(w_pathitem, w_lib_extensions)):
  473. return delayed_builtin
  474. if use_loader:
  475. w_loader = find_in_path_hooks(space, w_modulename, w_pathitem)
  476. if w_loader:
  477. return FindInfo.fromLoader(w_loader)
  478. path = space.str0_w(w_pathitem)
  479. filepart = os.path.join(path, partname)
  480. log_pyverbose(space, 2, "# trying %s" % (filepart,))
  481. if os.path.isdir(filepart) and case_ok(filepart):
  482. initfile = os.path.join(filepart, '__init__')
  483. modtype, _, _ = find_modtype(space, initfile)
  484. if modtype in (PY_SOURCE, PY_COMPILED):
  485. return FindInfo(PKG_DIRECTORY, filepart, None)
  486. else:
  487. msg = ("Not importing directory '%s' missing __init__.py" %
  488. (filepart,))
  489. space.warn(space.wrap(msg), space.w_ImportWarning)
  490. modtype, suffix, filemode = find_modtype(space, filepart)
  491. try:
  492. if modtype in (PY_SOURCE, PY_COMPILED, C_EXTENSION):
  493. assert suffix is not None
  494. filename = filepart + suffix
  495. stream = streamio.open_file_as_stream(filename, filemode)
  496. try:
  497. return FindInfo(modtype, filename, stream, suffix, filemode)
  498. except:
  499. stream.close()
  500. raise
  501. except StreamErrors:
  502. pass # XXX! must not eat all exceptions, e.g.
  503. # Out of file descriptors.
  504. # not found
  505. return delayed_builtin
  506. def _prepare_module(space, w_mod, filename, pkgdir):
  507. w = space.wrap
  508. space.sys.setmodule(w_mod)
  509. space.setattr(w_mod, w('__file__'), space.wrap(filename))
  510. space.setattr(w_mod, w('__doc__'), space.w_None)
  511. if pkgdir is not None:
  512. space.setattr(w_mod, w('__path__'), space.newlist([w(pkgdir)]))
  513. def add_module(space, w_name):
  514. w_mod = check_sys_modules(space, w_name)
  515. if w_mod is None:
  516. w_mod = space.wrap(Module(space, w_name))
  517. space.sys.setmodule(w_mod)
  518. return w_mod
  519. def load_c_extension(space, filename, modulename):
  520. from pypy.module.cpyext.api import load_extension_module
  521. log_pyverbose(space, 1, "import %s # from %s\n" %
  522. (modulename, filename))
  523. load_extension_module(space, filename, modulename)
  524. # NB. cpyext.api.load_extension_module() can also delegate to _cffi_backend
  525. @jit.dont_look_inside
  526. def load_module(space, w_modulename, find_info, reuse=False):
  527. if find_info is None:
  528. return
  529. if find_info.w_loader:
  530. return space.call_method(find_info.w_loader, "load_module", w_modulename)
  531. if find_info.modtype == C_BUILTIN:
  532. return space.getbuiltinmodule(find_info.filename, force_init=True,
  533. reuse=reuse)
  534. if find_info.modtype in (PY_SOURCE, PY_COMPILED, C_EXTENSION, PKG_DIRECTORY):
  535. w_mod = None
  536. if reuse:
  537. try:
  538. w_mod = space.getitem(space.sys.get('modules'), w_modulename)
  539. except OperationError as oe:
  540. if not oe.match(space, space.w_KeyError):
  541. raise
  542. if w_mod is None:
  543. w_mod = space.wrap(Module(space, w_modulename))
  544. if find_info.modtype == PKG_DIRECTORY:
  545. pkgdir = find_info.filename
  546. else:
  547. pkgdir = None
  548. _prepare_module(space, w_mod, find_info.filename, pkgdir)
  549. try:
  550. if find_info.modtype == PY_SOURCE:
  551. load_source_module(
  552. space, w_modulename, w_mod,
  553. find_info.filename, find_info.stream.readall(),
  554. find_info.stream.try_to_find_file_descriptor())
  555. return w_mod
  556. elif find_info.modtype == PY_COMPILED:
  557. magic = _r_long(find_info.stream)
  558. timestamp = _r_long(find_info.stream)
  559. load_compiled_module(space, w_modulename, w_mod, find_info.filename,
  560. magic, timestamp, find_info.stream.readall())
  561. return w_mod
  562. elif find_info.modtype == PKG_DIRECTORY:
  563. w_path = space.newlist([space.wrap(find_info.filename)])
  564. space.setattr(w_mod, space.wrap('__path__'), w_path)
  565. find_info = find_module(space, "__init__", None, "__init__",
  566. w_path, use_loader=False)
  567. if find_info is None:
  568. return w_mod
  569. try:
  570. load_module(space, w_modulename, find_info, reuse=True)
  571. finally:
  572. try:
  573. find_info.stream.close()
  574. except StreamErrors:
  575. pass
  576. # fetch the module again, in case of "substitution"
  577. w_mod = check_sys_modules(space, w_modulename)
  578. return w_mod
  579. elif find_info.modtype == C_EXTENSION and has_so_extension(space):
  580. load_c_extension(space, find_info.filename, space.str_w(w_modulename))
  581. return check_sys_modules(space, w_modulename)
  582. except OperationError:
  583. w_mods = space.sys.get('modules')
  584. space.call_method(w_mods, 'pop', w_modulename, space.w_None)
  585. raise
  586. def load_part(space, w_path, prefix, partname, w_parent, tentative):
  587. w = space.wrap
  588. modulename = '.'.join(prefix + [partname])
  589. w_modulename = w(modulename)
  590. w_mod = check_sys_modules(space, w_modulename)
  591. if w_mod is not None:
  592. if not space.is_w(w_mod, space.w_None):
  593. return w_mod
  594. elif not prefix or w_path is not None:
  595. find_info = find_module(
  596. space, modulename, w_modulename, partname, w_path)
  597. try:
  598. if find_info:
  599. w_mod = load_module(space, w_modulename, find_info)
  600. try:
  601. w_mod = space.getitem(space.sys.get("modules"),
  602. w_modulename)
  603. except OperationError as oe:
  604. if not oe.match(space, space.w_KeyError):
  605. raise
  606. raise OperationError(space.w_ImportError, w_modulename)
  607. if w_parent is not None:
  608. space.setattr(w_parent, space.wrap(partname), w_mod)
  609. return w_mod
  610. finally:
  611. if find_info:
  612. stream = find_info.stream
  613. if stream:
  614. try:
  615. stream.close()
  616. except StreamErrors:
  617. pass
  618. if tentative:
  619. return None
  620. else:
  621. # ImportError
  622. raise oefmt(space.w_ImportError, "No module named %s", modulename)
  623. @jit.dont_look_inside
  624. def reload(space, w_module):
  625. """Reload the module.
  626. The module must have been successfully imported before."""
  627. if not space.is_w(space.type(w_module), space.type(space.sys)):
  628. raise oefmt(space.w_TypeError, "reload() argument must be module")
  629. w_modulename = space.getattr(w_module, space.wrap("__name__"))
  630. modulename = space.str0_w(w_modulename)
  631. if not space.is_w(check_sys_modules(space, w_modulename), w_module):
  632. raise oefmt(space.w_ImportError,
  633. "reload(): module %s not in sys.modules", modulename)
  634. try:
  635. w_mod = space.reloading_modules[modulename]
  636. # Due to a recursive reload, this module is already being reloaded.
  637. return w_mod
  638. except KeyError:
  639. pass
  640. space.reloading_modules[modulename] = w_module
  641. try:
  642. namepath = modulename.split('.')
  643. subname = namepath[-1]
  644. parent_name = '.'.join(namepath[:-1])
  645. if parent_name:
  646. w_parent = check_sys_modules_w(space, parent_name)
  647. if w_parent is None:
  648. raise oefmt(space.w_ImportError,
  649. "reload(): parent %s not in sys.modules",
  650. parent_name)
  651. w_path = space.getattr(w_parent, space.wrap("__path__"))
  652. else:
  653. w_path = None
  654. find_info = find_module(
  655. space, modulename, w_modulename, subname, w_path)
  656. if not find_info:
  657. # ImportError
  658. raise oefmt(space.w_ImportError, "No module named %s", modulename)
  659. try:
  660. try:
  661. return load_module(space, w_modulename, find_info, reuse=True)
  662. finally:
  663. if find_info.stream:
  664. find_info.stream.close()
  665. except:
  666. # load_module probably removed name from modules because of
  667. # the error. Put back the original module object.
  668. space.sys.setmodule(w_module)
  669. raise
  670. finally:
  671. del space.reloading_modules[modulename]
  672. # __________________________________________________________________
  673. #
  674. # import lock, to prevent two threads from running module-level code in
  675. # parallel. This behavior is more or less part of the language specs,
  676. # as an attempt to avoid failure of 'from x import y' if module x is
  677. # still being executed in another thread.
  678. # This logic is tested in pypy.module.thread.test.test_import_lock.
  679. class ImportRLock:
  680. def __init__(self, space):
  681. self.space = space
  682. self.lock = None
  683. self.lockowner = None
  684. self.lockcounter = 0
  685. def lock_held_by_someone_else(self):
  686. me = self.space.getexecutioncontext() # used as thread ident
  687. return self.lockowner is not None and self.lockowner is not me
  688. def lock_held_by_anyone(self):
  689. return self.lockowner is not None
  690. def acquire_lock(self):
  691. # this function runs with the GIL acquired so there is no race
  692. # condition in the creation of the lock
  693. if self.lock is None:
  694. try:
  695. self.lock = self.space.allocate_lock()
  696. except CannotHaveLock:
  697. return
  698. me = self.space.getexecutioncontext() # used as thread ident
  699. if self.lockowner is me:
  700. pass # already acquired by the current thread
  701. else:
  702. self.lock.acquire(True)
  703. assert self.lockowner is None
  704. assert self.lockcounter == 0
  705. self.lockowner = me
  706. self.lockcounter += 1
  707. def release_lock(self, silent_after_fork):
  708. me = self.space.getexecutioncontext() # used as thread ident
  709. if self.lockowner is not me:
  710. if self.lockowner is None and silent_after_fork:
  711. # Too bad. This situation can occur if a fork() occurred
  712. # with the import lock held, and we're the child.
  713. return
  714. if self.lock is None: # CannotHaveLock occurred
  715. return
  716. space = self.space
  717. raise oefmt(space.w_RuntimeError, "not holding the import lock")
  718. assert self.lockcounter > 0
  719. self.lockcounter -= 1
  720. if self.lockcounter == 0:
  721. self.lockowner = None
  722. self.lock.release()
  723. def reinit_lock(self):
  724. # Called after fork() to ensure that newly created child
  725. # processes do not share locks with the parent
  726. self.lock = None
  727. self.lockowner = None
  728. self.lockcounter = 0
  729. def getimportlock(space):
  730. return space.fromcache(ImportRLock)
  731. # __________________________________________________________________
  732. #
  733. # .pyc file support
  734. """
  735. Magic word to reject .pyc files generated by other Python versions.
  736. It should change for each incompatible change to the bytecode.
  737. The value of CR and LF is incorporated so if you ever read or write
  738. a .pyc file in text mode the magic number will be wrong; also, the
  739. Apple MPW compiler swaps their values, botching string constants.
  740. CPython uses values between 20121 - 62xxx
  741. """
  742. # picking a magic number is a mess. So far it works because we
  743. # have only one extra opcode which might or might not be present.
  744. # CPython leaves a gap of 10 when it increases its own magic number.
  745. # To avoid assigning exactly the same numbers as CPython, we can pick
  746. # any number between CPython + 2 and CPython + 9. Right now,
  747. # default_magic = CPython + 7.
  748. #
  749. # CPython + 0 -- used by CPython without the -U option
  750. # CPython + 1 -- used by CPython with the -U option
  751. # CPython + 7 = default_magic -- used by PyPy (incompatible!)
  752. #
  753. from pypy.interpreter.pycode import default_magic
  754. MARSHAL_VERSION_FOR_PYC = 2
  755. def get_pyc_magic(space):
  756. # XXX CPython testing hack: delegate to the real imp.get_magic
  757. if not we_are_translated():
  758. if '__pypy__' not in space.builtin_modules:
  759. import struct
  760. magic = __import__('imp').get_magic()
  761. return struct.unpack('<i', magic)[0]
  762. return default_magic
  763. def parse_source_module(space, pathname, source):
  764. """ Parse a source file and return the corresponding code object """
  765. ec = space.getexecutioncontext()
  766. pycode = ec.compiler.compile(source, pathname, 'exec', 0)
  767. return pycode
  768. def exec_code_module(space, w_mod, code_w):
  769. w_dict = space.getattr(w_mod, space.wrap('__dict__'))
  770. space.call_method(w_dict, 'setdefault',
  771. space.wrap('__builtins__'),
  772. space.wrap(space.builtin))
  773. code_w.exec_code(space, w_dict, w_dict)
  774. @jit.dont_look_inside
  775. def load_source_module(space, w_modulename, w_mod, pathname, source, fd,
  776. write_pyc=True):
  777. """
  778. Load a source module from a given file and return its module
  779. object.
  780. """
  781. w = space.wrap
  782. log_pyverbose(space, 1, "import %s # from %s\n" %
  783. (space.str_w(w_modulename), pathname))
  784. src_stat = os.fstat(fd)
  785. cpathname = pathname + 'c'
  786. mtime = int(src_stat[stat.ST_MTIME])
  787. mode = src_stat[stat.ST_MODE]
  788. stream = check_compiled_module(space, cpathname, mtime)
  789. if stream:
  790. # existing and up-to-date .pyc file
  791. try:
  792. code_w = read_compiled_module(space, cpathname, stream.readall())
  793. finally:
  794. try:
  795. stream.close()
  796. except StreamErrors:
  797. pass
  798. space.setattr(w_mod, w('__file__'), w(cpathname))
  799. else:
  800. code_w = parse_source_module(space, pathname, source)
  801. if write_pyc:
  802. if not space.is_true(space.sys.get('dont_write_bytecode')):
  803. write_compiled_module(space, code_w, cpathname, mode, mtime)
  804. try:
  805. optimize = space.sys.get_flag('optimize')
  806. except RuntimeError:
  807. # during bootstrapping
  808. optimize = 0
  809. if optimize >= 2:
  810. code_w.remove_docstrings(space)
  811. update_code_filenames(space, code_w, pathname)
  812. exec_code_module(space, w_mod, code_w)
  813. return w_mod
  814. def update_code_filenames(space, code_w, pathname, oldname=None):
  815. assert isinstance(code_w, PyCode)
  816. if oldname is None:
  817. oldname = code_w.co_filename
  818. elif code_w.co_filename != oldname:
  819. return
  820. code_w.co_filename = pathname
  821. constants = code_w.co_consts_w
  822. for const in constants:
  823. if const is not None and isinstance(const, PyCode):
  824. update_code_filenames(space, const, pathname, oldname)
  825. def _get_long(s):
  826. a = ord(s[0])
  827. b = ord(s[1])
  828. c = ord(s[2])
  829. d = ord(s[3])
  830. if d >= 0x80:
  831. d -= 0x100
  832. return a | (b<<8) | (c<<16) | (d<<24)
  833. def _read_n(stream, n):
  834. buf = ''
  835. while len(buf) < n:
  836. data = stream.read(n - len(buf))
  837. if not data:
  838. raise streamio.StreamError("end of file")
  839. buf += data
  840. return buf
  841. def _r_long(stream):
  842. s = _read_n(stream, 4)
  843. return _get_long(s)
  844. def _w_long(stream, x):
  845. a = x & 0xff
  846. x >>= 8
  847. b = x & 0xff
  848. x >>= 8
  849. c = x & 0xff
  850. x >>= 8
  851. d = x & 0xff
  852. stream.write(chr(a) + chr(b) + chr(c) + chr(d))
  853. def check_compiled_module(space, pycfilename, expected_mtime):
  854. """
  855. Check if a pyc file's magic number and mtime match.
  856. """
  857. stream = None
  858. try:
  859. stream = streamio.open_file_as_stream(pycfilename, "rb")
  860. magic = _r_long(stream)
  861. if magic != get_pyc_magic(space):
  862. stream.close()
  863. return None
  864. pyc_mtime = _r_long(stream)
  865. if pyc_mtime != expected_mtime:
  866. stream.close()
  867. return None
  868. return stream
  869. except StreamErrors:
  870. if stream:
  871. try:
  872. stream.close()
  873. except StreamErrors:
  874. pass
  875. return None # XXX! must not eat all exceptions, e.g.
  876. # Out of file descriptors.
  877. def read_compiled_module(space, cpathname, strbuf):
  878. """ Read a code object from a file and check it for validity """
  879. w_marshal = space.getbuiltinmodule('marshal')
  880. w_code = space.call_method(w_marshal, 'loads', space.wrap(strbuf))
  881. if not isinstance(w_code, Code):
  882. raise oefmt(space.w_ImportError, "Non-code object in %s", cpathname)
  883. return w_code
  884. @jit.dont_look_inside
  885. def load_compiled_module(space, w_modulename, w_mod, cpathname, magic,
  886. timestamp, source):
  887. """
  888. Load a module from a compiled file, execute it, and return its
  889. module object.
  890. """
  891. log_pyverbose(space, 1, "import %s # compiled from %s\n" %
  892. (space.str_w(w_modulename), cpathname))
  893. if magic != get_pyc_magic(space):
  894. raise oefmt(space.w_ImportError, "Bad magic number in %s", cpathname)
  895. #print "loading pyc file:", cpathname
  896. code_w = read_compiled_module(space, cpathname, source)
  897. try:
  898. optimize = space.sys.get_flag('optimize')
  899. except RuntimeError:
  900. # during bootstrapping
  901. optimize = 0
  902. if optimize >= 2:
  903. code_w.remove_docstrings(space)
  904. exec_code_module(space, w_mod, code_w)
  905. return w_mod
  906. def open_exclusive(space, cpathname, mode):
  907. try:
  908. os.unlink(cpathname)
  909. except OSError:
  910. pass
  911. flags = (os.O_EXCL|os.O_CREAT|os.O_WRONLY|os.O_TRUNC|
  912. streamio.O_BINARY)
  913. fd = os.open(cpathname, flags, mode)
  914. return streamio.fdopen_as_stream(fd, "wb")
  915. def write_compiled_module(space, co, cpathname, src_mode, src_mtime):
  916. """
  917. Write a compiled module to a file, placing the time of last
  918. modification of its source into the header.
  919. Errors are ignored, if a write error occurs an attempt is made to
  920. remove the file.
  921. """
  922. w_marshal = space.getbuiltinmodule('marshal')
  923. try:
  924. w_str = space.call_method(w_marshal, 'dumps', space.wrap(co),
  925. space.wrap(MARSHAL_VERSION_FOR_PYC))
  926. strbuf = space.str_w(w_str)
  927. except OperationError as e:
  928. if e.async(space):
  929. raise
  930. #print "Problem while marshalling %s, skipping" % cpathname
  931. return
  932. #
  933. # Careful here: we must not crash nor leave behind something that looks
  934. # too much like a valid pyc file but really isn't one.
  935. #
  936. mode = src_mode & ~0111
  937. try:
  938. stream = open_exclusive(space, cpathname, mode)
  939. except (OSError, StreamErrors):
  940. try:
  941. os.unlink(cpathname)
  942. except OSError:
  943. pass
  944. return
  945. try:
  946. try:
  947. # will patch the header later; write zeroes until we are sure that
  948. # the rest of the file is valid
  949. _w_long(stream, 0) # pyc_magic
  950. _w_long(stream, 0) # mtime
  951. stream.write(strbuf)
  952. # should be ok (XXX or should call os.fsync() to be sure?)
  953. stream.seek(0, 0)
  954. _w_long(stream, get_pyc_magic(space))
  955. _w_long(stream, src_mtime)
  956. finally:
  957. stream.close()
  958. except StreamErrors:
  959. try:
  960. os.unlink(cpathname)
  961. except OSError:
  962. pass