Debian Codegraph @

pypy/module/sys/initpath.py

raw symbols SCIP
1 """
2 Logic to find sys.executable and the initial sys.path containing the stdlib
3 In CPython much of this is done in Modules/getpath.py which is frozen into
4 the executable as bytecode
5 """
6
7 import errno
8 import os
9 import stat
10 import sys
11
12 from rpython.rlib import rpath, rdynload
13 from rpython.rlib.rstring import assert_str0
14 from rpython.rlib.objectmodel import we_are_translated
15 from rpython.rtyper.lltypesystem import lltype, rffi
16 from rpython.translator.tool.cbuild import ExternalCompilationInfo
17
18 from pypy.interpreter.gateway import unwrap_spec
19 from pypy.module.sys.state import get as get_state
20 from pypy.module.sys.interp_encoding import _getfilesystemencoding
21
22 PLATFORM = sys.platform
23 _MACOSX = sys.platform == 'darwin'
24 _WIN32 = sys.platform == 'win32'
25
26
27 def _exists_and_is_executable(fn):
28 # os.access checks using the user's real uid and gid.
29 # Since pypy should not be run setuid/setgid, this
30 # should be sufficient.
31 return os.path.isfile(fn) and os.access(fn, os.X_OK)
32
33
34 def find_executable(executable):
35 """
36 Return the absolute path of the executable, by looking into PATH and
37 the current directory. If it cannot be found, return ''.
38 """
39 if (we_are_translated() and _WIN32 and
40 not executable.lower().endswith('.exe')):
41 executable += '.exe'
42 if os.sep in executable or (_WIN32 and ':' in executable):
43 # the path is already more than just an executable name
44 pass
45 else:
46 path = os.environ.get('PATH')
47 if path:
48 for dir in path.split(os.pathsep):
49 fn = os.path.join(dir, executable)
50 if _exists_and_is_executable(fn):
51 executable = fn
52 break
53 executable = rpath.rabspath(executable)
54
55 # 'sys.executable' should not end up being an non-existing file;
56 # just use '' in this case. (CPython issue #7774)
57 return executable if _exists_and_is_executable(executable) else ''
58
59
60 def _readlink_maybe(filename):
61 if not _WIN32:
62 return os.readlink(filename)
63 raise NotImplementedError
64
65
66 def resolvedirof(filename):
67 if isinstance(filename, unicode):
68 filename = filename.encode('utf8')
69 filename = rpath.rabspath(filename)
70 dirname = rpath.rabspath(os.path.join(filename, '..'))
71 if os.path.islink(filename):
72 try:
73 link = _readlink_maybe(filename)
74 except OSError:
75 pass
76 else:
77 return resolvedirof(os.path.join(dirname, link))
78 return dirname
79
80
81 def find_pyvenv_cfg(dirname):
82 try:
83 fd = os.open(os.path.join(dirname, 'pyvenv.cfg'), os.O_RDONLY, 0)
84 try:
85 content = os.read(fd, 16384)
86 finally:
87 os.close(fd)
88 except OSError:
89 return ''
90 # painfully parse the file for a line 'home = PATH'
91 for line in content.splitlines():
92 line += '\x00'
93 i = 0
94 while line[i] == ' ':
95 i += 1
96 if (line[i] == 'h' and
97 line[i+1] == 'o' and
98 line[i+2] == 'm' and
99 line[i+3] == 'e'):
100 i += 4
101 while line[i] == ' ':
102 i += 1
103 if line[i] == '=':
104 line = line[i+1:]
105 n = line.find('\x00')
106 assert n >= 0
107 line = line[:n]
108 return assert_str0(line.strip())
109 return ''
110
111
112 def find_stdlib(state, platlibdir, executable):
113 """
114 Find and compute the stdlib path, starting from the directory where
115 ``executable`` is and going one level up until we find it. Return a
116 tuple (path, prefix), where ``prefix`` is the root directory which
117 contains the stdlib. If it cannot be found, return (None, None).
118
119 On PyPy3, it will also look for 'pyvenv.cfg' either in the same or
120 in the parent directory of 'executable', and search from the 'home'
121 entry instead of from the path to 'executable'.
122 """
123 search = 'pypy3-c' if executable == '' else executable
124 search_pyvenv_cfg = 2
125 while True:
126 dirname = resolvedirof(search)
127 if dirname == search:
128 return None, None # not found :-(
129 if search_pyvenv_cfg > 0:
130 search_pyvenv_cfg -= 1
131 home = find_pyvenv_cfg(dirname)
132 if home:
133 dirname = home
134 search_pyvenv_cfg = 0
135 newpath = compute_stdlib_path_maybe(state, platlibdir, dirname)
136 if newpath is not None:
137 return newpath, dirname
138 search = dirname # walk to the parent directory
139
140
141 def _checkdir(path):
142 st = os.stat(path)
143 if not stat.S_ISDIR(st[0]):
144 raise OSError(errno.ENOTDIR, path)
145
146 def _checkfile(path, fname):
147 pth = os.path.join(path, fname)
148 if not os.path.isfile(pth):
149 raise OSError(errno.EEXIST, pth)
150
151 def compute_stdlib_path_packaged(state, platlibdir, prefix):
152 """
153 Compute the paths for the stdlib rooted at ``prefix``. ``prefix``
154 must at least contain a directory called ``lib/pypyX.Y`` (``Lib`` on
155 windows), and there must be a site.py in that directory. If it cannot
156 be found, it raises OSError. This version is called first, and handles
157 packaged PyPy.
158 """
159 from pypy.module.sys.version import CPYTHON_VERSION
160 lib_pyzip = os.path.join(prefix, 'python%d%d.zip' % CPYTHON_VERSION[:2])
161 if os.path.isfile(lib_pyzip):
162 python_std_lib = lib_pyzip
163 else:
164 if _WIN32:
165 lib_python = os.path.join(prefix, 'Lib')
166 else:
167 dirname = 'pypy%d.%d' % CPYTHON_VERSION[:2]
168 lib_python = os.path.join(prefix, platlibdir)
169 lib_python = os.path.join(lib_python, dirname)
170 python_std_lib = os.path.join(prefix, lib_python)
171 # In a source checkout, the directory will exist but site.py will not
172 # yet exist in it
173 _checkfile(python_std_lib, 'site.py')
174 return compute_lib_pypy_path(state, python_std_lib, prefix, use_lib_pypy=False)
175
176 def compute_stdlib_path_sourcetree(state, platlibdir, prefix):
177 """
178 Compute the paths for the stdlib rooted at ``prefix``. ``prefix``
179 must at least contain a directory called ``lib-python/X.Y``. If it
180 cannot be found, it raises OSError. This version is called if
181 compute_stdlib_path_packaged fails.
182 """
183 from pypy.module.sys.version import CPYTHON_VERSION
184 lib_pyzip = os.path.join(prefix, 'python%d%d.zip' % CPYTHON_VERSION[:2])
185 if os.path.isfile(lib_pyzip):
186 python_std_lib = lib_pyzip
187 else:
188 dirname = '%d' % CPYTHON_VERSION[0]
189 lib_python = os.path.join(prefix, 'lib-python')
190 python_std_lib = os.path.join(lib_python, dirname)
191 _checkdir(python_std_lib)
192 return compute_lib_pypy_path(state, python_std_lib, prefix)
193
194 def compute_lib_pypy_path(state, python_std_lib, prefix, use_lib_pypy=True):
195 importlist = []
196
197 if use_lib_pypy:
198 lib_pypy = os.path.join(prefix, 'lib_pypy')
199 _checkdir(lib_pypy)
200 importlist.append(lib_pypy)
201 importlist.append(python_std_lib)
202
203 # List here the extra platform-specific paths.
204 if _MACOSX:
205 # Is this still desirable?
206 platmac = os.path.join(python_std_lib, 'plat-mac')
207 importlist.append(platmac)
208 importlist.append(os.path.join(platmac, 'lib-scriptpackages'))
209 return importlist
210
211
212 def compute_stdlib_path_maybe(state, platlibdir, prefix):
213 """Return the stdlib path rooted at ``prefix``, or None if it cannot
214 be found.
215 """
216 try:
217 return compute_stdlib_path_packaged(state, platlibdir, prefix)
218 except OSError:
219 try:
220 return compute_stdlib_path_sourcetree(state, platlibdir, prefix)
221 except OSError:
222 return None
223
224
225 @unwrap_spec(executable='fsencode')
226 def pypy_find_executable(space, executable):
227 if _WIN32:
228 module_filename = pypy_init_executable()
229 if module_filename:
230 if _WIN32:
231 module_path, lgt = rffi.wcharp2utf8(module_filename)
232 module_path = assert_str0(module_path)
233 else:
234 module_path = rffi.charp2str(module_filename)
235 pypy_init_free(module_filename)
236 module_path = rpath.rabspath(module_path)
237 if _exists_and_is_executable(module_path):
238 return space.newfilename(module_path)
239 return space.newfilename(find_executable(executable))
240
241
242 @unwrap_spec(filename='fsencode')
243 def pypy_resolvedirof(space, filename):
244 return space.newfilename(resolvedirof(filename))
245
246
247 @unwrap_spec(executable='fsencode')
248 def pypy_find_stdlib(space, executable):
249 path, prefix = None, None
250 if executable != '*':
251 path, prefix = find_stdlib(get_state(space), space.config.objspace.platlibdir, executable)
252 if path is None:
253 if space.config.translation.shared:
254 dynamic_location = pypy_init_home()
255 if dynamic_location:
256 if _WIN32:
257 dyn_path, lgt = rffi.wcharp2utf8(dynamic_location)
258 dyn_path = assert_str0(dyn_path)
259 else:
260 dyn_path = rffi.charp2str(dynamic_location)
261 pypy_init_free(dynamic_location)
262 path, prefix = find_stdlib(get_state(space), space.config.objspace.platlibdir, dyn_path)
263 if path is None:
264 return space.w_None
265 w_prefix = space.newfilename(prefix)
266 space.setitem(space.sys.w_dict, space.newtext('prefix'), w_prefix)
267 space.setitem(space.sys.w_dict, space.newtext('exec_prefix'), w_prefix)
268 space.setitem(space.sys.w_dict, space.newtext('base_prefix'), w_prefix)
269 space.setitem(space.sys.w_dict, space.newtext('base_exec_prefix'), w_prefix)
270 for p in path:
271 if os.path.isfile(os.path.join(p, 'os.py')):
272 space.setitem(space.sys.w_dict, space.newtext('_stdlib_dir'),
273 space.newfilename(p))
274 break
275 return space.newlist([space.newfilename(p) for p in path])
276
277 def pypy_initfsencoding(space):
278 space.sys.filesystemencoding = _getfilesystemencoding(space)
279
280
281 # ____________________________________________________________
282
283
284 if os.name == 'nt':
285
286 _source_code = r"""
287 #ifndef _WIN32_WINNT
288 #define _WIN32_WINNT 0x0501
289 #endif
290 #include <windows.h>
291 #include <stdio.h>
292 #include <stdlib.h>
293
294 char *_pypy_init_home(void)
295 {
296 HMODULE hModule = 0;
297 DWORD res;
298 WCHAR *p;
299
300 GetModuleHandleExW(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS |
301 GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT,
302 (LPCWSTR)&_pypy_init_home, &hModule);
303
304 if (hModule == 0 ) {
305 fprintf(stderr, "PyPy initialization: GetModuleHandleExW() failed\n");
306 return NULL;
307 }
308 p = malloc(_MAX_PATH * sizeof(WCHAR));
309 if (p == NULL)
310 return NULL;
311 res = GetModuleFileNameW(hModule, p, _MAX_PATH);
312 if (res >= _MAX_PATH || res <= 0) {
313 free(p);
314 fprintf(stderr, "PyPy initialization: GetModuleFileName() failed\n");
315 return NULL;
316 }
317 return p;
318 }
319
320 wchar_t *_pypy_init_executable(void)
321 {
322 DWORD res;
323 WCHAR *p;
324
325 p = (WCHAR *)malloc(_MAX_PATH * sizeof(WCHAR));
326 if (p == NULL)
327 return NULL;
328 res = GetModuleFileNameW(NULL, p, _MAX_PATH);
329 if (res >= _MAX_PATH || res <= 0) {
330 free(p);
331 fprintf(stderr, "PyPy initialization: GetModuleFileName() failed\n");
332 return NULL;
333 }
334 return p;
335 }
336 inline
337 void _pypy_init_free(WCHAR *p)
338 {
339 free(p);
340 }
341 """
342
343 else:
344
345 _source_code = r"""
346 #include <dlfcn.h>
347 #include <string.h>
348 #include <stdio.h>
349 #include <stdlib.h>
350
351 char *_pypy_init_home(void)
352 {
353 Dl_info info;
354 dlerror(); /* reset */
355 if (dladdr(&_pypy_init_home, &info) == 0) {
356 fprintf(stderr, "PyPy initialization: dladdr() failed: %s\n",
357 dlerror());
358 return NULL;
359 }
360 char *p = realpath(info.dli_fname, NULL);
361 if (p == NULL) {
362 p = strdup(info.dli_fname);
363 }
364 return p;
365 }
366
367 inline
368 void _pypy_init_free(char *p)
369 {
370 free(p);
371 }
372 """
373
374 if we_are_translated():
375 post_include_bits = []
376 else:
377 # for tests
378 if _WIN32:
379 post_include_bits=['RPY_EXPORTED char *_pypy_init_home(void);',
380 'RPY_EXPORTED void _pypy_init_free(char*);',
381 'RPY_EXPORTED wchar_t *_pypy_init_executable(void);',
382 ]
383 else:
384 post_include_bits=['RPY_EXPORTED char *_pypy_init_home(void);',
385 'RPY_EXPORTED void _pypy_init_free(char*);',
386 ]
387
388 _eci = ExternalCompilationInfo(separate_module_sources=[_source_code],
389 post_include_bits=post_include_bits)
390 _eci = _eci.merge(rdynload.eci)
391
392 if _WIN32:
393 pypy_init_executable = rffi.llexternal("_pypy_init_executable", [], rffi.CWCHARP,
394 _nowrapper=True, compilation_info=_eci)
395 pypy_init_free = rffi.llexternal("_pypy_init_free", [rffi.CWCHARP], lltype.Void,
396 _nowrapper=True, compilation_info=_eci)
397 pypy_init_home = rffi.llexternal("_pypy_init_home", [], rffi.CWCHARP,
398 _nowrapper=True, compilation_info=_eci)
399 else:
400 pypy_init_free = rffi.llexternal("_pypy_init_free", [rffi.CCHARP], lltype.Void,
401 _nowrapper=True, compilation_info=_eci)
402 pypy_init_home = rffi.llexternal("_pypy_init_home", [], rffi.CCHARP,
403 _nowrapper=True, compilation_info=_eci)