PageRenderTime 70ms CodeModel.GetById 29ms RepoModel.GetById 1ms app.codeStats 0ms

/pypy/module/imp/importing.py

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