PageRenderTime 60ms CodeModel.GetById 25ms RepoModel.GetById 0ms app.codeStats 0ms

/pypy/module/imp/importing.py

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