Debian Codegraph @

pypy/module/imp/importing.py

raw symbols SCIP
1 """
2 Implementation of the interpreter-level default import logic.
3 """
4
5 import sys, os, stat, re, platform
6
7 from pypy.interpreter.module import Module, init_extra_module_attrs
8 from pypy.interpreter.gateway import interp2app, unwrap_spec
9 from pypy.interpreter.typedef import TypeDef, generic_new_descr
10 from pypy.interpreter.error import OperationError, oefmt, wrap_oserror
11 from pypy.interpreter.baseobjspace import W_Root, CannotHaveLock
12 from pypy.interpreter.eval import Code
13 from pypy.interpreter.pycode import PyCode
14 from rpython.rlib import streamio, jit
15 from rpython.rlib.streamio import StreamErrors
16 from rpython.rlib.objectmodel import we_are_translated, specialize
17 from rpython.rlib.signature import signature
18 from rpython.rlib import rposix_stat, types
19 from pypy.module.sys.version import PYPY_VERSION, CPYTHON_VERSION
20 from pypy.module.__pypy__.interp_os import _multiarch
21
22 _WIN32 = sys.platform == 'win32'
23
24 SO = '.pyd' if _WIN32 else '.so'
25 PYC_TAG = 'pypy%d%d' % CPYTHON_VERSION[:2]
26 DEFAULT_SOABI_BASE = '%s-pp%d%d' % ((PYC_TAG,) + PYPY_VERSION[:2])
27
28 # see also pypy_incremental_magic in interpreter/pycode.py for the magic
29 # version number stored inside pyc files.
30
31
32 @specialize.memo()
33 def get_so_extension(space):
34 if space.config.objspace.soabi is not None:
35 soabi = space.config.objspace.soabi
36 else:
37 soabi = DEFAULT_SOABI_BASE
38
39 if not soabi:
40 return SO
41
42 if not space.config.translating:
43 soabi += 'i'
44
45 platform_name = sys.platform
46 if platform_name.startswith('linux'):
47 platform_name = _multiarch
48 elif platform_name == 'win32' and sys.maxsize > 2**32:
49 platform_name = 'win_amd64'
50 else:
51 # darwin?
52 pass
53
54 soabi += '-' + platform_name
55
56 result = '.' + soabi + SO
57 assert result == result.lower() # this is an implicit requirement of importlib on Windows!
58 return result
59
60 def has_so_extension(space):
61 return (space.config.objspace.usemodules.cpyext or
62 space.config.objspace.usemodules._cffi_backend)
63
64 def check_sys_modules(space, w_modulename):
65 return space.finditem(space.sys.get('modules'), w_modulename)
66
67 def check_sys_modules_w(space, modulename):
68 return space.finditem_str(space.sys.get('modules'), modulename)
69
70
71 lib_pypy = os.path.join(os.path.dirname(__file__),
72 '..', '..', '..', 'lib_pypy')
73
74 def _readall(space, filename):
75 try:
76 fd = os.open(filename, os.O_RDONLY, 0400)
77 try:
78 result = []
79 while True:
80 data = os.read(fd, 8192)
81 if not data:
82 break
83 result.append(data)
84 finally:
85 os.close(fd)
86 except OSError as e:
87 raise wrap_oserror(space, e, filename)
88 return ''.join(result)
89
90 @unwrap_spec(modulename='fsencode', level=int)
91 def importhook(space, modulename, w_globals=None, w_locals=None, w_fromlist=None, level=0):
92 # A minimal version, that can only import builtin and lib_pypy modules!
93 # The actual __import__ is
94 # pypy.module._frozenimportlib.interp_import.interp___import__
95 assert w_locals is w_globals
96 assert level == 0
97
98 w_mod = check_sys_modules_w(space, modulename)
99 if w_mod:
100 return w_mod
101 lock = getimportlock(space)
102 try:
103 lock.acquire_lock()
104
105 if modulename in space.builtin_modules:
106 return space.getbuiltinmodule(modulename)
107
108 ec = space.getexecutioncontext()
109 source = _readall(space, os.path.join(lib_pypy, modulename + '.py'))
110 pathname = "<frozen %s>" % modulename
111 # *must* pass optimize here, otherwise can get strange bootstrapping
112 # problems, because compile would try to get the sys.flags, which might
113 # not be there yet
114 code_w = ec.compiler.compile(source, pathname, 'exec', 0, optimize=0)
115 w_mod = add_module(space, space.newtext(modulename))
116 assert isinstance(w_mod, Module) # XXX why is that necessary?
117 space.setitem(space.sys.get('modules'), w_mod.w_name, w_mod)
118 space.setitem(w_mod.w_dict, space.newtext('__name__'), w_mod.w_name)
119 code_w.exec_code(space, w_mod.w_dict, w_mod.w_dict)
120 assert check_sys_modules_w(space, modulename)
121 finally:
122 lock.release_lock(silent_after_fork=True)
123 return w_mod
124
125
126 class _WIN32Path(object):
127 def __init__(self, path):
128 self.path = path
129
130 def as_unicode(self):
131 return self.path
132
133 def _prepare_module(space, w_mod, filename, pkgdir):
134 space.sys.setmodule(w_mod)
135 space.setattr(w_mod, space.newtext('__file__'), space.newfilename(filename))
136 space.setattr(w_mod, space.newtext('__doc__'), space.w_None)
137 if pkgdir is not None:
138 space.setattr(w_mod, space.newtext('__path__'),
139 space.newlist([space.newtext(pkgdir)]))
140 init_extra_module_attrs(space, w_mod)
141
142 def add_module(space, w_name):
143 w_mod = check_sys_modules(space, w_name)
144 if w_mod is None:
145 w_mod = Module(space, w_name)
146 init_extra_module_attrs(space, w_mod)
147 space.sys.setmodule(w_mod)
148 return w_mod
149
150 # __________________________________________________________________
151 #
152 # import lock, to prevent two threads from running module-level code in
153 # parallel. This behavior is more or less part of the language specs,
154 # as an attempt to avoid failure of 'from x import y' if module x is
155 # still being executed in another thread.
156
157 # This logic is tested in pypy.module.thread.test.test_import_lock.
158
159 class ImportRLock:
160
161 def __init__(self, space):
162 self.space = space
163 self.lock = None
164 self.lockowner = None
165 self.lockcounter = 0
166
167 def lock_held_by_someone_else(self):
168 me = self.space.getexecutioncontext() # used as thread ident
169 return self.lockowner is not None and self.lockowner is not me
170
171 def lock_held_by_anyone(self):
172 return self.lockowner is not None
173
174 def acquire_lock(self):
175 # this function runs with the GIL acquired so there is no race
176 # condition in the creation of the lock
177 if self.lock is None:
178 try:
179 self.lock = self.space.allocate_lock()
180 except CannotHaveLock:
181 return
182 me = self.space.getexecutioncontext() # used as thread ident
183 if self.lockowner is me:
184 pass # already acquired by the current thread
185 else:
186 self.lock.acquire(True)
187 assert self.lockowner is None
188 assert self.lockcounter == 0
189 self.lockowner = me
190 self.lockcounter += 1
191
192 def release_lock(self, silent_after_fork):
193 me = self.space.getexecutioncontext() # used as thread ident
194 if self.lockowner is not me:
195 if self.lockowner is None and silent_after_fork:
196 # Too bad. This situation can occur if a fork() occurred
197 # with the import lock held, and we're the child.
198 return
199 if self.lock is None: # CannotHaveLock occurred
200 return
201 space = self.space
202 raise oefmt(space.w_RuntimeError, "not holding the import lock")
203 assert self.lockcounter > 0
204 self.lockcounter -= 1
205 if self.lockcounter == 0:
206 self.lockowner = None
207 self.lock.release()
208
209 def reinit_lock(self):
210 # Called after fork() to ensure that newly created child
211 # processes do not share locks with the parent
212 # (Note that this runs after interp_imp.acquire_lock()
213 # done in the "before" fork hook, so that's why we decrease
214 # the lockcounter here)
215 if self.lockcounter > 1:
216 # Forked as a side effect of import
217 self.lock = self.space.allocate_lock()
218 me = self.space.getexecutioncontext()
219 self.lock.acquire(True)
220 # XXX: can the previous line fail?
221 self.lockowner = me
222 self.lockcounter -= 1
223 else:
224 self.lock = None
225 self.lockowner = None
226 self.lockcounter = 0
227
228 def getimportlock(space):
229 return space.fromcache(ImportRLock)
230
231 # __________________________________________________________________
232 #
233 # .pyc file support
234
235 """
236 Magic word to reject .pyc files generated by other Python versions.
237 It should change for each incompatible change to the bytecode.
238
239 The value of CR and LF is incorporated so if you ever read or write
240 a .pyc file in text mode the magic number will be wrong; also, the
241 Apple MPW compiler swaps their values, botching string constants.
242
243 CPython 2 uses values between 20121 - 62xxx
244 CPython 3 uses values greater than 3000
245 PyPy uses values under 3000
246
247 """
248
249 # Depending on which opcodes are enabled, eg. CALL_METHOD we bump the version
250 # number by some constant
251 #
252 # CPython + 0 -- used by CPython without the -U option
253 # CPython + 1 -- used by CPython with the -U option
254 # CPython + 7 = default_magic -- used by PyPy (incompatible!)
255 #
256 from pypy.interpreter.pycode import default_magic
257 MARSHAL_VERSION_FOR_PYC = 4
258
259 def get_pyc_magic(space):
260 return default_magic
261
262
263 def parse_source_module(space, pathname, source):
264 """ Parse a source file and return the corresponding code object """
265 ec = space.getexecutioncontext()
266 pycode = ec.compiler.compile(source, pathname, 'exec', 0)
267 return pycode
268
269 def exec_code_module(space, w_mod, code_w, pathname, cpathname,
270 write_paths=True):
271 w_dict = space.getattr(w_mod, space.newtext('__dict__'))
272 space.call_method(w_dict, 'setdefault',
273 space.newtext('__builtins__'),
274 space.builtin)
275 if write_paths:
276 if pathname is not None:
277 w_pathname = get_sourcefile(space, pathname)
278 else:
279 w_pathname = code_w.w_filename
280 if cpathname is not None:
281 w_cpathname = space.newfilename(cpathname)
282 else:
283 w_cpathname = space.w_None
284 space.setitem(w_dict, space.newtext("__file__"), w_pathname)
285 space.setitem(w_dict, space.newtext("__cached__"), w_cpathname)
286 #
287 # like PyImport_ExecCodeModuleObject(), we invoke
288 # _bootstrap_external._fix_up_module() here, which should try to
289 # fix a few more attributes (also __file__ and __cached__, but
290 # let's keep the logic that also sets them explicitly above, just
291 # in case)
292 space.appexec([w_dict, w_pathname, w_cpathname],
293 """(d, pathname, cpathname):
294 from importlib._bootstrap_external import _fix_up_module
295 name = d.get('__name__')
296 if name is not None:
297 _fix_up_module(d, name, pathname, cpathname)
298 """)
299 #
300 code_w.exec_code(space, w_dict, w_dict)
301
302 def rightmost_sep(filename):
303 "Like filename.rfind('/'), but also search for \\."
304 index = filename.rfind(os.sep)
305 if os.altsep is not None:
306 index2 = filename.rfind(os.altsep)
307 index = max(index, index2)
308 return index
309
310 @signature(types.str0(), returns=types.str0())
311 def make_compiled_pathname(pathname):
312 "Given the path to a .py file, return the path to its .pyc file."
313 # foo.py -> __pycache__/foo.<tag>.pyc
314
315 lastpos = rightmost_sep(pathname) + 1
316 assert lastpos >= 0 # zero when slash, takes the full name
317 fname = pathname[lastpos:]
318 if lastpos > 0:
319 # Windows: re-use the last separator character (/ or \\) when
320 # appending the __pycache__ path.
321 lastsep = pathname[lastpos-1]
322 else:
323 lastsep = os.sep
324 ext = fname
325 for i in range(len(fname)):
326 if fname[i] == '.':
327 ext = fname[:i + 1]
328
329 result = (pathname[:lastpos] + "__pycache__" + lastsep +
330 ext + PYC_TAG + '.pyc')
331 return result
332
333 @signature(types.str0(), returns=types.any())
334 def make_source_pathname(pathname):
335 "Given the path to a .pyc file, return the path to its .py file."
336 # (...)/__pycache__/foo.<tag>.pyc -> (...)/foo.py
337
338 right = rightmost_sep(pathname)
339 if right < 0:
340 return None
341 left = rightmost_sep(pathname[:right]) + 1
342 assert left >= 0
343 if pathname[left:right] != '__pycache__':
344 return None
345
346 # Now verify that the path component to the right of the last
347 # slash has two dots in it.
348 rightpart = pathname[right + 1:]
349 dot0 = rightpart.find('.') + 1
350 if dot0 <= 0:
351 return None
352 dot1 = rightpart[dot0:].find('.') + 1
353 if dot1 <= 0:
354 return None
355 # Too many dots?
356 if rightpart[dot0 + dot1:].find('.') >= 0:
357 return None
358
359 result = pathname[:left] + rightpart[:dot0] + 'py'
360 return result
361
362 def get_sourcefile(space, filename):
363 start = len(filename) - 4
364 stop = len(filename) - 1
365 if not 0 <= start <= stop or filename[start:stop].lower() != ".py":
366 return space.newfilename(filename)
367 py = make_source_pathname(filename)
368 if py is None:
369 py = filename[:-1]
370 try:
371 st = os.stat(py)
372 except OSError:
373 pass
374 else:
375 if stat.S_ISREG(st.st_mode):
376 return space.newfilename(py)
377 return space.newfilename(filename)
378
379 def update_code_filenames(space, code_w, pathname, oldname=None):
380 assert isinstance(code_w, PyCode)
381 if oldname is None:
382 oldname = code_w.co_filename
383 elif code_w.co_filename != oldname:
384 return
385
386 code_w.co_filename = pathname
387 code_w.w_filename = space.newfilename(pathname)
388 constants = code_w.co_consts_w
389 for const in constants:
390 if const is not None and isinstance(const, PyCode):
391 update_code_filenames(space, const, pathname, oldname)
392
393 def _get_long(s):
394 a = ord(s[0])
395 b = ord(s[1])
396 c = ord(s[2])
397 d = ord(s[3])
398 if d >= 0x80:
399 d -= 0x100
400 return a | (b<<8) | (c<<16) | (d<<24)
401
402 def read_compiled_module(space, cpathname, strbuf):
403 """ Read a code object from a file and check it for validity """
404
405 w_marshal = space.getbuiltinmodule('marshal')
406 w_code = space.call_method(w_marshal, 'loads', space.newbytes(strbuf))
407 if not isinstance(w_code, Code):
408 raise oefmt(space.w_ImportError, "Non-code object in %s", cpathname)
409 return w_code
410
411 @jit.dont_look_inside
412 def load_compiled_module(space, w_modulename, w_mod, cpathname, magic,
413 source, write_paths=True):
414 """
415 Load a module from a compiled file, execute it, and return its
416 module object.
417 """
418 if magic != get_pyc_magic(space):
419 raise oefmt(space.w_ImportError, "Bad magic number in %s", cpathname)
420 #print "loading pyc file:", cpathname
421 code_w = read_compiled_module(space, cpathname, source)
422 optimize = space.sys.get_optimize()
423 if optimize >= 2:
424 code_w.remove_docstrings(space)
425
426 exec_code_module(space, w_mod, code_w, cpathname, cpathname, write_paths)
427
428 return w_mod
429
430 def get_spec(space, w_module):
431 try:
432 return space.getattr(w_module, space.newtext('__spec__'))
433 except OperationError as e:
434 if not e.match(space, space.w_AttributeError):
435 raise
436 return space.w_None
437
438 def is_spec_initializing(space, w_spec):
439 if space.is_none(w_spec):
440 return False
441
442 try:
443 w_initializing = space.getattr(w_spec, space.newtext("_initializing"))
444 except OperationError as e:
445 if not e.match(space, space.w_AttributeError):
446 raise
447
448 return False
449 else:
450 return space.is_true(w_initializing)
451
452 def is_spec_uninitialized_submodule(space, w_spec, w_name):
453 # Check if the submodule name is in the "_uninitialized_submodules" attribute
454 # of the module spec.
455 if space.is_none(w_spec):
456 return False
457 w_value = space.getattr(w_spec, space.newtext("_uninitialized_submodules"))
458 return space.contains_w(w_value, w_name)
459
460 def get_path(space, w_module):
461 default = space.newtext("unknown location")
462 try:
463 w_ret = space.getattr(w_module, space.newtext('__file__'))
464 except OperationError as e:
465 if not e.match(space, space.w_AttributeError):
466 raise
467 return default
468 if w_ret is space.w_None:
469 return default
470 return w_ret
471