Debian Codegraph @

rpython/rlib/rposix.py

raw symbols SCIP
1 import os
2 import sys
3 import errno
4 from rpython.annotator.model import s_Str0
5 from rpython.rtyper.lltypesystem.rffi import CConstant, CExternVariable, INT
6 from rpython.rtyper.lltypesystem import lltype, ll2ctypes, rffi
7 from rpython.rtyper.tool import rffi_platform
8 from rpython.rlib import debug, jit, rstring, rthread, types
9 from rpython.rlib._os_support import (
10 _CYGWIN, _MACRO_ON_POSIX, UNDERSCORE_ON_WIN32, _WIN32,
11 POSIX_SIZE_T, POSIX_SSIZE_T, utf8_traits, _LINUX)
12 from rpython.rlib.objectmodel import (
13 specialize, enforceargs, register_replacement_for, NOT_CONSTANT)
14 from rpython.rlib.rarithmetic import intmask, widen
15 from rpython.rlib.signature import signature
16 from rpython.tool.sourcetools import func_renamer
17 from rpython.translator.platform import platform
18 from rpython.translator.tool.cbuild import ExternalCompilationInfo
19
20
21 if _WIN32:
22 from rpython.rlib import rwin32
23 from rpython.rlib.rwin32file import make_win32_traits
24
25
26 class CConstantErrno(CConstant):
27 # these accessors are used when calling get_errno() or set_errno()
28 # on top of CPython
29 def __getitem__(self, index):
30 assert index == 0
31 try:
32 return ll2ctypes.TLS.errno
33 except AttributeError:
34 raise ValueError("no C function call occurred so far, "
35 "errno is undefined")
36 def __setitem__(self, index, value):
37 assert index == 0
38 ll2ctypes.TLS.errno = value
39
40 if os.name == 'nt':
41 includes=['errno.h','stdio.h', 'stdlib.h']
42 separate_module_sources =['''
43 /* Lifted completely from CPython 3 Modules/posixmodule.c */
44 static void __cdecl _Py_silent_invalid_parameter_handler(
45 wchar_t const* expression,
46 wchar_t const* function,
47 wchar_t const* file,
48 unsigned int line,
49 uintptr_t pReserved) {
50 }
51
52 RPY_EXTERN void* enter_suppress_iph(void)
53 {
54 void* ret = _set_thread_local_invalid_parameter_handler(_Py_silent_invalid_parameter_handler);
55 /*fprintf(stdout, "setting %p returning %p\\n", (void*)_Py_silent_invalid_parameter_handler, ret);*/
56 return ret;
57 }
58 RPY_EXTERN void exit_suppress_iph(void* old_handler)
59 {
60 void * ret;
61 _invalid_parameter_handler _handler = (_invalid_parameter_handler)old_handler;
62 ret = _set_thread_local_invalid_parameter_handler(_handler);
63 /*fprintf(stdout, "exiting, setting %p returning %p\\n", old_handler, ret);*/
64 }
65 RPY_EXTERN size_t wrap_write(int fd, const void* data, size_t count)
66 {
67 _invalid_parameter_handler old = enter_suppress_iph();
68 if (count > 32767 && _isatty(fd)) {
69 // CPython Issue #11395, PyPy Issue #2636: the Windows console
70 // returns an error (12: not enough space error) on writing into
71 // stdout if stdout mode is binary and the length is greater than
72 // 66,000 bytes (or less, depending on heap usage). Can't easily
73 // test that, because we need 'fd' to be non-redirected...
74 count = 32767;
75 }
76 else if (count > 0x7fffffff)
77 {
78 count = 0x7fffffff;
79 }
80 size_t ret = _write(fd, data, count);
81 exit_suppress_iph(old);
82 return ret;
83 }
84 RPY_EXTERN size_t wrap_read(int fd, const void* buffer, size_t buffer_size)
85 {
86 _invalid_parameter_handler old = enter_suppress_iph();
87 size_t ret = _read(fd, buffer, buffer_size);
88 exit_suppress_iph(old);
89 return ret;
90 }
91 ''',]
92 post_include_bits=['RPY_EXTERN void* enter_suppress_iph();',
93 'RPY_EXTERN void exit_suppress_iph(void* handle);',
94 'RPY_EXTERN size_t wrap_write(int, const void*, size_t);',
95 'RPY_EXTERN size_t wrap_read(int, const void*, size_t);',
96 ]
97 else:
98 separate_module_sources = []
99 post_include_bits = []
100 includes=['errno.h','stdio.h']
101 errno_eci = ExternalCompilationInfo(
102 includes=includes,
103 separate_module_sources=separate_module_sources,
104 post_include_bits=post_include_bits,
105 )
106
107 # Direct getters/setters, don't use directly!
108 _get_errno, _set_errno = CExternVariable(INT, 'errno', errno_eci,
109 CConstantErrno, sandboxsafe=True,
110 _nowrapper=True, c_type='int',
111 declare_as_extern=False)
112
113 def get_saved_errno():
114 """Return the value of the "saved errno".
115 This value is saved after a call to a C function, if it was declared
116 with the flag llexternal(..., save_err=rffi.RFFI_SAVE_ERRNO).
117 Functions without that flag don't change the saved errno.
118 """
119 return intmask(rthread.tlfield_rpy_errno.getraw())
120
121 def set_saved_errno(errno):
122 """Set the value of the saved errno. This value will be used to
123 initialize the real errno just before calling the following C function,
124 provided it was declared llexternal(..., save_err=RFFI_READSAVED_ERRNO).
125 Note also that it is more common to want the real errno to be initially
126 zero; for that case, use llexternal(..., save_err=RFFI_ZERO_ERRNO_BEFORE)
127 and then you don't need set_saved_errno(0).
128 """
129 rthread.tlfield_rpy_errno.setraw(rffi.cast(INT, errno))
130
131 def get_saved_alterrno():
132 """Return the value of the "saved alterrno".
133 This value is saved after a call to a C function, if it was declared
134 with the flag llexternal(..., save_err=rffi.RFFI_SAVE_ERRNO | rffl.RFFI_ALT_ERRNO).
135 Functions without that flag don't change the saved errno.
136 """
137 return intmask(rthread.tlfield_alt_errno.getraw())
138
139 def set_saved_alterrno(errno):
140 """Set the value of the saved alterrno. This value will be used to
141 initialize the real errno just before calling the following C function,
142 provided it was declared llexternal(..., save_err=RFFI_READSAVED_ERRNO | rffl.RFFI_ALT_ERRNO).
143 Note also that it is more common to want the real errno to be initially
144 zero; for that case, use llexternal(..., save_err=RFFI_ZERO_ERRNO_BEFORE)
145 and then you don't need set_saved_errno(0).
146 """
147 rthread.tlfield_alt_errno.setraw(rffi.cast(INT, errno))
148
149
150 # These are not posix specific, but where should they move to?
151 @specialize.call_location()
152 def _errno_before(save_err):
153 if save_err & rffi.RFFI_READSAVED_ERRNO:
154 if save_err & rffi.RFFI_ALT_ERRNO:
155 _set_errno(rthread.tlfield_alt_errno.getraw())
156 else:
157 _set_errno(rthread.tlfield_rpy_errno.getraw())
158 elif save_err & rffi.RFFI_ZERO_ERRNO_BEFORE:
159 _set_errno(rffi.cast(rffi.INT, 0))
160 if _WIN32 and (save_err & rffi.RFFI_READSAVED_LASTERROR):
161 if save_err & rffi.RFFI_ALT_ERRNO:
162 err = rthread.tlfield_alt_lasterror.getraw()
163 else:
164 err = rthread.tlfield_rpy_lasterror.getraw()
165 # careful, getraw() overwrites GetLastError.
166 # We must assign it with _SetLastError() as the last
167 # operation, i.e. after the errno handling.
168 rwin32._SetLastError(err)
169
170 @specialize.call_location()
171 def _errno_after(save_err):
172 if _WIN32:
173 if save_err & rffi.RFFI_SAVE_LASTERROR:
174 err = rwin32._GetLastError()
175 # careful, setraw() overwrites GetLastError.
176 # We must read it first, before the errno handling.
177 if save_err & rffi.RFFI_ALT_ERRNO:
178 rthread.tlfield_alt_lasterror.setraw(err)
179 else:
180 rthread.tlfield_rpy_lasterror.setraw(err)
181 elif save_err & rffi.RFFI_SAVE_WSALASTERROR:
182 from rpython.rlib import _rsocket_rffi
183 err = _rsocket_rffi._WSAGetLastError()
184 if save_err & rffi.RFFI_ALT_ERRNO:
185 rthread.tlfield_alt_lasterror.setraw(err)
186 else:
187 rthread.tlfield_rpy_lasterror.setraw(err)
188 if save_err & rffi.RFFI_SAVE_ERRNO:
189 if save_err & rffi.RFFI_ALT_ERRNO:
190 rthread.tlfield_alt_errno.setraw(_get_errno())
191 else:
192 rthread.tlfield_rpy_errno.setraw(_get_errno())
193 # ^^^ keep fork() up-to-date too, below
194 if _WIN32:
195 includes = ['io.h', 'sys/utime.h', 'sys/types.h', 'process.h', 'time.h',
196 'direct.h', 'Windows.h']
197 libraries = []
198 else:
199 if sys.platform.startswith(('darwin', 'netbsd', 'openbsd')):
200 _ptyh = 'util.h'
201 elif sys.platform.startswith('freebsd'):
202 _ptyh = 'libutil.h'
203 else:
204 _ptyh = 'pty.h'
205 includes = ['unistd.h', 'sys/types.h', 'sys/wait.h',
206 'utime.h', 'sys/time.h', 'sys/times.h',
207 'sys/resource.h',
208 'sched.h',
209 'grp.h', 'dirent.h', 'sys/stat.h', 'fcntl.h',
210 'signal.h', 'sys/utsname.h', _ptyh]
211 if sys.platform.startswith('linux') or sys.platform.startswith('gnu'):
212 includes.append('sys/sysmacros.h')
213 if sys.platform.startswith('freebsd') or sys.platform.startswith('openbsd'):
214 includes.append('sys/ttycom.h')
215 libraries = ['util']
216
217 eci = ExternalCompilationInfo(
218 includes=includes,
219 libraries=libraries,
220 )
221
222 def external(name, args, result, compilation_info=eci, **kwds):
223 return rffi.llexternal(name, args, result,
224 compilation_info=compilation_info, **kwds)
225
226
227 if os.name == 'nt':
228 # is_valid_fd is useful only on MSVC9, and should be deprecated. With it
229 c_enter_suppress_iph = jit.dont_look_inside(external("enter_suppress_iph",
230 [], rffi.VOIDP, compilation_info=errno_eci))
231 c_exit_suppress_iph = jit.dont_look_inside(external("exit_suppress_iph",
232 [rffi.VOIDP], lltype.Void,
233 compilation_info=errno_eci))
234 c_enter_suppress_iph_del = jit.dont_look_inside(external("enter_suppress_iph",
235 [], rffi.VOIDP, compilation_info=errno_eci,
236 releasegil=False))
237 c_exit_suppress_iph_del = jit.dont_look_inside(external("exit_suppress_iph",
238 [rffi.VOIDP], lltype.Void, releasegil=False,
239 compilation_info=errno_eci))
240
241 class SuppressIPH_del(object):
242
243 def __init__(self):
244 pass
245
246 def __enter__(self):
247 self.invalid_param_hndlr = c_enter_suppress_iph_del()
248 return self
249
250 def __exit__(self, *args):
251 c_exit_suppress_iph_del(self.invalid_param_hndlr)
252
253 class SuppressIPH(object):
254
255 def __init__(self):
256 pass
257
258 def __enter__(self):
259 self.invalid_param_hndlr = c_enter_suppress_iph()
260 return self
261
262 def __exit__(self, *args):
263 c_exit_suppress_iph(self.invalid_param_hndlr)
264
265 else:
266 class SuppressIPH(object):
267
268 def __init__(self):
269 pass
270
271 def __enter__(self):
272 return self
273
274 def __exit__(self, *args):
275 pass
276
277 SuppressIPH_del = SuppressIPH
278
279 def closerange(fd_low, fd_high):
280 # this behaves like os.closerange() from Python 2.6.
281 for fd in xrange(fd_low, fd_high):
282 try:
283 with SuppressIPH():
284 os.close(fd)
285 except OSError:
286 pass
287
288 class CConfig:
289 _compilation_info_ = eci
290 SEEK_SET = rffi_platform.DefinedConstantInteger('SEEK_SET')
291 SEEK_CUR = rffi_platform.DefinedConstantInteger('SEEK_CUR')
292 SEEK_END = rffi_platform.DefinedConstantInteger('SEEK_END')
293 PRIO_PROCESS = rffi_platform.DefinedConstantInteger('PRIO_PROCESS')
294 PRIO_PGRP = rffi_platform.DefinedConstantInteger('PRIO_PGRP')
295 PRIO_USER = rffi_platform.DefinedConstantInteger('PRIO_USER')
296 SCHED_FIFO = rffi_platform.DefinedConstantInteger('SCHED_FIFO')
297 SCHED_RR = rffi_platform.DefinedConstantInteger('SCHED_RR')
298 SCHED_OTHER = rffi_platform.DefinedConstantInteger('SCHED_OTHER')
299 SCHED_BATCH = rffi_platform.DefinedConstantInteger('SCHED_BATCH')
300 O_NONBLOCK = rffi_platform.DefinedConstantInteger('O_NONBLOCK')
301 F_LOCK = rffi_platform.DefinedConstantInteger('F_LOCK')
302 F_TLOCK = rffi_platform.DefinedConstantInteger('F_TLOCK')
303 F_ULOCK = rffi_platform.DefinedConstantInteger('F_ULOCK')
304 F_TEST = rffi_platform.DefinedConstantInteger('F_TEST')
305 OFF_T = rffi_platform.SimpleType('off_t')
306 OFF_T_SIZE = rffi_platform.SizeOf('off_t')
307
308 HAVE_UTIMES = rffi_platform.Has('utimes')
309 HAVE_D_TYPE = rffi_platform.Has('DT_UNKNOWN')
310 HAVE_FALLOCATE = rffi_platform.Has('posix_fallocate')
311 HAVE_FADVISE = rffi_platform.Has('posix_fadvise')
312 UTIMBUF = rffi_platform.Struct('struct %sutimbuf' % UNDERSCORE_ON_WIN32,
313 [('actime', rffi.INT),
314 ('modtime', rffi.INT)])
315 CLOCK_T = rffi_platform.SimpleType('clock_t', rffi.INT)
316 _HAVE_STRUCT_TERMIOS_C_ISPEED = rffi_platform.Defined(
317 '_HAVE_STRUCT_TERMIOS_C_ISPEED')
318 _HAVE_STRUCT_TERMIOS_C_OSPEED = rffi_platform.Defined(
319 '_HAVE_STRUCT_TERMIOS_C_OSPEED')
320 if not _WIN32:
321 UID_T = rffi_platform.SimpleType('uid_t', rffi.UINT_real)
322 GID_T = rffi_platform.SimpleType('gid_t', rffi.UINT_real)
323 ID_T = rffi_platform.SimpleType('id_t', rffi.UINT_real)
324 TIOCGWINSZ = rffi_platform.DefinedConstantInteger('TIOCGWINSZ')
325 NCCS = rffi_platform.DefinedConstantInteger('NCCS')
326
327 TMS = rffi_platform.Struct(
328 'struct tms', [('tms_utime', rffi.INT),
329 ('tms_stime', rffi.INT),
330 ('tms_cutime', rffi.INT),
331 ('tms_cstime', rffi.INT)])
332
333 GETPGRP_HAVE_ARG = rffi_platform.Has("getpgrp(0)")
334 SETPGRP_HAVE_ARG = rffi_platform.Has("setpgrp(0, 0)")
335
336 config = rffi_platform.configure(CConfig)
337 globals().update(config)
338
339 # For now we require off_t to be the same size as LONGLONG, which is the
340 # interface required by callers of functions that thake an argument of type
341 # off_t.
342 if not _WIN32:
343 assert OFF_T_SIZE == rffi.sizeof(rffi.LONGLONG)
344
345 c_dup = external(UNDERSCORE_ON_WIN32 + 'dup', [rffi.INT], rffi.INT,
346 save_err=rffi.RFFI_SAVE_ERRNO)
347 c_dup2 = external(UNDERSCORE_ON_WIN32 + 'dup2', [rffi.INT, rffi.INT], rffi.INT,
348 save_err=rffi.RFFI_SAVE_ERRNO)
349 if sys.platform == 'darwin':
350 extra_open_args = {'natural_arity': 2}
351 mode_type = rffi.INT
352 else:
353 extra_open_args = {}
354 mode_type = rffi.MODE_T
355 c_open = external(UNDERSCORE_ON_WIN32 + 'open',
356 [rffi.CCHARP, rffi.INT, mode_type], rffi.INT,
357 save_err=rffi.RFFI_SAVE_ERRNO, **extra_open_args)
358
359 # Win32 Unicode functions
360 c_wopen = external(UNDERSCORE_ON_WIN32 + 'wopen',
361 [rffi.CWCHARP, rffi.INT, rffi.MODE_T], rffi.INT,
362 save_err=rffi.RFFI_SAVE_ERRNO)
363
364 #___________________________________________________________________
365 # Wrappers around posix functions, that accept either strings, or
366 # instances with a "as_bytes()" method.
367 # - pypy.modules.posix.interp_posix passes an object containing a unicode path
368 # which can encode itself with sys.filesystemencoding.
369 # - but rpython.rtyper.module.ll_os.py on Windows will replace these functions
370 # with other wrappers that directly handle unicode strings.
371 @specialize.argtype(0)
372 @signature(types.any(), returns=s_Str0)
373 def _as_bytes(path):
374 assert path is not None
375 if isinstance(path, str):
376 return path
377 elif isinstance(path, unicode):
378 # This never happens in PyPy's Python interpreter!
379 # Only in raw RPython code that uses unicode strings.
380 # We implement python2 behavior: silently convert to ascii.
381 return path.encode('ascii')
382 else:
383 return path.as_bytes()
384
385 @specialize.argtype(0)
386 def _as_bytes0(path):
387 """Crashes translation if the path contains NUL characters."""
388 res = _as_bytes(path)
389 rstring.check_str0(res)
390 return res
391
392 @specialize.argtype(0)
393 def _as_utf8(path):
394 assert path is not None
395 if isinstance(path, str):
396 return path
397 if isinstance(path, unicode):
398 return path.encode("utf8")
399 else:
400 return path.as_utf8()
401
402 @specialize.argtype(0)
403 def _as_utf80(path):
404 """Crashes translation if the path contains NUL characters."""
405 res = _as_utf8(path)
406 rstring.check_str0(res)
407 return res
408
409 @specialize.argtype(0, 1)
410 def putenv(name, value):
411 os.environ[_as_bytes(name)] = _as_bytes(value)
412
413 @specialize.argtype(0)
414 def unsetenv(name):
415 del os.environ[_as_bytes(name)]
416
417 #___________________________________________________________________
418 # Implementation of many posix functions.
419 # They usually check the return value and raise an (RPython) OSError
420 # with errno.
421
422 def replace_os_function(name):
423 func = getattr(os, name, None)
424 if func is None:
425 return lambda f: f
426 return register_replacement_for(
427 func,
428 sandboxed_name='ll_os.ll_os_%s' % name)
429
430 @specialize.arg(0)
431 def handle_posix_error(name, result):
432 result = widen(result)
433 if result < 0:
434 raise OSError(get_saved_errno(), '%s failed' % name)
435 return result
436
437 def _dup(fd, inheritable=True):
438 with SuppressIPH():
439 if inheritable:
440 res = c_dup(fd)
441 else:
442 res = c_dup_noninheritable(fd)
443 return res
444
445 @replace_os_function('dup')
446 def dup(fd, inheritable=True):
447 res = _dup(fd, inheritable)
448 return handle_posix_error('dup', res)
449
450 @replace_os_function('dup2')
451 def dup2(fd, newfd, inheritable=True):
452 with SuppressIPH():
453 if inheritable:
454 res = c_dup2(fd, newfd)
455 else:
456 res = c_dup2_noninheritable(fd, newfd)
457 handle_posix_error('dup2', res)
458
459 #___________________________________________________________________
460
461 @replace_os_function('open')
462 @specialize.argtype(0)
463 @enforceargs(NOT_CONSTANT, int, int, typecheck=False)
464 def open(path, flags, mode):
465 if _WIN32:
466 utf8 = _as_utf80(path)
467 with rffi.scoped_utf82wcharp(utf8) as buf:
468 fd = c_wopen(buf, flags, mode)
469 else:
470 fd = c_open(_as_bytes0(path), flags, mode)
471 return handle_posix_error('open', fd)
472
473 if _WIN32:
474 c_read = external('wrap_read',
475 [rffi.INT, rffi.VOIDP, POSIX_SIZE_T], POSIX_SSIZE_T,
476 save_err=rffi.RFFI_SAVE_ERRNO, compilation_info=errno_eci)
477 c_write = external('wrap_write',
478 [rffi.INT, rffi.VOIDP, POSIX_SIZE_T], POSIX_SSIZE_T,
479 save_err=rffi.RFFI_SAVE_ERRNO, compilation_info=errno_eci)
480 else:
481 c_read = external('read',
482 [rffi.INT, rffi.VOIDP, POSIX_SIZE_T], POSIX_SSIZE_T,
483 save_err=rffi.RFFI_SAVE_ERRNO)
484 c_write = external('write',
485 [rffi.INT, rffi.VOIDP, POSIX_SIZE_T], POSIX_SSIZE_T,
486 save_err=rffi.RFFI_SAVE_ERRNO)
487 c_close = external(UNDERSCORE_ON_WIN32 + 'close', [rffi.INT], rffi.INT,
488 releasegil=False, save_err=rffi.RFFI_SAVE_ERRNO)
489
490 @replace_os_function('read')
491 @signature(types.int(), types.int(), returns=types.any())
492 def read(fd, count):
493 if count < 0:
494 raise OSError(errno.EINVAL, None)
495 with rffi.scoped_alloc_buffer(count) as buf:
496 void_buf = rffi.cast(rffi.VOIDP, buf.raw)
497 got = handle_posix_error('read', c_read(fd, void_buf, count))
498 return buf.str(got)
499
500 @replace_os_function('write')
501 @signature(types.int(), types.any(), returns=types.any())
502 def write(fd, data):
503 count = len(data)
504 with rffi.scoped_nonmovingbuffer(data) as buf:
505 ret = c_write(fd, buf, count)
506 return handle_posix_error('write', ret)
507
508 @replace_os_function('close')
509 @signature(types.int(), returns=types.any())
510 def close(fd):
511 with SuppressIPH():
512 handle_posix_error('close', c_close(fd))
513
514 c_lseek = external('_lseeki64' if _WIN32 else 'lseek',
515 [rffi.INT, rffi.LONGLONG, rffi.INT], rffi.LONGLONG,
516 macro=_MACRO_ON_POSIX, save_err=rffi.RFFI_SAVE_ERRNO)
517
518 @replace_os_function('lseek')
519 def lseek(fd, pos, how):
520 with SuppressIPH():
521 if SEEK_SET is not None:
522 if how == 0:
523 how = SEEK_SET
524 elif how == 1:
525 how = SEEK_CUR
526 elif how == 2:
527 how = SEEK_END
528 return handle_posix_error('lseek', c_lseek(fd, pos, how))
529
530 if not _WIN32:
531 c_pread = external('pread',
532 [rffi.INT, rffi.VOIDP, rffi.SIZE_T , OFF_T], rffi.SSIZE_T,
533 save_err=rffi.RFFI_SAVE_ERRNO)
534 c_pwrite = external('pwrite',
535 [rffi.INT, rffi.VOIDP, rffi.SIZE_T, OFF_T], rffi.SSIZE_T,
536 save_err=rffi.RFFI_SAVE_ERRNO)
537
538 @enforceargs(int, int, None)
539 def pread(fd, count, offset):
540 if count < 0:
541 raise OSError(errno.EINVAL, None)
542 with rffi.scoped_alloc_buffer(count) as buf:
543 void_buf = rffi.cast(rffi.VOIDP, buf.raw)
544 return buf.str(handle_posix_error('pread', c_pread(fd, void_buf, count, offset)))
545
546 @enforceargs(int, None, None)
547 def pwrite(fd, data, offset):
548 count = len(data)
549 with rffi.scoped_nonmovingbuffer(data) as buf:
550 return handle_posix_error('pwrite', c_pwrite(fd, buf, count, offset))
551
552 if HAVE_FALLOCATE:
553 c_posix_fallocate = external('posix_fallocate',
554 [rffi.INT, OFF_T, OFF_T], rffi.INT,
555 save_err=rffi.RFFI_SAVE_ERRNO)
556
557 @enforceargs(int, None, None)
558 def posix_fallocate(fd, offset, length):
559 return handle_posix_error('posix_fallocate', c_posix_fallocate(fd, offset, length))
560
561 if HAVE_FADVISE:
562 class CConfig:
563 _compilation_info_ = eci
564 POSIX_FADV_WILLNEED = rffi_platform.DefinedConstantInteger('POSIX_FADV_WILLNEED')
565 POSIX_FADV_NORMAL = rffi_platform.DefinedConstantInteger('POSIX_FADV_NORMAL')
566 POSIX_FADV_SEQUENTIAL = rffi_platform.DefinedConstantInteger('POSIX_FADV_SEQUENTIAL')
567 POSIX_FADV_RANDOM= rffi_platform.DefinedConstantInteger('POSIX_FADV_RANDOM')
568 POSIX_FADV_NOREUSE = rffi_platform.DefinedConstantInteger('POSIX_FADV_NOREUSE')
569 POSIX_FADV_DONTNEED = rffi_platform.DefinedConstantInteger('POSIX_FADV_DONTNEED')
570
571 advise_config = rffi_platform.configure(CConfig)
572 globals().update(advise_config)
573
574 c_posix_fadvise = external('posix_fadvise',
575 [rffi.INT, OFF_T, OFF_T, rffi.INT], rffi.INT,
576 save_err=rffi.RFFI_SAVE_ERRNO)
577
578 @enforceargs(int, None, None, int)
579 def posix_fadvise(fd, offset, length, advice):
580 error = c_posix_fadvise(fd, offset, length, advice)
581 error = widen(error)
582 if error != 0:
583 raise OSError(error, 'posix_fadvise failed')
584
585 c_lockf = external('lockf',
586 [rffi.INT, rffi.INT , OFF_T], rffi.INT,
587 save_err=rffi.RFFI_SAVE_ERRNO)
588 @enforceargs(int, None, None)
589 def lockf(fd, cmd, length):
590 return handle_posix_error('lockf', c_lockf(fd, cmd, length))
591
592 c_fsync = external('fsync' if not _WIN32 else '_commit', [rffi.INT], rffi.INT,
593 save_err=rffi.RFFI_SAVE_ERRNO)
594 c_fdatasync = external('fdatasync', [rffi.INT], rffi.INT,
595 save_err=rffi.RFFI_SAVE_ERRNO)
596 if _WIN32:
597 c_ftruncate = external('_chsize_s', [rffi.INT, rffi.LONGLONG], rffi.INT,
598 save_err=rffi.RFFI_SAVE_ERRNO)
599 else:
600 c_sync = external('sync', [], lltype.Void)
601 c_ftruncate = external('ftruncate', [rffi.INT, rffi.LONGLONG], rffi.INT,
602 macro=_MACRO_ON_POSIX, save_err=rffi.RFFI_SAVE_ERRNO)
603
604 @replace_os_function('ftruncate')
605 def ftruncate(fd, length):
606 with SuppressIPH():
607 handle_posix_error('ftruncate', c_ftruncate(fd, length))
608
609 @replace_os_function('fsync')
610 def fsync(fd):
611 with SuppressIPH():
612 handle_posix_error('fsync', c_fsync(fd))
613
614 @replace_os_function('fdatasync')
615 def fdatasync(fd):
616 handle_posix_error('fdatasync', c_fdatasync(fd))
617
618 def sync():
619 c_sync()
620
621 #___________________________________________________________________
622
623 c_chdir = external('chdir', [rffi.CCHARP], rffi.INT,
624 save_err=rffi.RFFI_SAVE_ERRNO)
625 c_fchdir = external('fchdir', [rffi.INT], rffi.INT,
626 save_err=rffi.RFFI_SAVE_ERRNO)
627 c_access = external(UNDERSCORE_ON_WIN32 + 'access',
628 [rffi.CCHARP, rffi.INT], rffi.INT)
629 c_waccess = external(UNDERSCORE_ON_WIN32 + 'waccess',
630 [rffi.CWCHARP, rffi.INT], rffi.INT)
631
632 @replace_os_function('chdir')
633 @specialize.argtype(0)
634 def chdir(path):
635 if not _WIN32:
636 handle_posix_error('chdir', c_chdir(_as_bytes0(path)))
637 else:
638 traits = utf8_traits
639 win32traits = make_win32_traits(traits)
640 utf8 = traits.as_utf80(path)
641
642 # This is a reimplementation of the C library's chdir
643 # function, but one that produces Win32 errors instead of DOS
644 # error codes.
645 # chdir is essentially a wrapper around SetCurrentDirectory;
646 # however, it also needs to set "magic" environment variables
647 # indicating the per-drive current directory, which are of the
648 # form =<drive>:
649 with rffi.scoped_utf82wcharp(utf8) as buf:
650 if not win32traits.SetCurrentDirectory(buf):
651 raise rwin32.lastSavedWindowsError()
652 MAX_PATH = rwin32.MAX_PATH
653 assert MAX_PATH > 0
654
655 with traits.scoped_alloc_buffer(MAX_PATH) as path:
656 res = win32traits.GetCurrentDirectory(MAX_PATH + 1, path.raw)
657 if not res:
658 raise rwin32.lastSavedWindowsError()
659 res = rffi.cast(lltype.Signed, res)
660 assert res > 0
661 if res <= MAX_PATH + 1:
662 new_path = path.str(res).encode('utf8')
663 else:
664 with traits.scoped_alloc_buffer(res) as path:
665 res = win32traits.GetCurrentDirectory(res, path.raw)
666 if not res:
667 raise rwin32.lastSavedWindowsError()
668 res = rffi.cast(lltype.Signed, res)
669 assert res > 0
670 new_path = path.str(res).encode('utf8')
671 utf8 = new_path
672 if utf8[0] == '\\' or utf8[0] == '/': # UNC path
673 return
674 magic_envvar = '=' + new_path[0] + ':'
675 with rffi.scoped_utf82wcharp(utf8) as buf2:
676 with rffi.scoped_utf82wcharp(magic_envvar) as buf1:
677 if not win32traits.SetEnvironmentVariable(buf1, buf2):
678 raise rwin32.lastSavedWindowsError()
679
680 @replace_os_function('fchdir')
681 def fchdir(fd):
682 handle_posix_error('fchdir', c_fchdir(fd))
683
684 @replace_os_function('access')
685 @specialize.argtype(0)
686 def access(path, mode):
687 if _WIN32:
688 # All files are executable on Windows
689 mode = mode & ~os.X_OK
690 utf8 = _as_utf80(path)
691 with rffi.scoped_utf82wcharp(utf8) as buf:
692 error = c_waccess(buf, mode)
693 else:
694 error = c_access(_as_bytes0(path), mode)
695 return error == 0
696
697 # This Win32 function is not exposed via os, but needed to get a
698 # correct implementation of os.path.abspath.
699 @specialize.argtype(0)
700 def getfullpathname(path):
701 length = rwin32.MAX_PATH + 1
702 win32traits = make_win32_traits(utf8_traits)
703 utf8 = _as_utf80(path)
704 while True: # should run the loop body maximum twice
705 with rffi.scoped_alloc_unicodebuffer(length) as out_buf:
706 with rffi.scoped_utf82wcharp(utf8) as in_buf:
707
708 res = win32traits.GetFullPathName(
709 in_buf, rffi.cast(rwin32.DWORD, length),
710 out_buf.raw, lltype.nullptr(win32traits.LPSTRP.TO))
711 res = intmask(res)
712 if res == 0:
713 raise rwin32.lastSavedWindowsError("_getfullpathname failed")
714 if res >= length:
715 length = res + 1
716 continue
717 result = out_buf.str(res)
718
719 assert result is not None
720 result = rstring.assert_str0(result)
721 return result.encode('utf8')
722
723 c_getcwd = external(UNDERSCORE_ON_WIN32 + 'getcwd',
724 [rffi.CCHARP, rffi.SIZE_T], rffi.CCHARP,
725 save_err=rffi.RFFI_SAVE_ERRNO)
726 c_wgetcwd = external(UNDERSCORE_ON_WIN32 + 'wgetcwd',
727 [rffi.CWCHARP, rffi.SIZE_T], rffi.CWCHARP,
728 save_err=rffi.RFFI_SAVE_ERRNO)
729
730 @replace_os_function('getcwd')
731 def getcwd():
732 bufsize = 256
733 while True:
734 buf = lltype.malloc(rffi.CCHARP.TO, bufsize, flavor='raw')
735 res = c_getcwd(buf, bufsize)
736 if res:
737 break # ok
738 error = get_saved_errno()
739 lltype.free(buf, flavor='raw')
740 if error != errno.ERANGE:
741 raise OSError(error, "getcwd failed")
742 # else try again with a larger buffer, up to some sane limit
743 bufsize *= 4
744 if bufsize > 1024*1024: # xxx hard-coded upper limit
745 # must be <2**31 for win32
746 raise OSError(error, "getcwd result too large")
747 result = rffi.charp2str(res)
748 lltype.free(buf, flavor='raw')
749 return result
750
751 @replace_os_function('getcwdu')
752 def getcwdu():
753 bufsize = 256
754 while True:
755 buf = lltype.malloc(rffi.CWCHARP.TO, bufsize, flavor='raw')
756 res = c_wgetcwd(buf, bufsize)
757 if res:
758 break # ok
759 error = get_saved_errno()
760 lltype.free(buf, flavor='raw')
761 if error != errno.ERANGE:
762 raise OSError(error, "getcwd failed")
763 # else try again with a larger buffer, up to some sane limit
764 bufsize *= 4
765 if bufsize > 1024*1024: # xxx hard-coded upper limit
766 # must be <2**31 for win32
767 raise OSError(error, "getcwd result too large")
768 result = rffi.wcharp2unicode(res)
769 lltype.free(buf, flavor='raw')
770 return result
771
772 if not _WIN32:
773 class CConfig:
774 _compilation_info_ = eci
775 DIRENT = rffi_platform.Struct('struct dirent',
776 [('d_name', lltype.FixedSizeArray(rffi.CHAR, 1)),
777 ('d_ino', lltype.Signed)]
778 + ([('d_type', rffi.INT)] if HAVE_D_TYPE else []))
779 if HAVE_D_TYPE:
780 DT_UNKNOWN = rffi_platform.ConstantInteger('DT_UNKNOWN')
781 DT_REG = rffi_platform.ConstantInteger('DT_REG')
782 DT_DIR = rffi_platform.ConstantInteger('DT_DIR')
783 DT_LNK = rffi_platform.ConstantInteger('DT_LNK')
784
785 DIRP = rffi.COpaquePtr('DIR')
786 dirent_config = rffi_platform.configure(CConfig)
787 DIRENT = dirent_config['DIRENT']
788 DIRENTP = lltype.Ptr(DIRENT)
789 c_opendir = external('opendir',
790 [rffi.CCHARP], DIRP, save_err=rffi.RFFI_SAVE_ERRNO)
791 c_fdopendir = external('fdopendir',
792 [rffi.INT], DIRP, save_err=rffi.RFFI_SAVE_ERRNO)
793 c_rewinddir = external('rewinddir',
794 [DIRP], lltype.Void, releasegil=False)
795 # XXX macro=True is hack to make sure we get the correct kind of
796 # dirent struct (which depends on defines)
797 c_readdir = external('readdir', [DIRP], DIRENTP,
798 macro=True, save_err=rffi.RFFI_FULL_ERRNO_ZERO)
799 c_closedir = external('closedir', [DIRP], rffi.INT, releasegil=False)
800 c_dirfd = external('dirfd', [DIRP], rffi.INT, releasegil=False,
801 macro=True)
802 if sys.platform == 'darwin':
803 c_ioctl_voidp = external('ioctl', [rffi.INT, rffi.UINT, rffi.VOIDP], rffi.INT,
804 save_err=rffi.RFFI_SAVE_ERRNO, natural_arity=2)
805 else:
806 c_ioctl_voidp = external('ioctl', [rffi.INT, rffi.UINT, rffi.VOIDP], rffi.INT,
807 save_err=rffi.RFFI_SAVE_ERRNO)
808 else:
809 dirent_config = {}
810
811 def _listdir(dirp, rewind=False):
812 result = []
813 while True:
814 direntp = c_readdir(dirp)
815 if not direntp:
816 error = get_saved_errno()
817 break
818 namep = rffi.cast(rffi.CCHARP, direntp.c_d_name)
819 name = rffi.charp2str(namep)
820 if name != '.' and name != '..':
821 result.append(name)
822 if rewind:
823 c_rewinddir(dirp)
824 c_closedir(dirp)
825 if error:
826 raise OSError(error, "readdir failed")
827 return result
828
829 if not _WIN32:
830 def fdlistdir(dirfd):
831 """
832 Like listdir(), except that the directory is specified as an open
833 file descriptor.
834
835 Note: fdlistdir() closes the file descriptor. To emulate the
836 Python 3.x 'os.opendir(dirfd)', you must first duplicate the
837 file descriptor.
838 """
839 dirp = c_fdopendir(dirfd)
840 if not dirp:
841 error = get_saved_errno()
842 c_close(dirfd)
843 raise OSError(error, "opendir failed")
844 return _listdir(dirp, rewind=True)
845
846 @replace_os_function('listdir')
847 @specialize.argtype(0)
848 def listdir(path):
849 if not _WIN32:
850 path = _as_bytes0(path)
851 dirp = c_opendir(path)
852 if not dirp:
853 raise OSError(get_saved_errno(), "opendir failed")
854 return _listdir(dirp)
855 else: # _WIN32 case
856 traits = utf8_traits
857 win32traits = make_win32_traits(traits)
858 if not path:
859 raise OSError(win32traits.ERROR_FILE_NOT_FOUND,
860 "listdir called with invalid path")
861 utf8 = traits.as_utf80(path)
862 if utf8 and utf8[-1] not in ('/', '\\', ':'):
863 utf8 += '\\'
864 mask = utf8 + '*.*'
865
866 filedata = lltype.malloc(win32traits.WIN32_FIND_DATA, flavor='raw')
867 try:
868 result = []
869 with rffi.scoped_utf82wcharp(mask) as buf:
870 hFindFile = win32traits.FindFirstFile(buf, filedata)
871 if hFindFile == rwin32.INVALID_HANDLE_VALUE:
872 error = rwin32.GetLastError_saved()
873 if error == win32traits.ERROR_FILE_NOT_FOUND:
874 return result
875 else:
876 raise WindowsError(error, "FindFirstFile failed")
877 while True:
878 name = traits.charp2str(rffi.cast(traits.CCHARP,
879 filedata.c_cFileName))
880 if not (name == "." or name == ".."):
881 result.append(name)
882 if not win32traits.FindNextFile(hFindFile, filedata):
883 break
884 # FindNextFile sets error to ERROR_NO_MORE_FILES if
885 # it got to the end of the directory
886 error = rwin32.GetLastError_saved()
887 win32traits.FindClose(hFindFile)
888 if error == win32traits.ERROR_NO_MORE_FILES:
889 return result
890 else:
891 raise WindowsError(error, "FindNextFile failed")
892 finally:
893 lltype.free(filedata, flavor='raw')
894
895 #___________________________________________________________________
896
897 c_execv = external('execv', [rffi.CCHARP, rffi.CCHARPP], rffi.INT,
898 save_err=rffi.RFFI_SAVE_ERRNO)
899 c_execve = external('execve',
900 [rffi.CCHARP, rffi.CCHARPP, rffi.CCHARPP], rffi.INT,
901 save_err=rffi.RFFI_SAVE_ERRNO)
902 c_spawnv = external(UNDERSCORE_ON_WIN32 + 'spawnv',
903 [rffi.INT, rffi.CCHARP, rffi.CCHARPP], rffi.INT,
904 save_err=rffi.RFFI_SAVE_ERRNO)
905 c_spawnve = external(UNDERSCORE_ON_WIN32 + 'spawnve',
906 [rffi.INT, rffi.CCHARP, rffi.CCHARPP, rffi.CCHARPP],
907 rffi.INT,
908 save_err=rffi.RFFI_SAVE_ERRNO)
909
910 @replace_os_function('execv')
911 def execv(path, args):
912 rstring.check_str0(path)
913 # This list conversion already takes care of NUL bytes.
914 l_args = rffi.ll_liststr2charpp(args)
915 c_execv(path, l_args)
916 rffi.free_charpp(l_args)
917 raise OSError(get_saved_errno(), "execv failed")
918
919 @replace_os_function('execve')
920 def execve(path, args, env):
921 envstrs = []
922 for item in env.iteritems():
923 envstr = "%s=%s" % item
924 envstrs.append(envstr)
925
926 rstring.check_str0(path)
927 # This list conversion already takes care of NUL bytes.
928 l_args = rffi.ll_liststr2charpp(args)
929 l_env = rffi.ll_liststr2charpp(envstrs)
930 c_execve(path, l_args, l_env)
931
932 rffi.free_charpp(l_env)
933 rffi.free_charpp(l_args)
934 raise OSError(get_saved_errno(), "execve failed")
935
936 @replace_os_function('spawnv')
937 def spawnv(mode, path, args):
938 rstring.check_str0(path)
939 l_args = rffi.ll_liststr2charpp(args)
940 childpid = c_spawnv(mode, path, l_args)
941 rffi.free_charpp(l_args)
942 return handle_posix_error('spawnv', childpid)
943
944 @replace_os_function('spawnve')
945 def spawnve(mode, path, args, env):
946 envstrs = []
947 for item in env.iteritems():
948 envstrs.append("%s=%s" % item)
949 rstring.check_str0(path)
950 l_args = rffi.ll_liststr2charpp(args)
951 l_env = rffi.ll_liststr2charpp(envstrs)
952 childpid = c_spawnve(mode, path, l_args, l_env)
953 rffi.free_charpp(l_env)
954 rffi.free_charpp(l_args)
955 return handle_posix_error('spawnve', childpid)
956
957 if not _WIN32:
958 TCFLAG_T = rffi.UINT
959 CC_T = rffi.UCHAR
960 SPEED_T = rffi.UINT
961 _add = []
962 if config['_HAVE_STRUCT_TERMIOS_C_ISPEED']:
963 _add.append(('c_ispeed', SPEED_T))
964 if config['_HAVE_STRUCT_TERMIOS_C_OSPEED']:
965 _add.append(('c_ospeed', SPEED_T))
966
967 TERMIOS = rffi.CStruct('termios', ('c_iflag', TCFLAG_T), ('c_oflag', TCFLAG_T),
968 ('c_cflag', TCFLAG_T), ('c_lflag', TCFLAG_T),
969 ('c_line', CC_T),
970 ('c_cc', lltype.FixedSizeArray(CC_T, NCCS)), *_add)
971 WINSIZE = rffi.CStruct('winsize', ('ws_row', rffi.USHORT),
972 ('ws_col', rffi.USHORT),
973 ('ws_xpixel', rffi.USHORT),
974 ('ws_ypixel', rffi.USHORT))
975
976
977 TERMIOS_P = lltype.Ptr(TERMIOS)
978 WINSIZE_P = lltype.Ptr(WINSIZE)
979 c_fork = external('fork', [], rffi.PID_T, _nowrapper = True)
980 c_openpty = external('openpty',
981 [rffi.INT_realP, rffi.INT_realP, rffi.VOIDP, TERMIOS_P, WINSIZE_P],
982 rffi.INT,
983 save_err=rffi.RFFI_SAVE_ERRNO)
984 c_forkpty = external('forkpty',
985 [rffi.INT_realP, rffi.VOIDP, TERMIOS_P, WINSIZE_P],
986 rffi.PID_T, _nowrapper = True)
987
988 @replace_os_function('fork')
989 @jit.dont_look_inside
990 def fork():
991 # NB. keep forkpty() up-to-date, too
992 # lots of custom logic here, to do things in the right order
993 ofs = debug.debug_offset()
994 opaqueaddr = rthread.gc_thread_before_fork()
995 childpid = c_fork()
996 errno = _get_errno()
997 rthread.gc_thread_after_fork(childpid, opaqueaddr)
998 rthread.tlfield_rpy_errno.setraw(errno)
999 childpid = handle_posix_error('fork', childpid)
1000 if childpid == 0:
1001 debug.debug_forked(ofs)
1002 return childpid
1003
1004 @replace_os_function('openpty')
1005 @jit.dont_look_inside
1006 def openpty():
1007 master_p = lltype.malloc(rffi.INT_realP.TO, 1, flavor='raw')
1008 slave_p = lltype.malloc(rffi.INT_realP.TO, 1, flavor='raw')
1009 try:
1010 handle_posix_error(
1011 'openpty', c_openpty(master_p, slave_p, None,
1012 rffi.cast(TERMIOS_P, 0),
1013 rffi.cast(WINSIZE_P, 0)))
1014 return (widen(master_p[0]), widen(slave_p[0]))
1015 finally:
1016 lltype.free(master_p, flavor='raw')
1017 lltype.free(slave_p, flavor='raw')
1018
1019 @replace_os_function('forkpty')
1020 @jit.dont_look_inside
1021 def forkpty():
1022 master_p = lltype.malloc(rffi.INT_realP.TO, 1, flavor='raw')
1023 master_p[0] = rffi.cast(rffi.INT_real, -1)
1024 null = lltype.nullptr(rffi.VOIDP.TO)
1025 try:
1026 ofs = debug.debug_offset()
1027 opaqueaddr = rthread.gc_thread_before_fork()
1028 childpid = c_forkpty(master_p, null,
1029 rffi.cast(TERMIOS_P, 0),
1030 rffi.cast(WINSIZE_P, 0))
1031 errno = _get_errno()
1032 rthread.gc_thread_after_fork(childpid, opaqueaddr)
1033 rthread.tlfield_rpy_errno.setraw(errno)
1034 childpid = handle_posix_error('forkpty', childpid)
1035 if childpid == 0:
1036 debug.debug_forked(ofs)
1037 return (childpid, master_p[0])
1038 finally:
1039 lltype.free(master_p, flavor='raw')
1040
1041 if _WIN32:
1042 # emulate waitpid() with the _cwait() of Microsoft's compiler
1043 c__cwait = external('_cwait',
1044 [rffi.INTP, rffi.PID_T, rffi.INT], rffi.PID_T,
1045 save_err=rffi.RFFI_SAVE_ERRNO)
1046 @jit.dont_look_inside
1047 def c_waitpid(pid, status_p, options):
1048 result = c__cwait(status_p, pid, options)
1049 # shift the status left a byte so this is more
1050 # like the POSIX waitpid
1051 status_p[0] = rffi.cast(rffi.INT, widen(status_p[0]) << 8)
1052 return result
1053 elif _CYGWIN:
1054 c_waitpid = external('cygwin_waitpid',
1055 [rffi.PID_T, rffi.INTP, rffi.INT], rffi.PID_T,
1056 save_err=rffi.RFFI_SAVE_ERRNO)
1057 else:
1058 c_waitpid = external('waitpid',
1059 [rffi.PID_T, rffi.INT_realP, rffi.INT_real], rffi.PID_T,
1060 save_err=rffi.RFFI_SAVE_ERRNO)
1061
1062 @replace_os_function('waitpid')
1063 def waitpid(pid, options):
1064 if _WIN32 or _CYGWIN:
1065 status_p = lltype.malloc(rffi.INTP.TO, 1, flavor='raw')
1066 status_p[0] = rffi.cast(rffi.INT, 0)
1067 else:
1068 status_p = lltype.malloc(rffi.INT_realP.TO, 1, flavor='raw')
1069 status_p[0] = rffi.cast(rffi.INT_real, 0)
1070 try:
1071 result = handle_posix_error('waitpid',
1072 c_waitpid(pid, status_p, options))
1073 status = widen(status_p[0])
1074 return (result, status)
1075 finally:
1076 lltype.free(status_p, flavor='raw')
1077
1078 def _make_waitmacro(name):
1079 # note that rffi.INT as first parameter type is intentional.
1080 # on s390x providing a lltype.Signed as param type, the
1081 # macro wrapper function will always return 0
1082 # reason: legacy code required a union wait. see
1083 # https://sourceware.org/bugzilla/show_bug.cgi?id=19613
1084 # for more details. If this get's fixed we can use lltype.Signed
1085 # again. (The exact same issue occurs on ppc64 big-endian.)
1086 c_func = external(name, [rffi.INT], lltype.Signed,
1087 macro=_MACRO_ON_POSIX)
1088 returning_int = name in ('WEXITSTATUS', 'WSTOPSIG', 'WTERMSIG')
1089
1090 @replace_os_function(name)
1091 @func_renamer(name)
1092 def _waitmacro(status):
1093 if returning_int:
1094 return c_func(status)
1095 else:
1096 return bool(c_func(status))
1097
1098 WAIT_MACROS = ['WCOREDUMP', 'WIFSTOPPED',
1099 'WIFSIGNALED', 'WIFEXITED',
1100 'WEXITSTATUS', 'WSTOPSIG', 'WTERMSIG']
1101 if not sys.platform.startswith('gnu'):
1102 WAIT_MACROS.append('WIFCONTINUED')
1103
1104 for name in WAIT_MACROS:
1105 _make_waitmacro(name)
1106
1107 #___________________________________________________________________
1108
1109 c_getlogin = external('getlogin', [], rffi.CCHARP,
1110 releasegil=False, save_err=rffi.RFFI_SAVE_ERRNO)
1111 c_getloadavg = external('getloadavg',
1112 [rffi.CArrayPtr(lltype.Float), rffi.INT], rffi.INT)
1113
1114 @replace_os_function('getlogin')
1115 def getlogin():
1116 result = c_getlogin()
1117 if not result:
1118 raise OSError(get_saved_errno(), "getlogin failed")
1119 return rffi.charp2str(result)
1120
1121 @replace_os_function('getloadavg')
1122 def getloadavg():
1123 load = lltype.malloc(rffi.CArrayPtr(lltype.Float).TO, 3, flavor='raw')
1124 try:
1125 r = c_getloadavg(load, 3)
1126 if r != 3:
1127 raise OSError
1128 return (load[0], load[1], load[2])
1129 finally:
1130 lltype.free(load, flavor='raw')
1131
1132 #___________________________________________________________________
1133
1134 c_readlink = external('readlink',
1135 [rffi.CCHARP, rffi.CCHARP, rffi.SIZE_T], rffi.SSIZE_T,
1136 save_err=rffi.RFFI_SAVE_ERRNO)
1137
1138 @replace_os_function('readlink')
1139 def readlink(path):
1140 path = _as_bytes0(path)
1141 bufsize = 1023
1142 while True:
1143 buf = lltype.malloc(rffi.CCHARP.TO, bufsize, flavor='raw')
1144 res = widen(c_readlink(path, buf, bufsize))
1145 if res < 0:
1146 lltype.free(buf, flavor='raw')
1147 error = get_saved_errno() # failed
1148 raise OSError(error, "readlink failed")
1149 elif res < bufsize:
1150 break # ok
1151 else:
1152 # buf too small, try again with a larger buffer
1153 lltype.free(buf, flavor='raw')
1154 bufsize *= 4
1155 # convert the result to a string
1156 result = rffi.charp2strn(buf, res)
1157 lltype.free(buf, flavor='raw')
1158 return result
1159
1160 c_isatty = external(UNDERSCORE_ON_WIN32 + 'isatty', [rffi.INT], rffi.INT)
1161
1162 @replace_os_function('isatty')
1163 def isatty(fd):
1164 with SuppressIPH():
1165 return c_isatty(fd) != 0
1166 return False
1167
1168 c_ttyname = external('ttyname', [lltype.Signed], rffi.CCHARP,
1169 releasegil=False,
1170 save_err=rffi.RFFI_SAVE_ERRNO)
1171
1172 @replace_os_function('ttyname')
1173 def ttyname(fd):
1174 l_name = c_ttyname(fd)
1175 if not l_name:
1176 raise OSError(get_saved_errno(), "ttyname raised")
1177 return rffi.charp2str(l_name)
1178
1179 c_strerror = external('strerror', [rffi.INT], rffi.CCHARP,
1180 releasegil=False)
1181
1182 @replace_os_function('strerror')
1183 def strerror(errnum):
1184 res = c_strerror(errnum)
1185 if not res:
1186 raise ValueError("os_strerror failed")
1187 return rffi.charp2str(res)
1188
1189 c_system = external('system', [rffi.CCHARP], rffi.INT)
1190
1191 @replace_os_function('system')
1192 def system(command):
1193 return widen(c_system(command))
1194
1195 c_unlink = external('unlink', [rffi.CCHARP], rffi.INT,
1196 save_err=rffi.RFFI_SAVE_ERRNO)
1197 c_mkdir = external('mkdir', [rffi.CCHARP, rffi.MODE_T], rffi.INT,
1198 save_err=rffi.RFFI_SAVE_ERRNO)
1199 c_rmdir = external(UNDERSCORE_ON_WIN32 + 'rmdir', [rffi.CCHARP], rffi.INT,
1200 save_err=rffi.RFFI_SAVE_ERRNO)
1201 c_wrmdir = external(UNDERSCORE_ON_WIN32 + 'wrmdir', [rffi.CWCHARP], rffi.INT,
1202 save_err=rffi.RFFI_SAVE_ERRNO)
1203
1204 @replace_os_function('unlink')
1205 @specialize.argtype(0)
1206 def unlink(path):
1207 if not _WIN32:
1208 handle_posix_error('unlink', c_unlink(_as_bytes0(path)))
1209 else:
1210 if isinstance(path, str):
1211 src_utf8 = path
1212 else:
1213 src_utf8 = path.as_utf8()
1214 with rffi.scoped_utf82wcharp(src_utf8) as src_wch:
1215 ret = rwin32.os_unlink_impl(src_wch)
1216 if not ret:
1217 raise rwin32.lastSavedWindowsError()
1218
1219 @replace_os_function('mkdir')
1220 @specialize.argtype(0)
1221 def mkdir(path, mode=0o777):
1222 if not _WIN32:
1223 handle_posix_error('mkdir', c_mkdir(_as_bytes0(path), mode))
1224 else:
1225 win32traits = make_win32_traits(utf8_traits)
1226 if isinstance(path, str):
1227 src_utf8 = path
1228 else:
1229 src_utf8 = path.as_utf8()
1230 with rffi.scoped_utf82wcharp(src_utf8) as src_wch:
1231 result = rwin32.os_createdirectory_impl(src_wch, mode)
1232 if result < 0:
1233 raise rwin32.lastSavedWindowsError()
1234
1235
1236 @replace_os_function('rmdir')
1237 @specialize.argtype(0)
1238 @jit.dont_look_inside
1239 def rmdir(path):
1240 if _WIN32:
1241 traits = utf8_traits
1242 utf8 = _as_utf80(path)
1243 with rffi.scoped_utf82wcharp(utf8) as buf:
1244 handle_posix_error('wrmdir', c_wrmdir(buf))
1245 else:
1246 handle_posix_error('rmdir', c_rmdir(_as_bytes0(path)))
1247
1248 c_chmod = external('chmod', [rffi.CCHARP, rffi.MODE_T], rffi.INT,
1249 save_err=rffi.RFFI_SAVE_ERRNO)
1250 c_fchmod = external('fchmod', [rffi.INT, rffi.MODE_T], rffi.INT,
1251 save_err=rffi.RFFI_SAVE_ERRNO,)
1252 c_rename = external('rename', [rffi.CCHARP, rffi.CCHARP], rffi.INT,
1253 save_err=rffi.RFFI_SAVE_ERRNO)
1254
1255 @replace_os_function('chmod')
1256 @specialize.argtype(0)
1257 def chmod(path, mode):
1258 if not _WIN32:
1259 handle_posix_error('chmod', c_chmod(_as_bytes0(path), mode))
1260 else:
1261 traits = utf8_traits
1262 win32traits = make_win32_traits(traits)
1263 utf8 = traits.as_utf80(path)
1264 with rffi.scoped_utf82wcharp(utf8) as buf:
1265 attr = win32traits.GetFileAttributes(buf)
1266 if attr == win32traits.INVALID_FILE_ATTRIBUTES:
1267 raise rwin32.lastSavedWindowsError()
1268 if mode & 0200: # _S_IWRITE
1269 attr &= ~win32traits.FILE_ATTRIBUTE_READONLY
1270 else:
1271 attr |= win32traits.FILE_ATTRIBUTE_READONLY
1272 with rffi.scoped_utf82wcharp(utf8) as buf:
1273 if not win32traits.SetFileAttributes(buf, attr):
1274 raise rwin32.lastSavedWindowsError()
1275
1276 @replace_os_function('fchmod')
1277 def fchmod(fd, mode):
1278 handle_posix_error('fchmod', c_fchmod(fd, mode))
1279
1280 @replace_os_function('rename')
1281 @specialize.argtype(0, 1)
1282 def rename(path1, path2):
1283 if _WIN32:
1284 traits = utf8_traits
1285 win32traits = make_win32_traits(traits)
1286 utf81 = traits.as_utf80(path1)
1287 utf82 = traits.as_utf80(path2)
1288 with rffi.scoped_utf82wcharp(utf81) as buf1:
1289 with rffi.scoped_utf82wcharp(utf82) as buf2:
1290 if not win32traits.MoveFileEx(buf1, buf2, 0):
1291 raise rwin32.lastSavedWindowsError()
1292 else:
1293 handle_posix_error('rename',
1294 c_rename(_as_bytes0(path1), _as_bytes0(path2)))
1295
1296 @specialize.argtype(0, 1)
1297 def replace(path1, path2):
1298 if _WIN32:
1299 traits = utf8_traits
1300 win32traits = make_win32_traits(traits)
1301 utf81 = traits.as_utf80(path1)
1302 utf82 = traits.as_utf80(path2)
1303 with rffi.scoped_utf82wcharp(utf81) as buf1:
1304 with rffi.scoped_utf82wcharp(utf82) as buf2:
1305 ret = win32traits.MoveFileEx(buf1, buf2,
1306 win32traits.MOVEFILE_REPLACE_EXISTING)
1307 if not ret:
1308 raise rwin32.lastSavedWindowsError()
1309 else:
1310 ret = rename(path1, path2)
1311 return ret
1312
1313 #___________________________________________________________________
1314
1315 c_mkfifo = external('mkfifo', [rffi.CCHARP, rffi.MODE_T], rffi.INT,
1316 save_err=rffi.RFFI_SAVE_ERRNO)
1317 c_mknod = external('mknod', [rffi.CCHARP, rffi.MODE_T, rffi.INT], rffi.INT,
1318 # # xxx: actually ^^^ dev_t
1319 macro=_MACRO_ON_POSIX, save_err=rffi.RFFI_SAVE_ERRNO)
1320
1321 @replace_os_function('mkfifo')
1322 @specialize.argtype(0)
1323 def mkfifo(path, mode):
1324 handle_posix_error('mkfifo', c_mkfifo(_as_bytes0(path), mode))
1325
1326 @replace_os_function('mknod')
1327 @specialize.argtype(0)
1328 def mknod(path, mode, dev):
1329 handle_posix_error('mknod', c_mknod(_as_bytes0(path), mode, dev))
1330
1331 constants =[ # These are added to posix/nt
1332 # windows
1333 'LOAD_LIBRARY_SEARCH_DEFAULT_DIRS',
1334 'LOAD_LIBRARY_SEARCH_APPLICATION_DIR',
1335 'LOAD_LIBRARY_SEARCH_SYSTEM32',
1336 'LOAD_LIBRARY_SEARCH_USER_DIRS',
1337 'LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR',
1338 # darwin
1339 'COPYFILE_DATA',
1340 # linux, darwin
1341 'O_CLOEXEC',
1342 ]
1343 darwin_constants = ['COPYFILE_DATA']
1344 if _WIN32:
1345 CreatePipe = external('CreatePipe', [rwin32.LPHANDLE,
1346 rwin32.LPHANDLE,
1347 rffi.VOIDP,
1348 rwin32.DWORD],
1349 rwin32.BOOL)
1350 c_open_osfhandle = external('_open_osfhandle', [rffi.INTPTR_T,
1351 rffi.INT],
1352 rffi.INT)
1353 HAVE_PIPE2 = False
1354 HAVE_DUP3 = False
1355 class CConfig:
1356 _compilation_info_ = eci
1357 for name in constants:
1358 setattr(CConfig, name, rffi_platform.DefinedConstantInteger(name))
1359 pipe_config = rffi_platform.configure(CConfig)
1360 for name in constants:
1361 locals()[name] = pipe_config[name]
1362 else:
1363 INT_ARRAY_P = rffi.CArrayPtr(rffi.INT_real)
1364 c_pipe = external('pipe', [INT_ARRAY_P], rffi.INT_real,
1365 save_err=rffi.RFFI_SAVE_ERRNO)
1366 class CConfig:
1367 _compilation_info_ = eci
1368 HAVE_PIPE2 = rffi_platform.Has('pipe2')
1369 HAVE_DUP3 = rffi_platform.Has('dup3')
1370 for name in constants:
1371 setattr(CConfig, name, rffi_platform.DefinedConstantInteger(name))
1372 pipe_config = rffi_platform.configure(CConfig)
1373 for name in constants:
1374 locals()[name] = pipe_config[name]
1375 HAVE_PIPE2 = pipe_config['HAVE_PIPE2']
1376 HAVE_DUP3 = pipe_config['HAVE_DUP3']
1377 if HAVE_PIPE2:
1378 c_pipe2 = external('pipe2', [INT_ARRAY_P, rffi.INT_real], rffi.INT_real,
1379 save_err=rffi.RFFI_SAVE_ERRNO)
1380
1381 @replace_os_function('pipe')
1382 def pipe(flags=0):
1383 # 'flags' might be ignored. Check the result.
1384 # The handles returned are always inheritable on Posix.
1385 # The situation on Windows is not completely clear: I think
1386 # it should always return non-inheritable handles, but CPython
1387 # uses SECURITY_ATTRIBUTES to ensure that and we don't.
1388 if _WIN32:
1389 # 'flags' ignored
1390 ralloc = lltype.scoped_alloc(rwin32.LPHANDLE.TO, 1)
1391 walloc = lltype.scoped_alloc(rwin32.LPHANDLE.TO, 1)
1392 with ralloc as pread, walloc as pwrite:
1393 if CreatePipe(pread, pwrite, lltype.nullptr(rffi.VOIDP.TO), 0):
1394 hread = pread[0]
1395 hwrite = pwrite[0]
1396 fdread = c_open_osfhandle(rffi.cast(rffi.INTPTR_T, hread), 0)
1397 fdwrite = c_open_osfhandle(rffi.cast(rffi.INTPTR_T, hwrite), 1)
1398 if not (fdread == -1 or fdwrite == -1):
1399 return (fdread, fdwrite)
1400 rwin32.CloseHandle(hread)
1401 rwin32.CloseHandle(hwrite)
1402 raise WindowsError(rwin32.GetLastError_saved(), "CreatePipe failed")
1403 else:
1404 filedes = lltype.malloc(INT_ARRAY_P.TO, 2, flavor='raw')
1405 try:
1406 if HAVE_PIPE2 and _pipe2_syscall.attempt_syscall():
1407 res = c_pipe2(filedes, flags)
1408 if _pipe2_syscall.fallback(res):
1409 res = c_pipe(filedes)
1410 else:
1411 res = c_pipe(filedes) # 'flags' ignored
1412 handle_posix_error('pipe', res)
1413 return (widen(filedes[0]), widen(filedes[1]))
1414 finally:
1415 lltype.free(filedes, flavor='raw')
1416
1417 def pipe2(flags):
1418 # Only available if there is really a c_pipe2 function.
1419 # No fallback to pipe() if we get ENOSYS.
1420 filedes = lltype.malloc(INT_ARRAY_P.TO, 2, flavor='raw')
1421 try:
1422 res = c_pipe2(filedes, flags)
1423 handle_posix_error('pipe2', res)
1424 return (widen(filedes[0]), widen(filedes[1]))
1425 finally:
1426 lltype.free(filedes, flavor='raw')
1427
1428 c_link = external('link', [rffi.CCHARP, rffi.CCHARP], rffi.INT,
1429 save_err=rffi.RFFI_SAVE_ERRNO,)
1430 c_symlink = external('symlink', [rffi.CCHARP, rffi.CCHARP], rffi.INT,
1431 save_err=rffi.RFFI_SAVE_ERRNO)
1432
1433 #___________________________________________________________________
1434
1435 @replace_os_function('link')
1436 @specialize.argtype(0, 1)
1437 def link(oldpath, newpath):
1438 if not _WIN32:
1439 oldpath = _as_bytes0(oldpath)
1440 newpath = _as_bytes0(newpath)
1441 handle_posix_error('link', c_link(oldpath, newpath))
1442 else:
1443 traits = utf8_traits
1444 win32traits = make_win32_traits(traits)
1445 utf8old = traits.as_utf80(oldpath)
1446 utf8new = traits.as_utf80(newpath)
1447 with rffi.scoped_utf82wcharp(utf8old) as oldbuf:
1448 with rffi.scoped_utf82wcharp(utf8new) as newbuf:
1449 if not win32traits.CreateHardLink(newbuf, oldbuf, None):
1450 raise rwin32.lastSavedWindowsError()
1451
1452 @replace_os_function('symlink')
1453 @specialize.argtype(0, 1)
1454 def symlink(oldpath, newpath):
1455 oldpath = _as_bytes0(oldpath)
1456 newpath = _as_bytes0(newpath)
1457 handle_posix_error('symlink', c_symlink(oldpath, newpath))
1458
1459 c_umask = external(UNDERSCORE_ON_WIN32 + 'umask', [rffi.MODE_T], rffi.MODE_T)
1460
1461 @replace_os_function('umask')
1462 def umask(newmask):
1463 return widen(c_umask(newmask))
1464
1465 c_chown = external('chown', [rffi.CCHARP, rffi.INT, rffi.INT], rffi.INT,
1466 save_err=rffi.RFFI_SAVE_ERRNO)
1467 c_lchown = external('lchown', [rffi.CCHARP, rffi.INT, rffi.INT], rffi.INT,
1468 save_err=rffi.RFFI_SAVE_ERRNO)
1469 c_fchown = external('fchown', [rffi.INT, rffi.INT, rffi.INT], rffi.INT,
1470 save_err=rffi.RFFI_SAVE_ERRNO)
1471
1472 @replace_os_function('chown')
1473 def chown(path, uid, gid):
1474 handle_posix_error('chown', c_chown(path, uid, gid))
1475
1476 @replace_os_function('lchown')
1477 def lchown(path, uid, gid):
1478 handle_posix_error('lchown', c_lchown(path, uid, gid))
1479
1480 @replace_os_function('fchown')
1481 def fchown(fd, uid, gid):
1482 handle_posix_error('fchown', c_fchown(fd, uid, gid))
1483
1484 #___________________________________________________________________
1485
1486 UTIMBUFP = lltype.Ptr(UTIMBUF)
1487 c_utime = external('utime', [rffi.CCHARP, UTIMBUFP], rffi.INT,
1488 save_err=rffi.RFFI_SAVE_ERRNO)
1489 if HAVE_UTIMES:
1490 class CConfig:
1491 _compilation_info_ = eci
1492 TIMEVAL = rffi_platform.Struct('struct timeval', [
1493 ('tv_sec', rffi.LONG),
1494 ('tv_usec', rffi.LONG)])
1495 times_config = rffi_platform.configure(CConfig)
1496 TIMEVAL = times_config['TIMEVAL']
1497 TIMEVAL2P = rffi.CArrayPtr(TIMEVAL)
1498 c_utimes = external('utimes', [rffi.CCHARP, TIMEVAL2P], rffi.INT,
1499 save_err=rffi.RFFI_SAVE_ERRNO)
1500
1501 if _WIN32:
1502 from rpython.rlib import rwin32
1503 GetSystemTime = external(
1504 'GetSystemTime',
1505 [lltype.Ptr(rwin32.SYSTEMTIME)],
1506 lltype.Void,
1507 calling_conv='win',
1508 save_err=rffi.RFFI_SAVE_LASTERROR)
1509
1510 SystemTimeToFileTime = external(
1511 'SystemTimeToFileTime',
1512 [lltype.Ptr(rwin32.SYSTEMTIME),
1513 lltype.Ptr(rwin32.FILETIME)],
1514 rwin32.BOOL,
1515 calling_conv='win',
1516 save_err=rffi.RFFI_SAVE_LASTERROR)
1517
1518 SetFileTime = external(
1519 'SetFileTime',
1520 [rwin32.HANDLE,
1521 lltype.Ptr(rwin32.FILETIME),
1522 lltype.Ptr(rwin32.FILETIME),
1523 lltype.Ptr(rwin32.FILETIME)],
1524 rwin32.BOOL,
1525 calling_conv='win')
1526
1527
1528 @replace_os_function('utime')
1529 @specialize.argtype(0, 1)
1530 def utime(path, times):
1531 if not _WIN32:
1532 path = _as_bytes0(path)
1533 if times is None:
1534 error = c_utime(path, lltype.nullptr(UTIMBUFP.TO))
1535 else:
1536 if HAVE_UTIMES:
1537 with lltype.scoped_alloc(TIMEVAL2P.TO, 2) as l_timeval2p:
1538 times_to_timeval2p(times, l_timeval2p)
1539 error = c_utimes(path, l_timeval2p)
1540 else:
1541 # we only have utime(), which does not allow
1542 # sub-second resolution
1543 actime, modtime = times
1544 l_utimbuf = lltype.malloc(UTIMBUFP.TO, flavor='raw')
1545 l_utimbuf.c_actime = rffi.r_time_t(actime)
1546 l_utimbuf.c_modtime = rffi.r_time_t(modtime)
1547 error = c_utime(path, l_utimbuf)
1548 lltype.free(l_utimbuf, flavor='raw')
1549 handle_posix_error('utime', error)
1550 else: # _WIN32 case
1551 from rpython.rlib.rwin32file import time_t_to_FILE_TIME
1552 traits = utf8_traits
1553 win32traits = make_win32_traits(traits)
1554 path = traits.as_utf80(path)
1555 with rffi.scoped_utf82wcharp(path) as buf:
1556
1557 hFile = win32traits.CreateFile(buf,
1558 win32traits.FILE_WRITE_ATTRIBUTES, 0,
1559 None, win32traits.OPEN_EXISTING,
1560 win32traits.FILE_FLAG_BACKUP_SEMANTICS,
1561 rwin32.NULL_HANDLE)
1562 if hFile == rwin32.INVALID_HANDLE_VALUE:
1563 raise rwin32.lastSavedWindowsError()
1564 ctime = lltype.nullptr(rwin32.FILETIME)
1565 atime = lltype.malloc(rwin32.FILETIME, flavor='raw')
1566 mtime = lltype.malloc(rwin32.FILETIME, flavor='raw')
1567 try:
1568 if times is None:
1569 now = lltype.malloc(rwin32.SYSTEMTIME, flavor='raw')
1570 try:
1571 GetSystemTime(now)
1572 if (not SystemTimeToFileTime(now, atime) or
1573 not SystemTimeToFileTime(now, mtime)):
1574 raise rwin32.lastSavedWindowsError()
1575 finally:
1576 lltype.free(now, flavor='raw')
1577 else:
1578 actime, modtime = times
1579 time_t_to_FILE_TIME(actime, atime)
1580 time_t_to_FILE_TIME(modtime, mtime)
1581 if not SetFileTime(hFile, ctime, atime, mtime):
1582 raise rwin32.lastSavedWindowsError()
1583 finally:
1584 rwin32.CloseHandle(hFile)
1585 lltype.free(atime, flavor='raw')
1586 lltype.free(mtime, flavor='raw')
1587
1588 def times_to_timeval2p(times, l_timeval2p):
1589 actime, modtime = times
1590 _time_to_timeval(actime, l_timeval2p[0])
1591 _time_to_timeval(modtime, l_timeval2p[1])
1592
1593 def _time_to_timeval(t, l_timeval):
1594 import math
1595 fracpart, intpart = math.modf(t)
1596 intpart = int(intpart)
1597 fracpart = int(fracpart * 1e6)
1598 if fracpart < 0:
1599 intpart -= 1
1600 fracpart += 1000000
1601 assert 0 <= fracpart < 1000000
1602 rffi.setintfield(l_timeval, 'c_tv_sec', intpart)
1603 rffi.setintfield(l_timeval, 'c_tv_usec', fracpart)
1604
1605 if not _WIN32:
1606 TMSP = lltype.Ptr(TMS)
1607 c_times = external('times', [TMSP], CLOCK_T,
1608 save_err=rffi.RFFI_SAVE_ERRNO |
1609 rffi.RFFI_ZERO_ERRNO_BEFORE)
1610
1611 # Here is a random extra platform parameter which is important.
1612 # Strictly speaking, this should probably be retrieved at runtime, not
1613 # at translation time.
1614 CLOCK_TICKS_PER_SECOND = float(os.sysconf('SC_CLK_TCK'))
1615 else:
1616 GetCurrentProcess = external(
1617 'GetCurrentProcess', [],
1618 rwin32.HANDLE, calling_conv='win')
1619 GetProcessTimes = external(
1620 'GetProcessTimes', [
1621 rwin32.HANDLE,
1622 lltype.Ptr(rwin32.FILETIME), lltype.Ptr(rwin32.FILETIME),
1623 lltype.Ptr(rwin32.FILETIME), lltype.Ptr(rwin32.FILETIME)],
1624 rwin32.BOOL, calling_conv='win')
1625
1626 @replace_os_function('times')
1627 def times():
1628 if not _WIN32:
1629 l_tmsbuf = lltype.malloc(TMSP.TO, flavor='raw')
1630 try:
1631 # note: times() can return a negative value (or even -1)
1632 # even if there is no error
1633 result = rffi.cast(lltype.Signed, c_times(l_tmsbuf))
1634 if result == -1:
1635 errno = get_saved_errno()
1636 if errno != 0:
1637 raise OSError(errno, 'times() failed')
1638 return (
1639 rffi.cast(lltype.Signed, l_tmsbuf.c_tms_utime)
1640 / CLOCK_TICKS_PER_SECOND,
1641 rffi.cast(lltype.Signed, l_tmsbuf.c_tms_stime)
1642 / CLOCK_TICKS_PER_SECOND,
1643 rffi.cast(lltype.Signed, l_tmsbuf.c_tms_cutime)
1644 / CLOCK_TICKS_PER_SECOND,
1645 rffi.cast(lltype.Signed, l_tmsbuf.c_tms_cstime)
1646 / CLOCK_TICKS_PER_SECOND,
1647 result / CLOCK_TICKS_PER_SECOND)
1648 finally:
1649 lltype.free(l_tmsbuf, flavor='raw')
1650 else:
1651 pcreate = lltype.malloc(rwin32.FILETIME, flavor='raw')
1652 pexit = lltype.malloc(rwin32.FILETIME, flavor='raw')
1653 pkernel = lltype.malloc(rwin32.FILETIME, flavor='raw')
1654 puser = lltype.malloc(rwin32.FILETIME, flavor='raw')
1655 try:
1656 hProc = GetCurrentProcess()
1657 GetProcessTimes(hProc, pcreate, pexit, pkernel, puser)
1658 # The fields of a FILETIME structure are the hi and lo parts
1659 # of a 64-bit value expressed in 100 nanosecond units
1660 # (of course).
1661 return (
1662 rffi.cast(lltype.Signed, pkernel.c_dwHighDateTime) * 429.4967296 +
1663 rffi.cast(lltype.Signed, pkernel.c_dwLowDateTime) * 1E-7,
1664 rffi.cast(lltype.Signed, puser.c_dwHighDateTime) * 429.4967296 +
1665 rffi.cast(lltype.Signed, puser.c_dwLowDateTime) * 1E-7,
1666 0., 0., 0.)
1667 finally:
1668 lltype.free(puser, flavor='raw')
1669 lltype.free(pkernel, flavor='raw')
1670 lltype.free(pexit, flavor='raw')
1671 lltype.free(pcreate, flavor='raw')
1672
1673 c_kill = external('kill', [rffi.PID_T, rffi.INT], rffi.INT,
1674 save_err=rffi.RFFI_SAVE_ERRNO)
1675 c_killpg = external('killpg', [rffi.INT, rffi.INT], rffi.INT,
1676 save_err=rffi.RFFI_SAVE_ERRNO)
1677 c_exit = external('_exit', [rffi.INT], lltype.Void)
1678 c_nice = external('nice', [rffi.INT], rffi.INT,
1679 save_err=rffi.RFFI_FULL_ERRNO_ZERO)
1680
1681 @replace_os_function('kill')
1682 def kill(pid, sig):
1683 if not _WIN32:
1684 return handle_posix_error('kill', c_kill(pid, sig))
1685 else:
1686 if sig == rwin32.CTRL_C_EVENT or sig == rwin32.CTRL_BREAK_EVENT:
1687 if rwin32.GenerateConsoleCtrlEvent(sig, pid) == 0:
1688 raise rwin32.lastSavedWindowsError(
1689 'kill() failed generating event')
1690 return
1691 handle = rwin32.OpenProcess(rwin32.PROCESS_ALL_ACCESS, False, pid)
1692 if not handle:
1693 raise rwin32.lastSavedWindowsError('kill() failed opening process')
1694 try:
1695 if rwin32.TerminateProcess(handle, sig) == 0:
1696 raise rwin32.lastSavedWindowsError(
1697 'kill() failed to terminate process')
1698 finally:
1699 rwin32.CloseHandle(handle)
1700
1701 @replace_os_function('killpg')
1702 def killpg(pgrp, sig):
1703 return handle_posix_error('killpg', c_killpg(pgrp, sig))
1704
1705 @replace_os_function('_exit')
1706 @jit.dont_look_inside
1707 def exit(status):
1708 debug.debug_flush()
1709 c_exit(status)
1710
1711 @replace_os_function('nice')
1712 def nice(inc):
1713 # Assume that the system provides a standard-compliant version
1714 # of nice() that returns the new priority. Nowadays, FreeBSD
1715 # might be the last major non-compliant system (xxx check me).
1716 res = widen(c_nice(inc))
1717 if res == -1:
1718 err = get_saved_errno()
1719 if err != 0:
1720 raise OSError(err, "os_nice failed")
1721 return res
1722
1723 c_ctermid = external('ctermid', [rffi.CCHARP], rffi.CCHARP)
1724
1725 @replace_os_function('ctermid')
1726 def ctermid():
1727 return rffi.charp2str(c_ctermid(lltype.nullptr(rffi.CCHARP.TO)))
1728
1729 c_tmpnam = external('tmpnam', [rffi.CCHARP], rffi.CCHARP)
1730
1731 @replace_os_function('tmpnam')
1732 def tmpnam():
1733 return rffi.charp2str(c_tmpnam(lltype.nullptr(rffi.CCHARP.TO)))
1734
1735 #___________________________________________________________________
1736
1737 c_getpid = external('getpid', [], rffi.PID_T,
1738 releasegil=False, save_err=rffi.RFFI_SAVE_ERRNO)
1739 c_getppid = external('getppid', [], rffi.PID_T,
1740 releasegil=False, save_err=rffi.RFFI_SAVE_ERRNO)
1741 c_setsid = external('setsid', [], rffi.PID_T,
1742 save_err=rffi.RFFI_SAVE_ERRNO)
1743 c_getsid = external('getsid', [rffi.PID_T], rffi.PID_T,
1744 save_err=rffi.RFFI_SAVE_ERRNO)
1745
1746 @replace_os_function('getpid')
1747 def getpid():
1748 return handle_posix_error('getpid', c_getpid())
1749
1750 @replace_os_function('getppid')
1751 def getppid():
1752 return handle_posix_error('getppid', c_getppid())
1753
1754 @replace_os_function('setsid')
1755 def setsid():
1756 return handle_posix_error('setsid', c_setsid())
1757
1758 @replace_os_function('getsid')
1759 def getsid(pid):
1760 return handle_posix_error('getsid', c_getsid(pid))
1761
1762 c_getpgid = external('getpgid', [rffi.PID_T], rffi.PID_T,
1763 save_err=rffi.RFFI_SAVE_ERRNO)
1764 c_setpgid = external('setpgid', [rffi.PID_T, rffi.PID_T], rffi.INT,
1765 save_err=rffi.RFFI_SAVE_ERRNO)
1766
1767 @replace_os_function('getpgid')
1768 def getpgid(pid):
1769 return handle_posix_error('getpgid', c_getpgid(pid))
1770
1771 @replace_os_function('setpgid')
1772 def setpgid(pid, gid):
1773 handle_posix_error('setpgid', c_setpgid(pid, gid))
1774
1775 if not _WIN32:
1776 GID_GROUPS_T = rffi.CArrayPtr(GID_T)
1777 c_getgroups = external('getgroups', [rffi.INT, GID_GROUPS_T], rffi.INT,
1778 save_err=rffi.RFFI_SAVE_ERRNO)
1779 c_setgroups = external('setgroups', [rffi.SIZE_T, GID_GROUPS_T], rffi.INT,
1780 save_err=rffi.RFFI_SAVE_ERRNO)
1781 c_initgroups = external('initgroups', [rffi.CCHARP, GID_T], rffi.INT,
1782 save_err=rffi.RFFI_SAVE_ERRNO)
1783
1784 @replace_os_function('getgroups')
1785 def getgroups():
1786 n = handle_posix_error('getgroups',
1787 c_getgroups(0, lltype.nullptr(GID_GROUPS_T.TO)))
1788 groups = lltype.malloc(GID_GROUPS_T.TO, n, flavor='raw')
1789 try:
1790 n = handle_posix_error('getgroups', c_getgroups(n, groups))
1791 return [widen_gid(groups[i]) for i in range(n)]
1792 finally:
1793 lltype.free(groups, flavor='raw')
1794
1795 @replace_os_function('setgroups')
1796 def setgroups(gids):
1797 n = len(gids)
1798 groups = lltype.malloc(GID_GROUPS_T.TO, n, flavor='raw')
1799 try:
1800 for i in range(n):
1801 groups[i] = rffi.cast(GID_T, gids[i])
1802 handle_posix_error('setgroups', c_setgroups(n, groups))
1803 finally:
1804 lltype.free(groups, flavor='raw')
1805
1806 @replace_os_function('initgroups')
1807 def initgroups(user, group):
1808 handle_posix_error('initgroups', c_initgroups(user, group))
1809
1810 if GETPGRP_HAVE_ARG:
1811 c_getpgrp = external('getpgrp', [rffi.INT], rffi.INT,
1812 save_err=rffi.RFFI_SAVE_ERRNO)
1813 else:
1814 c_getpgrp = external('getpgrp', [], rffi.INT,
1815 save_err=rffi.RFFI_SAVE_ERRNO)
1816 if SETPGRP_HAVE_ARG:
1817 c_setpgrp = external('setpgrp', [rffi.INT, rffi.INT], rffi.INT,
1818 save_err=rffi.RFFI_SAVE_ERRNO)
1819 else:
1820 c_setpgrp = external('setpgrp', [], rffi.INT,
1821 save_err=rffi.RFFI_SAVE_ERRNO)
1822
1823 @replace_os_function('getpgrp')
1824 def getpgrp():
1825 if GETPGRP_HAVE_ARG:
1826 return handle_posix_error('getpgrp', c_getpgrp(0))
1827 else:
1828 return handle_posix_error('getpgrp', c_getpgrp())
1829
1830 @replace_os_function('setpgrp')
1831 def setpgrp():
1832 if SETPGRP_HAVE_ARG:
1833 handle_posix_error('setpgrp', c_setpgrp(0, 0))
1834 else:
1835 handle_posix_error('setpgrp', c_setpgrp())
1836
1837 c_tcgetpgrp = external('tcgetpgrp', [rffi.INT], rffi.PID_T,
1838 save_err=rffi.RFFI_SAVE_ERRNO)
1839 c_tcsetpgrp = external('tcsetpgrp', [rffi.INT, rffi.PID_T], rffi.INT,
1840 save_err=rffi.RFFI_SAVE_ERRNO)
1841
1842 @replace_os_function('tcgetpgrp')
1843 def tcgetpgrp(fd):
1844 return handle_posix_error('tcgetpgrp', c_tcgetpgrp(fd))
1845
1846 @replace_os_function('tcsetpgrp')
1847 def tcsetpgrp(fd, pgrp):
1848 return handle_posix_error('tcsetpgrp', c_tcsetpgrp(fd, pgrp))
1849
1850 #___________________________________________________________________
1851
1852 if not _WIN32:
1853 c_getuid = external('getuid', [], UID_T)
1854 c_geteuid = external('geteuid', [], UID_T)
1855 c_setuid = external('setuid', [UID_T], rffi.INT,
1856 save_err=rffi.RFFI_SAVE_ERRNO)
1857 c_seteuid = external('seteuid', [UID_T], rffi.INT,
1858 save_err=rffi.RFFI_SAVE_ERRNO)
1859 c_getgid = external('getgid', [], GID_T)
1860 c_getegid = external('getegid', [], GID_T)
1861 c_setgid = external('setgid', [GID_T], rffi.INT,
1862 save_err=rffi.RFFI_SAVE_ERRNO)
1863 c_setegid = external('setegid', [GID_T], rffi.INT,
1864 save_err=rffi.RFFI_SAVE_ERRNO)
1865
1866 def widen_uid(x):
1867 return rffi.cast(lltype.Unsigned, x)
1868 widen_gid = widen_uid
1869
1870 # NOTE: the resulting type of functions that return a uid/gid is
1871 # always Unsigned. The argument type of functions that take a
1872 # uid/gid should also be Unsigned.
1873
1874 @replace_os_function('getuid')
1875 def getuid():
1876 return widen_uid(c_getuid())
1877
1878 @replace_os_function('geteuid')
1879 def geteuid():
1880 return widen_uid(c_geteuid())
1881
1882 @replace_os_function('setuid')
1883 def setuid(uid):
1884 handle_posix_error('setuid', c_setuid(uid))
1885
1886 @replace_os_function('seteuid')
1887 def seteuid(uid):
1888 handle_posix_error('seteuid', c_seteuid(uid))
1889
1890 @replace_os_function('getgid')
1891 def getgid():
1892 return widen_gid(c_getgid())
1893
1894 @replace_os_function('getegid')
1895 def getegid():
1896 return widen_gid(c_getegid())
1897
1898 @replace_os_function('setgid')
1899 def setgid(gid):
1900 handle_posix_error('setgid', c_setgid(gid))
1901
1902 @replace_os_function('setegid')
1903 def setegid(gid):
1904 handle_posix_error('setegid', c_setegid(gid))
1905
1906 c_setreuid = external('setreuid', [UID_T, UID_T], rffi.INT,
1907 save_err=rffi.RFFI_SAVE_ERRNO)
1908 c_setregid = external('setregid', [GID_T, GID_T], rffi.INT,
1909 save_err=rffi.RFFI_SAVE_ERRNO)
1910
1911 @replace_os_function('setreuid')
1912 def setreuid(ruid, euid):
1913 handle_posix_error('setreuid', c_setreuid(ruid, euid))
1914
1915 @replace_os_function('setregid')
1916 def setregid(rgid, egid):
1917 handle_posix_error('setregid', c_setregid(rgid, egid))
1918
1919 UID_T_P = lltype.Ptr(lltype.Array(UID_T, hints={'nolength': True}))
1920 GID_T_P = lltype.Ptr(lltype.Array(GID_T, hints={'nolength': True}))
1921 c_getresuid = external('getresuid', [UID_T_P] * 3, rffi.INT,
1922 save_err=rffi.RFFI_SAVE_ERRNO)
1923 c_getresgid = external('getresgid', [GID_T_P] * 3, rffi.INT,
1924 save_err=rffi.RFFI_SAVE_ERRNO)
1925 c_setresuid = external('setresuid', [UID_T] * 3, rffi.INT,
1926 save_err=rffi.RFFI_SAVE_ERRNO)
1927 c_setresgid = external('setresgid', [GID_T] * 3, rffi.INT,
1928 save_err=rffi.RFFI_SAVE_ERRNO)
1929
1930 @replace_os_function('getresuid')
1931 def getresuid():
1932 out = lltype.malloc(UID_T_P.TO, 3, flavor='raw')
1933 try:
1934 handle_posix_error('getresuid',
1935 c_getresuid(rffi.ptradd(out, 0),
1936 rffi.ptradd(out, 1),
1937 rffi.ptradd(out, 2)))
1938 return (widen_uid(out[0]), widen_uid(out[1]), widen_uid(out[2]))
1939 finally:
1940 lltype.free(out, flavor='raw')
1941
1942 @replace_os_function('getresgid')
1943 def getresgid():
1944 out = lltype.malloc(GID_T_P.TO, 3, flavor='raw')
1945 try:
1946 handle_posix_error('getresgid',
1947 c_getresgid(rffi.ptradd(out, 0),
1948 rffi.ptradd(out, 1),
1949 rffi.ptradd(out, 2)))
1950 return (widen_gid(out[0]), widen_gid(out[1]), widen_gid(out[2]))
1951 finally:
1952 lltype.free(out, flavor='raw')
1953
1954 @replace_os_function('setresuid')
1955 def setresuid(ruid, euid, suid):
1956 handle_posix_error('setresuid', c_setresuid(ruid, euid, suid))
1957
1958 @replace_os_function('setresgid')
1959 def setresgid(rgid, egid, sgid):
1960 handle_posix_error('setresgid', c_setresgid(rgid, egid, sgid))
1961
1962 c_getpriority = external('getpriority', [rffi.INT, ID_T], rffi.INT,
1963 save_err=rffi.RFFI_FULL_ERRNO_ZERO)
1964 c_setpriority = external('setpriority', [rffi.INT, ID_T, rffi.INT],
1965 rffi.INT, save_err=rffi.RFFI_SAVE_ERRNO)
1966
1967 def getpriority(which, who):
1968 result = widen(c_getpriority(which, who))
1969 error = get_saved_errno()
1970 if error != 0:
1971 raise OSError(error, 'getpriority failed')
1972 return result
1973
1974 def setpriority(which, who, prio):
1975 handle_posix_error('setpriority', c_setpriority(which, who, prio))
1976
1977 c_sched_get_priority_max = external('sched_get_priority_max', [rffi.INT],
1978 rffi.INT, save_err=rffi.RFFI_FULL_ERRNO_ZERO)
1979 c_sched_get_priority_min = external('sched_get_priority_min', [rffi.INT],
1980 rffi.INT, save_err=rffi.RFFI_SAVE_ERRNO)
1981 c_sched_yield = external('sched_yield', [], rffi.INT)
1982
1983 @enforceargs(int)
1984 def sched_get_priority_max(policy):
1985 return handle_posix_error('sched_get_priority_max', c_sched_get_priority_max(policy))
1986
1987 @enforceargs(int)
1988 def sched_get_priority_min(policy):
1989 return handle_posix_error('sched_get_priority_min', c_sched_get_priority_min(policy))
1990
1991 def sched_yield():
1992 return handle_posix_error('sched_yield', c_sched_yield())
1993
1994 c_getgroupslist = external('getgrouplist', [rffi.CCHARP, GID_T,
1995 GID_GROUPS_T, rffi.INT_realP], rffi.INT,
1996 save_err=rffi.RFFI_SAVE_ERRNO)
1997
1998 def getgrouplist(user, group):
1999 groups_p = lltype.malloc(GID_GROUPS_T.TO, 64, flavor='raw')
2000 ngroups_p = lltype.malloc(rffi.INT_realP.TO, 1, flavor='raw')
2001 ngroups_p[0] = rffi.cast(rffi.INT_real, 64)
2002 try:
2003 n = handle_posix_error('getgrouplist', c_getgroupslist(user, group,
2004 groups_p, ngroups_p))
2005 if n == -1:
2006 if widen(ngroups_p[0]) > 64:
2007 # reallocate. Should never happen
2008 lltype.free(groups_p, flavor='raw')
2009 groups_p = lltype.nullptr(GID_GROUPS_T.TO)
2010 groups_p = lltype.malloc(GID_GROUPS_T.TO, widen(ngroups_p[0]),
2011 flavor='raw')
2012
2013 n = handle_posix_error('getgrouplist', c_getgroupslist(user,
2014 group, groups_p, ngroups_p))
2015 ngroups = widen(ngroups_p[0])
2016 groups = [0] * ngroups
2017 for i in range(ngroups):
2018 groups[i] = widen_gid(groups_p[i])
2019 return groups
2020 finally:
2021 lltype.free(ngroups_p, flavor='raw')
2022 if groups_p:
2023 lltype.free(groups_p, flavor='raw')
2024
2025
2026 #___________________________________________________________________
2027
2028 c_chroot = external('chroot', [rffi.CCHARP], rffi.INT,
2029 save_err=rffi.RFFI_SAVE_ERRNO,
2030 macro=_MACRO_ON_POSIX,
2031 compilation_info=ExternalCompilationInfo(includes=['unistd.h']))
2032
2033 @replace_os_function('chroot')
2034 def chroot(path):
2035 handle_posix_error('chroot', c_chroot(_as_bytes0(path)))
2036
2037 if not _WIN32:
2038 CHARARRAY1 = lltype.FixedSizeArray(lltype.Char, 1)
2039 class CConfig:
2040 _compilation_info_ = ExternalCompilationInfo(
2041 includes = ['sys/utsname.h']
2042 )
2043 UTSNAME = rffi_platform.Struct('struct utsname', [
2044 ('sysname', CHARARRAY1),
2045 ('nodename', CHARARRAY1),
2046 ('release', CHARARRAY1),
2047 ('version', CHARARRAY1),
2048 ('machine', CHARARRAY1)])
2049 uts_config = rffi_platform.configure(CConfig)
2050 UTSNAMEP = lltype.Ptr(uts_config['UTSNAME'])
2051
2052 c_uname = external('uname', [UTSNAMEP], rffi.INT,
2053 compilation_info=CConfig._compilation_info_,
2054 save_err=rffi.RFFI_SAVE_ERRNO)
2055
2056 @replace_os_function('uname')
2057 def uname():
2058 l_utsbuf = lltype.malloc(UTSNAMEP.TO, flavor='raw')
2059 try:
2060 handle_posix_error('uname', c_uname(l_utsbuf))
2061 return (
2062 rffi.charp2str(rffi.cast(rffi.CCHARP, l_utsbuf.c_sysname)),
2063 rffi.charp2str(rffi.cast(rffi.CCHARP, l_utsbuf.c_nodename)),
2064 rffi.charp2str(rffi.cast(rffi.CCHARP, l_utsbuf.c_release)),
2065 rffi.charp2str(rffi.cast(rffi.CCHARP, l_utsbuf.c_version)),
2066 rffi.charp2str(rffi.cast(rffi.CCHARP, l_utsbuf.c_machine)),
2067 )
2068 finally:
2069 lltype.free(l_utsbuf, flavor='raw')
2070
2071 if sys.platform != 'win32':
2072 # These are actually macros on some/most systems
2073 c_makedev = external('makedev', [rffi.INT, rffi.INT], rffi.INT, macro=True)
2074 c_major = external('major', [rffi.INT], rffi.INT, macro=True)
2075 c_minor = external('minor', [rffi.INT], rffi.INT, macro=True)
2076
2077 @replace_os_function('makedev')
2078 def makedev(maj, min):
2079 return c_makedev(maj, min)
2080
2081 @replace_os_function('major')
2082 def major(dev):
2083 return c_major(dev)
2084
2085 @replace_os_function('minor')
2086 def minor(dev):
2087 return c_minor(dev)
2088
2089 #___________________________________________________________________
2090
2091 c_sysconf = external('sysconf', [rffi.INT], rffi.LONG,
2092 save_err=rffi.RFFI_FULL_ERRNO_ZERO)
2093 c_fpathconf = external('fpathconf', [rffi.INT, rffi.INT], rffi.LONG,
2094 save_err=rffi.RFFI_FULL_ERRNO_ZERO)
2095 c_pathconf = external('pathconf', [rffi.CCHARP, rffi.INT], rffi.LONG,
2096 save_err=rffi.RFFI_FULL_ERRNO_ZERO)
2097 c_confstr = external('confstr',
2098 [rffi.INT, rffi.CCHARP, rffi.SIZE_T], rffi.SIZE_T,
2099 save_err=rffi.RFFI_FULL_ERRNO_ZERO)
2100
2101 @replace_os_function('sysconf')
2102 def sysconf(value):
2103 res = c_sysconf(value)
2104 if res == -1:
2105 errno = get_saved_errno()
2106 if errno != 0:
2107 raise OSError(errno, "sysconf failed")
2108 return res
2109
2110 @replace_os_function('fpathconf')
2111 def fpathconf(fd, value):
2112 res = c_fpathconf(fd, value)
2113 if res == -1:
2114 errno = get_saved_errno()
2115 if errno != 0:
2116 raise OSError(errno, "fpathconf failed")
2117 return res
2118
2119 @replace_os_function('pathconf')
2120 def pathconf(path, value):
2121 res = c_pathconf(_as_bytes0(path), value)
2122 if res == -1:
2123 errno = get_saved_errno()
2124 if errno != 0:
2125 raise OSError(errno, "pathconf failed")
2126 return res
2127
2128 @replace_os_function('confstr')
2129 def confstr(value):
2130 n = intmask(c_confstr(value, lltype.nullptr(rffi.CCHARP.TO), 0))
2131 if n > 0:
2132 buf = lltype.malloc(rffi.CCHARP.TO, n, flavor='raw')
2133 try:
2134 c_confstr(value, buf, n)
2135 return rffi.charp2strn(buf, n)
2136 finally:
2137 lltype.free(buf, flavor='raw')
2138 else:
2139 errno = get_saved_errno()
2140 if errno != 0:
2141 raise OSError(errno, "confstr failed")
2142 return None
2143
2144 # ____________________________________________________________
2145 # Support for os.environ
2146
2147 # XXX only for systems where os.environ is an instance of _Environ,
2148 # which should cover Unix and Windows at least
2149 assert type(os.environ) is not dict
2150
2151 from rpython.rtyper.controllerentry import ControllerEntryForPrebuilt
2152
2153 class EnvironExtRegistry(ControllerEntryForPrebuilt):
2154 _about_ = os.environ
2155
2156 def getcontroller(self):
2157 from rpython.rlib.rposix_environ import OsEnvironController
2158 return OsEnvironController()
2159
2160
2161 # ____________________________________________________________
2162 # Support for f... and ...at families of POSIX functions
2163
2164 class CConfig:
2165 _compilation_info_ = eci.merge(ExternalCompilationInfo(
2166 includes=['sys/statvfs.h'],
2167 ))
2168 for _name in """faccessat fchdir fchmod fchmodat fchown fchownat fexecve
2169 fdopendir fpathconf fstat fstatat fstatvfs ftruncate
2170 futimens futimes futimesat linkat chflags lchflags lchmod lchown
2171 lstat lutimes mkdirat mkfifoat mknodat openat readlinkat renameat
2172 symlinkat unlinkat utimensat sched_getparam""".split():
2173 locals()['HAVE_%s' % _name.upper()] = rffi_platform.Has(_name)
2174 cConfig = rffi_platform.configure(CConfig)
2175 if _LINUX:
2176 # From CPython's configure script:
2177 # Force lchmod off for Linux. Linux disallows changing the mode of symbolic
2178 # links. Some libc implementations have a stub lchmod implementation that
2179 # always returns an error.
2180 cConfig["HAVE_LCHMOD"] = False
2181 globals().update(cConfig)
2182
2183 if not _WIN32:
2184 class CConfig:
2185 _compilation_info_ = ExternalCompilationInfo(
2186 includes=['sys/stat.h',
2187 'unistd.h',
2188 'fcntl.h',
2189 ],
2190 )
2191 AT_FDCWD = rffi_platform.DefinedConstantInteger('AT_FDCWD')
2192 AT_SYMLINK_NOFOLLOW = rffi_platform.DefinedConstantInteger('AT_SYMLINK_NOFOLLOW')
2193 AT_EACCESS = rffi_platform.DefinedConstantInteger('AT_EACCESS')
2194 AT_REMOVEDIR = rffi_platform.DefinedConstantInteger('AT_REMOVEDIR')
2195 AT_EMPTY_PATH = rffi_platform.DefinedConstantInteger('AT_EMPTY_PATH')
2196 UTIME_NOW = rffi_platform.DefinedConstantInteger('UTIME_NOW')
2197 UTIME_OMIT = rffi_platform.DefinedConstantInteger('UTIME_OMIT')
2198 TIMESPEC = rffi_platform.Struct('struct timespec', [
2199 ('tv_sec', rffi.TIME_T),
2200 ('tv_nsec', rffi.LONG)])
2201 AT_EACCESS = rffi_platform.DefinedConstantInteger('AT_EACCESS')
2202
2203 cConfig = rffi_platform.configure(CConfig)
2204 globals().update(cConfig)
2205
2206 TIMESPEC2P = rffi.CArrayPtr(TIMESPEC)
2207
2208 class ConfConfig:
2209 _compilation_info_ = ExternalCompilationInfo(
2210 includes=[ 'unistd.h', ],
2211 )
2212
2213 # Taken from posixmodule.c. Note the avaialbility is determined at
2214 # compile time by the host, but filled in by a runtime call to pathconf,
2215 # sysconf, or confstr.
2216 pathconf_consts_defs = {
2217 "PC_ABI_AIO_XFER_MAX": "_PC_ABI_AIO_XFER_MAX",
2218 "PC_ABI_ASYNC_IO": "_PC_ABI_ASYNC_IO",
2219 "PC_ASYNC_IO": "_PC_ASYNC_IO",
2220 "PC_CHOWN_RESTRICTED": "_PC_CHOWN_RESTRICTED",
2221 "PC_FILESIZEBITS": "_PC_FILESIZEBITS",
2222 "PC_LAST": "_PC_LAST",
2223 "PC_LINK_MAX": "_PC_LINK_MAX",
2224 "PC_MAX_CANON": "_PC_MAX_CANON",
2225 "PC_MAX_INPUT": "_PC_MAX_INPUT",
2226 "PC_NAME_MAX": "_PC_NAME_MAX",
2227 "PC_NO_TRUNC": "_PC_NO_TRUNC",
2228 "PC_PATH_MAX": "_PC_PATH_MAX",
2229 "PC_PIPE_BUF": "_PC_PIPE_BUF",
2230 "PC_PRIO_IO": "_PC_PRIO_IO",
2231 "PC_SOCK_MAXBUF": "_PC_SOCK_MAXBUF",
2232 "PC_SYNC_IO": "_PC_SYNC_IO",
2233 "PC_VDISABLE": "_PC_VDISABLE",
2234 "PC_ACL_ENABLED": "_PC_ACL_ENABLED",
2235 "PC_MIN_HOLE_SIZE": "_PC_MIN_HOLE_SIZE",
2236 "PC_ALLOC_SIZE_MIN": "_PC_ALLOC_SIZE_MIN",
2237 "PC_REC_INCR_XFER_SIZE": "_PC_REC_INCR_XFER_SIZE",
2238 "PC_REC_MAX_XFER_SIZE": "_PC_REC_MAX_XFER_SIZE",
2239 "PC_REC_MIN_XFER_SIZE": "_PC_REC_MIN_XFER_SIZE",
2240 "PC_REC_XFER_ALIGN": "_PC_REC_XFER_ALIGN",
2241 "PC_SYMLINK_MAX": "_PC_SYMLINK_MAX",
2242 "PC_XATTR_ENABLED": "_PC_XATTR_ENABLED",
2243 "PC_XATTR_EXISTS": "_PC_XATTR_EXISTS",
2244 "PC_TIMESTAMP_RESOLUTION": "_PC_TIMESTAMP_RESOLUTION",
2245 }
2246
2247 confstr_consts_defs = {
2248 "CS_ARCHITECTURE": "_CS_ARCHITECTURE",
2249 "CS_GNU_LIBC_VERSION": "_CS_GNU_LIBC_VERSION",
2250 "CS_GNU_LIBPTHREAD_VERSION": "_CS_GNU_LIBPTHREAD_VERSION",
2251 "CS_HOSTNAME": "_CS_HOSTNAME",
2252 "CS_HW_PROVIDER": "_CS_HW_PROVIDER",
2253 "CS_HW_SERIAL": "_CS_HW_SERIAL",
2254 "CS_INITTAB_NAME": "_CS_INITTAB_NAME",
2255 "CS_LFS64_CFLAGS": "_CS_LFS64_CFLAGS",
2256 "CS_LFS64_LDFLAGS": "_CS_LFS64_LDFLAGS",
2257 "CS_LFS64_LIBS": "_CS_LFS64_LIBS",
2258 "CS_LFS64_LINTFLAGS": "_CS_LFS64_LINTFLAGS",
2259 "CS_LFS_CFLAGS": "_CS_LFS_CFLAGS",
2260 "CS_LFS_LDFLAGS": "_CS_LFS_LDFLAGS",
2261 "CS_LFS_LIBS": "_CS_LFS_LIBS",
2262 "CS_LFS_LINTFLAGS": "_CS_LFS_LINTFLAGS",
2263 "CS_MACHINE": "_CS_MACHINE",
2264 "CS_PATH": "_CS_PATH",
2265 "CS_RELEASE": "_CS_RELEASE",
2266 "CS_SRPC_DOMAIN": "_CS_SRPC_DOMAIN",
2267 "CS_SYSNAME": "_CS_SYSNAME",
2268 "CS_VERSION": "_CS_VERSION",
2269 "CS_XBS5_ILP32_OFF32_CFLAGS": "_CS_XBS5_ILP32_OFF32_CFLAGS",
2270 "CS_XBS5_ILP32_OFF32_LDFLAGS": "_CS_XBS5_ILP32_OFF32_LDFLAGS",
2271 "CS_XBS5_ILP32_OFF32_LIBS": "_CS_XBS5_ILP32_OFF32_LIBS",
2272 "CS_XBS5_ILP32_OFF32_LINTFLAGS": "_CS_XBS5_ILP32_OFF32_LINTFLAGS",
2273 "CS_XBS5_ILP32_OFFBIG_CFLAGS": "_CS_XBS5_ILP32_OFFBIG_CFLAGS",
2274 "CS_XBS5_ILP32_OFFBIG_LDFLAGS": "_CS_XBS5_ILP32_OFFBIG_LDFLAGS",
2275 "CS_XBS5_ILP32_OFFBIG_LIBS": "_CS_XBS5_ILP32_OFFBIG_LIBS",
2276 "CS_XBS5_ILP32_OFFBIG_LINTFLAGS": "_CS_XBS5_ILP32_OFFBIG_LINTFLAGS",
2277 "CS_XBS5_LP64_OFF64_CFLAGS": "_CS_XBS5_LP64_OFF64_CFLAGS",
2278 "CS_XBS5_LP64_OFF64_LDFLAGS": "_CS_XBS5_LP64_OFF64_LDFLAGS",
2279 "CS_XBS5_LP64_OFF64_LIBS": "_CS_XBS5_LP64_OFF64_LIBS",
2280 "CS_XBS5_LP64_OFF64_LINTFLAGS": "_CS_XBS5_LP64_OFF64_LINTFLAGS",
2281 "CS_XBS5_LPBIG_OFFBIG_CFLAGS": "_CS_XBS5_LPBIG_OFFBIG_CFLAGS",
2282 "CS_XBS5_LPBIG_OFFBIG_LDFLAGS": "_CS_XBS5_LPBIG_OFFBIG_LDFLAGS",
2283 "CS_XBS5_LPBIG_OFFBIG_LIBS": "_CS_XBS5_LPBIG_OFFBIG_LIBS",
2284 "CS_XBS5_LPBIG_OFFBIG_LINTFLAGS": "_CS_XBS5_LPBIG_OFFBIG_LINTFLAGS",
2285 "MIPS_CS_AVAIL_PROCESSORS": "_MIPS_CS_AVAIL_PROCESSORS",
2286 "MIPS_CS_BASE": "_MIPS_CS_BASE",
2287 "MIPS_CS_HOSTID": "_MIPS_CS_HOSTID",
2288 "MIPS_CS_HW_NAME": "_MIPS_CS_HW_NAME",
2289 "MIPS_CS_NUM_PROCESSORS": "_MIPS_CS_NUM_PROCESSORS",
2290 "MIPS_CS_OSREL_MAJ": "_MIPS_CS_OSREL_MAJ",
2291 "MIPS_CS_OSREL_MIN": "_MIPS_CS_OSREL_MIN",
2292 "MIPS_CS_OSREL_PATCH": "_MIPS_CS_OSREL_PATCH",
2293 "MIPS_CS_OS_NAME": "_MIPS_CS_OS_NAME",
2294 "MIPS_CS_OS_PROVIDER": "_MIPS_CS_OS_PROVIDER",
2295 "MIPS_CS_PROCESSORS": "_MIPS_CS_PROCESSORS",
2296 "MIPS_CS_SERIAL": "_MIPS_CS_SERIAL",
2297 "MIPS_CS_VENDOR": "_MIPS_CS_VENDOR",
2298 }
2299
2300 sysconf_consts_defs = {
2301 "SC_2_CHAR_TERM": "_SC_2_CHAR_TERM",
2302 "SC_2_C_BIND": "_SC_2_C_BIND",
2303 "SC_2_C_DEV": "_SC_2_C_DEV",
2304 "SC_2_C_VERSION": "_SC_2_C_VERSION",
2305 "SC_2_FORT_DEV": "_SC_2_FORT_DEV",
2306 "SC_2_FORT_RUN": "_SC_2_FORT_RUN",
2307 "SC_2_LOCALEDEF": "_SC_2_LOCALEDEF",
2308 "SC_2_SW_DEV": "_SC_2_SW_DEV",
2309 "SC_2_UPE": "_SC_2_UPE",
2310 "SC_2_VERSION": "_SC_2_VERSION",
2311 "SC_ABI_ASYNCHRONOUS_IO": "_SC_ABI_ASYNCHRONOUS_IO",
2312 "SC_ACL": "_SC_ACL",
2313 "SC_AIO_LISTIO_MAX": "_SC_AIO_LISTIO_MAX",
2314 "SC_AIO_MAX": "_SC_AIO_MAX",
2315 "SC_AIO_PRIO_DELTA_MAX": "_SC_AIO_PRIO_DELTA_MAX",
2316 "SC_ARG_MAX": "_SC_ARG_MAX",
2317 "SC_ASYNCHRONOUS_IO": "_SC_ASYNCHRONOUS_IO",
2318 "SC_ATEXIT_MAX": "_SC_ATEXIT_MAX",
2319 "SC_AUDIT": "_SC_AUDIT",
2320 "SC_AVPHYS_PAGES": "_SC_AVPHYS_PAGES",
2321 "SC_BC_BASE_MAX": "_SC_BC_BASE_MAX",
2322 "SC_BC_DIM_MAX": "_SC_BC_DIM_MAX",
2323 "SC_BC_SCALE_MAX": "_SC_BC_SCALE_MAX",
2324 "SC_BC_STRING_MAX": "_SC_BC_STRING_MAX",
2325 "SC_CAP": "_SC_CAP",
2326 "SC_CHARCLASS_NAME_MAX": "_SC_CHARCLASS_NAME_MAX",
2327 "SC_CHAR_BIT": "_SC_CHAR_BIT",
2328 "SC_CHAR_MAX": "_SC_CHAR_MAX",
2329 "SC_CHAR_MIN": "_SC_CHAR_MIN",
2330 "SC_CHILD_MAX": "_SC_CHILD_MAX",
2331 "SC_CLK_TCK": "_SC_CLK_TCK",
2332 "SC_COHER_BLKSZ": "_SC_COHER_BLKSZ",
2333 "SC_COLL_WEIGHTS_MAX": "_SC_COLL_WEIGHTS_MAX",
2334 "SC_DCACHE_ASSOC": "_SC_DCACHE_ASSOC",
2335 "SC_DCACHE_BLKSZ": "_SC_DCACHE_BLKSZ",
2336 "SC_DCACHE_LINESZ": "_SC_DCACHE_LINESZ",
2337 "SC_DCACHE_SZ": "_SC_DCACHE_SZ",
2338 "SC_DCACHE_TBLKSZ": "_SC_DCACHE_TBLKSZ",
2339 "SC_DELAYTIMER_MAX": "_SC_DELAYTIMER_MAX",
2340 "SC_EQUIV_CLASS_MAX": "_SC_EQUIV_CLASS_MAX",
2341 "SC_EXPR_NEST_MAX": "_SC_EXPR_NEST_MAX",
2342 "SC_FSYNC": "_SC_FSYNC",
2343 "SC_GETGR_R_SIZE_MAX": "_SC_GETGR_R_SIZE_MAX",
2344 "SC_GETPW_R_SIZE_MAX": "_SC_GETPW_R_SIZE_MAX",
2345 "SC_ICACHE_ASSOC": "_SC_ICACHE_ASSOC",
2346 "SC_ICACHE_BLKSZ": "_SC_ICACHE_BLKSZ",
2347 "SC_ICACHE_LINESZ": "_SC_ICACHE_LINESZ",
2348 "SC_ICACHE_SZ": "_SC_ICACHE_SZ",
2349 "SC_INF": "_SC_INF",
2350 "SC_INT_MAX": "_SC_INT_MAX",
2351 "SC_INT_MIN": "_SC_INT_MIN",
2352 "SC_IOV_MAX": "_SC_IOV_MAX",
2353 "SC_IP_SECOPTS": "_SC_IP_SECOPTS",
2354 "SC_JOB_CONTROL": "_SC_JOB_CONTROL",
2355 "SC_KERN_POINTERS": "_SC_KERN_POINTERS",
2356 "SC_KERN_SIM": "_SC_KERN_SIM",
2357 "SC_LINE_MAX": "_SC_LINE_MAX",
2358 "SC_LOGIN_NAME_MAX": "_SC_LOGIN_NAME_MAX",
2359 "SC_LOGNAME_MAX": "_SC_LOGNAME_MAX",
2360 "SC_LONG_BIT": "_SC_LONG_BIT",
2361 "SC_MAC": "_SC_MAC",
2362 "SC_MAPPED_FILES": "_SC_MAPPED_FILES",
2363 "SC_MAXPID": "_SC_MAXPID",
2364 "SC_MB_LEN_MAX": "_SC_MB_LEN_MAX",
2365 "SC_MEMLOCK": "_SC_MEMLOCK",
2366 "SC_MEMLOCK_RANGE": "_SC_MEMLOCK_RANGE",
2367 "SC_MEMORY_PROTECTION": "_SC_MEMORY_PROTECTION",
2368 "SC_MESSAGE_PASSING": "_SC_MESSAGE_PASSING",
2369 "SC_MMAP_FIXED_ALIGNMENT": "_SC_MMAP_FIXED_ALIGNMENT",
2370 "SC_MQ_OPEN_MAX": "_SC_MQ_OPEN_MAX",
2371 "SC_MQ_PRIO_MAX": "_SC_MQ_PRIO_MAX",
2372 "SC_NACLS_MAX": "_SC_NACLS_MAX",
2373 "SC_NGROUPS_MAX": "_SC_NGROUPS_MAX",
2374 "SC_NL_ARGMAX": "_SC_NL_ARGMAX",
2375 "SC_NL_LANGMAX": "_SC_NL_LANGMAX",
2376 "SC_NL_MSGMAX": "_SC_NL_MSGMAX",
2377 "SC_NL_NMAX": "_SC_NL_NMAX",
2378 "SC_NL_SETMAX": "_SC_NL_SETMAX",
2379 "SC_NL_TEXTMAX": "_SC_NL_TEXTMAX",
2380 "SC_NPROCESSORS_CONF": "_SC_NPROCESSORS_CONF",
2381 "SC_NPROCESSORS_ONLN": "_SC_NPROCESSORS_ONLN",
2382 "SC_NPROC_CONF": "_SC_NPROC_CONF",
2383 "SC_NPROC_ONLN": "_SC_NPROC_ONLN",
2384 "SC_NZERO": "_SC_NZERO",
2385 "SC_OPEN_MAX": "_SC_OPEN_MAX",
2386 "SC_PAGESIZE": "_SC_PAGESIZE",
2387 "SC_PAGE_SIZE": "_SC_PAGE_SIZE",
2388 "SC_PASS_MAX": "_SC_PASS_MAX",
2389 "SC_PHYS_PAGES": "_SC_PHYS_PAGES",
2390 "SC_PII": "_SC_PII",
2391 "SC_PII_INTERNET": "_SC_PII_INTERNET",
2392 "SC_PII_INTERNET_DGRAM": "_SC_PII_INTERNET_DGRAM",
2393 "SC_PII_INTERNET_STREAM": "_SC_PII_INTERNET_STREAM",
2394 "SC_PII_OSI": "_SC_PII_OSI",
2395 "SC_PII_OSI_CLTS": "_SC_PII_OSI_CLTS",
2396 "SC_PII_OSI_COTS": "_SC_PII_OSI_COTS",
2397 "SC_PII_OSI_M": "_SC_PII_OSI_M",
2398 "SC_PII_SOCKET": "_SC_PII_SOCKET",
2399 "SC_PII_XTI": "_SC_PII_XTI",
2400 "SC_POLL": "_SC_POLL",
2401 "SC_PRIORITIZED_IO": "_SC_PRIORITIZED_IO",
2402 "SC_PRIORITY_SCHEDULING": "_SC_PRIORITY_SCHEDULING",
2403 "SC_REALTIME_SIGNALS": "_SC_REALTIME_SIGNALS",
2404 "SC_RE_DUP_MAX": "_SC_RE_DUP_MAX",
2405 "SC_RTSIG_MAX": "_SC_RTSIG_MAX",
2406 "SC_SAVED_IDS": "_SC_SAVED_IDS",
2407 "SC_SCHAR_MAX": "_SC_SCHAR_MAX",
2408 "SC_SCHAR_MIN": "_SC_SCHAR_MIN",
2409 "SC_SELECT": "_SC_SELECT",
2410 "SC_SEMAPHORES": "_SC_SEMAPHORES",
2411 "SC_SEM_NSEMS_MAX": "_SC_SEM_NSEMS_MAX",
2412 "SC_SEM_VALUE_MAX": "_SC_SEM_VALUE_MAX",
2413 "SC_SHARED_MEMORY_OBJECTS": "_SC_SHARED_MEMORY_OBJECTS",
2414 "SC_SHRT_MAX": "_SC_SHRT_MAX",
2415 "SC_SHRT_MIN": "_SC_SHRT_MIN",
2416 "SC_SIGQUEUE_MAX": "_SC_SIGQUEUE_MAX",
2417 "SC_SIGRT_MAX": "_SC_SIGRT_MAX",
2418 "SC_SIGRT_MIN": "_SC_SIGRT_MIN",
2419 "SC_SOFTPOWER": "_SC_SOFTPOWER",
2420 "SC_SPLIT_CACHE": "_SC_SPLIT_CACHE",
2421 "SC_SSIZE_MAX": "_SC_SSIZE_MAX",
2422 "SC_STACK_PROT": "_SC_STACK_PROT",
2423 "SC_STREAM_MAX": "_SC_STREAM_MAX",
2424 "SC_SYNCHRONIZED_IO": "_SC_SYNCHRONIZED_IO",
2425 "SC_THREADS": "_SC_THREADS",
2426 "SC_THREAD_ATTR_STACKADDR": "_SC_THREAD_ATTR_STACKADDR",
2427 "SC_THREAD_ATTR_STACKSIZE": "_SC_THREAD_ATTR_STACKSIZE",
2428 "SC_THREAD_DESTRUCTOR_ITERATIONS": "_SC_THREAD_DESTRUCTOR_ITERATIONS",
2429 "SC_THREAD_KEYS_MAX": "_SC_THREAD_KEYS_MAX",
2430 "SC_THREAD_PRIORITY_SCHEDULING": "_SC_THREAD_PRIORITY_SCHEDULING",
2431 "SC_THREAD_PRIO_INHERIT": "_SC_THREAD_PRIO_INHERIT",
2432 "SC_THREAD_PRIO_PROTECT": "_SC_THREAD_PRIO_PROTECT",
2433 "SC_THREAD_PROCESS_SHARED": "_SC_THREAD_PROCESS_SHARED",
2434 "SC_THREAD_SAFE_FUNCTIONS": "_SC_THREAD_SAFE_FUNCTIONS",
2435 "SC_THREAD_STACK_MIN": "_SC_THREAD_STACK_MIN",
2436 "SC_THREAD_THREADS_MAX": "_SC_THREAD_THREADS_MAX",
2437 "SC_TIMERS": "_SC_TIMERS",
2438 "SC_TIMER_MAX": "_SC_TIMER_MAX",
2439 "SC_TTY_NAME_MAX": "_SC_TTY_NAME_MAX",
2440 "SC_TZNAME_MAX": "_SC_TZNAME_MAX",
2441 "SC_T_IOV_MAX": "_SC_T_IOV_MAX",
2442 "SC_UCHAR_MAX": "_SC_UCHAR_MAX",
2443 "SC_UINT_MAX": "_SC_UINT_MAX",
2444 "SC_UIO_MAXIOV": "_SC_UIO_MAXIOV",
2445 "SC_ULONG_MAX": "_SC_ULONG_MAX",
2446 "SC_USHRT_MAX": "_SC_USHRT_MAX",
2447 "SC_VERSION": "_SC_VERSION",
2448 "SC_WORD_BIT": "_SC_WORD_BIT",
2449 "SC_XBS5_ILP32_OFF32": "_SC_XBS5_ILP32_OFF32",
2450 "SC_XBS5_ILP32_OFFBIG": "_SC_XBS5_ILP32_OFFBIG",
2451 "SC_XBS5_LP64_OFF64": "_SC_XBS5_LP64_OFF64",
2452 "SC_XBS5_LPBIG_OFFBIG": "_SC_XBS5_LPBIG_OFFBIG",
2453 "SC_XOPEN_CRYPT": "_SC_XOPEN_CRYPT",
2454 "SC_XOPEN_ENH_I18N": "_SC_XOPEN_ENH_I18N",
2455 "SC_XOPEN_LEGACY": "_SC_XOPEN_LEGACY",
2456 "SC_XOPEN_REALTIME": "_SC_XOPEN_REALTIME",
2457 "SC_XOPEN_REALTIME_THREADS": "_SC_XOPEN_REALTIME_THREADS",
2458 "SC_XOPEN_SHM": "_SC_XOPEN_SHM",
2459 "SC_XOPEN_UNIX": "_SC_XOPEN_UNIX",
2460 "SC_XOPEN_VERSION": "_SC_XOPEN_VERSION",
2461 "SC_XOPEN_XCU_VERSION": "_SC_XOPEN_XCU_VERSION",
2462 "SC_XOPEN_XPG2": "_SC_XOPEN_XPG2",
2463 "SC_XOPEN_XPG3": "_SC_XOPEN_XPG3",
2464 "SC_XOPEN_XPG4": "_SC_XOPEN_XPG4",
2465 }
2466 for k,v in pathconf_consts_defs.items():
2467 setattr(ConfConfig, k, rffi_platform.DefinedConstantInteger(v))
2468 for k,v in confstr_consts_defs.items():
2469 setattr(ConfConfig, k, rffi_platform.DefinedConstantInteger(v))
2470 for k,v in sysconf_consts_defs.items():
2471 setattr(ConfConfig, k, rffi_platform.DefinedConstantInteger(v))
2472
2473 confConfig = rffi_platform.configure(ConfConfig)
2474 pathconf_names = {}
2475 confstr_names = {}
2476 sysconf_names = {}
2477 for k in pathconf_consts_defs:
2478 v = confConfig.get(k, None)
2479 if v is not None:
2480 pathconf_names[k] = v
2481 for k in confstr_consts_defs:
2482 v = confConfig.get(k, None)
2483 if v is not None:
2484 confstr_names[k] = v
2485 for k in sysconf_consts_defs:
2486 v = confConfig.get(k, None)
2487 if v is not None:
2488 sysconf_names[k] = v
2489
2490
2491
2492 if HAVE_SCHED_GETPARAM:
2493 class CConfig:
2494 _compilation_info_ = ExternalCompilationInfo(
2495 includes=['sys/stat.h',
2496 'unistd.h',
2497 'sched.h',
2498 ],
2499 )
2500 SCHED_PARAM = rffi_platform.Struct('struct sched_param', [
2501 ('sched_priority', rffi.INT)])
2502
2503 cConfig = rffi_platform.configure(CConfig)
2504 globals().update(cConfig)
2505
2506 SCHED_PARAM2P = rffi.CArrayPtr(SCHED_PARAM)
2507
2508 c_sched_rr_get_interval = external('sched_rr_get_interval',
2509 [rffi.PID_T, TIMESPEC2P],
2510 rffi.INT, save_err=rffi.RFFI_FULL_ERRNO_ZERO)
2511 c_sched_getscheduler = external('sched_getscheduler', [rffi.PID_T],
2512 rffi.INT, save_err=rffi.RFFI_FULL_ERRNO_ZERO)
2513 c_sched_setscheduler = external('sched_setscheduler',
2514 [rffi.PID_T, rffi.INT, SCHED_PARAM2P],
2515 rffi.INT, save_err=rffi.RFFI_FULL_ERRNO_ZERO)
2516 c_sched_getparam = external('sched_getparam', [rffi.PID_T, SCHED_PARAM2P],
2517 rffi.INT, save_err=rffi.RFFI_FULL_ERRNO_ZERO)
2518 c_sched_setparam = external('sched_setparam', [rffi.PID_T, SCHED_PARAM2P],
2519 rffi.INT, save_err=rffi.RFFI_FULL_ERRNO_ZERO)
2520
2521 def sched_rr_get_interval(pid):
2522 with lltype.scoped_alloc(TIMESPEC2P.TO, 1) as interval:
2523 handle_posix_error('sched_rr_get_interval', c_sched_rr_get_interval(pid, interval))
2524 return interval[0].c_tv_sec + 1e-9 * interval[0].c_tv_nsec
2525
2526 def sched_getscheduler(pid):
2527 return handle_posix_error('sched_getscheduler', c_sched_getscheduler(pid))
2528
2529 def sched_setscheduler(pid, policy, priority):
2530 with lltype.scoped_alloc(SCHED_PARAM2P.TO, 1) as param:
2531 param[0].c_sched_priority = rffi.cast(rffi.INT, priority)
2532 return handle_posix_error('sched_setscheduler', c_sched_setscheduler(pid, policy, param))
2533
2534
2535 def sched_getparam(pid):
2536 with lltype.scoped_alloc(SCHED_PARAM2P.TO, 1) as param:
2537 handle_posix_error('sched_getparam', c_sched_getparam(pid, param))
2538 return param[0].c_sched_priority
2539
2540 def sched_setparam(pid, priority):
2541 with lltype.scoped_alloc(SCHED_PARAM2P.TO, 1) as param:
2542 param[0].c_sched_priority = rffi.cast(rffi.INT, priority)
2543 return handle_posix_error('sched_setparam', c_sched_setparam(pid, param))
2544
2545
2546 if HAVE_FACCESSAT:
2547 c_faccessat = external('faccessat',
2548 [rffi.INT, rffi.CCHARP, rffi.INT, rffi.INT], rffi.INT)
2549
2550 def faccessat(pathname, mode, dir_fd=AT_FDCWD,
2551 effective_ids=False, follow_symlinks=True):
2552 """Thin wrapper around faccessat(2) with an interface simlar to
2553 Python3's os.access().
2554 """
2555 flags = 0
2556 if not follow_symlinks:
2557 flags |= AT_SYMLINK_NOFOLLOW
2558 if effective_ids:
2559 flags |= AT_EACCESS
2560 error = c_faccessat(dir_fd, pathname, mode, flags)
2561 return error == 0
2562
2563 if HAVE_FCHMODAT:
2564 c_fchmodat = external('fchmodat',
2565 [rffi.INT, rffi.CCHARP, rffi.INT, rffi.INT], rffi.INT,
2566 save_err=rffi.RFFI_SAVE_ERRNO,)
2567
2568 def fchmodat(path, mode, dir_fd=AT_FDCWD, follow_symlinks=True):
2569 if follow_symlinks:
2570 flag = 0
2571 else:
2572 flag = AT_SYMLINK_NOFOLLOW
2573 error = c_fchmodat(dir_fd, path, mode, flag)
2574 handle_posix_error('fchmodat', error)
2575
2576 if HAVE_FCHOWNAT:
2577 c_fchownat = external('fchownat',
2578 [rffi.INT, rffi.CCHARP, rffi.INT, rffi.INT, rffi.INT], rffi.INT,
2579 save_err=rffi.RFFI_SAVE_ERRNO,)
2580
2581 def fchownat(path, owner, group, dir_fd=AT_FDCWD,
2582 follow_symlinks=True, empty_path=False):
2583 flag = 0
2584 if not follow_symlinks:
2585 flag |= AT_SYMLINK_NOFOLLOW
2586 if empty_path:
2587 flag |= AT_EMPTY_PATH
2588 error = c_fchownat(dir_fd, path, owner, group, flag)
2589 handle_posix_error('fchownat', error)
2590
2591 if HAVE_FEXECVE:
2592 c_fexecve = external('fexecve',
2593 [rffi.INT, rffi.CCHARPP, rffi.CCHARPP], rffi.INT,
2594 save_err=rffi.RFFI_SAVE_ERRNO)
2595
2596 def fexecve(fd, args, env):
2597 envstrs = []
2598 for item in env.iteritems():
2599 envstr = "%s=%s" % item
2600 envstrs.append(envstr)
2601
2602 # This list conversion already takes care of NUL bytes.
2603 l_args = rffi.ll_liststr2charpp(args)
2604 l_env = rffi.ll_liststr2charpp(envstrs)
2605 c_fexecve(fd, l_args, l_env)
2606
2607 rffi.free_charpp(l_env)
2608 rffi.free_charpp(l_args)
2609 raise OSError(get_saved_errno(), "execve failed")
2610
2611 if HAVE_LINKAT:
2612 c_linkat = external(
2613 'linkat',
2614 [rffi.INT, rffi.CCHARP, rffi.INT, rffi.CCHARP, rffi.INT], rffi.INT,
2615 save_err=rffi.RFFI_SAVE_ERRNO)
2616
2617 def linkat(src, dst, src_dir_fd=AT_FDCWD, dst_dir_fd=AT_FDCWD,
2618 follow_symlinks=True):
2619 """Thin wrapper around linkat(2) with an interface similar to
2620 Python3's os.link()
2621 """
2622 if follow_symlinks:
2623 flag = 0
2624 else:
2625 flag = AT_SYMLINK_NOFOLLOW
2626 error = c_linkat(src_dir_fd, src, dst_dir_fd, dst, flag)
2627 handle_posix_error('linkat', error)
2628
2629 if HAVE_FUTIMENS:
2630 c_futimens = external('futimens', [rffi.INT, TIMESPEC2P], rffi.INT,
2631 save_err=rffi.RFFI_SAVE_ERRNO)
2632
2633 def futimens(fd, atime, atime_ns, mtime, mtime_ns):
2634 l_times = lltype.malloc(TIMESPEC2P.TO, 2, flavor='raw')
2635 rffi.setintfield(l_times[0], 'c_tv_sec', atime)
2636 rffi.setintfield(l_times[0], 'c_tv_nsec', atime_ns)
2637 rffi.setintfield(l_times[1], 'c_tv_sec', mtime)
2638 rffi.setintfield(l_times[1], 'c_tv_nsec', mtime_ns)
2639 error = c_futimens(fd, l_times)
2640 lltype.free(l_times, flavor='raw')
2641 handle_posix_error('futimens', error)
2642
2643 if HAVE_UTIMENSAT:
2644 c_utimensat = external(
2645 'utimensat',
2646 [rffi.INT, rffi.CCHARP, TIMESPEC2P, rffi.INT], rffi.INT,
2647 save_err=rffi.RFFI_SAVE_ERRNO)
2648
2649 def utimensat(pathname, atime, atime_ns, mtime, mtime_ns,
2650 dir_fd=AT_FDCWD, follow_symlinks=True):
2651 """Wrapper around utimensat(2)
2652
2653 To set access time to the current time, pass atime_ns=UTIME_NOW,
2654 atime is then ignored.
2655
2656 To set modification time to the current time, pass mtime_ns=UTIME_NOW,
2657 mtime is then ignored.
2658 """
2659 l_times = lltype.malloc(TIMESPEC2P.TO, 2, flavor='raw')
2660 rffi.setintfield(l_times[0], 'c_tv_sec', atime)
2661 rffi.setintfield(l_times[0], 'c_tv_nsec', atime_ns)
2662 rffi.setintfield(l_times[1], 'c_tv_sec', mtime)
2663 rffi.setintfield(l_times[1], 'c_tv_nsec', mtime_ns)
2664 if follow_symlinks:
2665 flag = 0
2666 else:
2667 flag = AT_SYMLINK_NOFOLLOW
2668 error = c_utimensat(dir_fd, pathname, l_times, flag)
2669 lltype.free(l_times, flavor='raw')
2670 handle_posix_error('utimensat', error)
2671
2672 if HAVE_LUTIMES:
2673 c_lutimes = external('lutimes',
2674 [rffi.CCHARP, TIMEVAL2P], rffi.INT,
2675 save_err=rffi.RFFI_SAVE_ERRNO)
2676
2677 @specialize.argtype(1)
2678 def lutimes(pathname, times):
2679 if times is None:
2680 error = c_lutimes(pathname, lltype.nullptr(TIMEVAL2P.TO))
2681 else:
2682 with lltype.scoped_alloc(TIMEVAL2P.TO, 2) as l_timeval2p:
2683 times_to_timeval2p(times, l_timeval2p)
2684 error = c_lutimes(pathname, l_timeval2p)
2685 handle_posix_error('lutimes', error)
2686
2687 if HAVE_FUTIMES:
2688 c_futimes = external('futimes',
2689 [rffi.INT, TIMEVAL2P], rffi.INT,
2690 save_err=rffi.RFFI_SAVE_ERRNO)
2691
2692 @specialize.argtype(1)
2693 def futimes(fd, times):
2694 if times is None:
2695 error = c_futimes(fd, lltype.nullptr(TIMEVAL2P.TO))
2696 else:
2697 with lltype.scoped_alloc(TIMEVAL2P.TO, 2) as l_timeval2p:
2698 times_to_timeval2p(times, l_timeval2p)
2699 error = c_futimes(fd, l_timeval2p)
2700 handle_posix_error('futimes', error)
2701
2702 if HAVE_MKDIRAT:
2703 c_mkdirat = external('mkdirat',
2704 [rffi.INT, rffi.CCHARP, rffi.INT], rffi.INT,
2705 save_err=rffi.RFFI_SAVE_ERRNO)
2706
2707 def mkdirat(pathname, mode, dir_fd=AT_FDCWD):
2708 error = c_mkdirat(dir_fd, pathname, mode)
2709 handle_posix_error('mkdirat', error)
2710
2711 if HAVE_UNLINKAT:
2712 c_unlinkat = external('unlinkat',
2713 [rffi.INT, rffi.CCHARP, rffi.INT], rffi.INT,
2714 save_err=rffi.RFFI_SAVE_ERRNO)
2715
2716 def unlinkat(pathname, dir_fd=AT_FDCWD, removedir=False):
2717 flag = AT_REMOVEDIR if removedir else 0
2718 error = c_unlinkat(dir_fd, pathname, flag)
2719 handle_posix_error('unlinkat', error)
2720
2721 if HAVE_READLINKAT:
2722 c_readlinkat = external(
2723 'readlinkat',
2724 [rffi.INT, rffi.CCHARP, rffi.CCHARP, rffi.SIZE_T], rffi.SSIZE_T,
2725 save_err=rffi.RFFI_SAVE_ERRNO)
2726
2727 def readlinkat(pathname, dir_fd=AT_FDCWD):
2728 pathname = _as_bytes0(pathname)
2729 bufsize = 1023
2730 while True:
2731 buf = lltype.malloc(rffi.CCHARP.TO, bufsize, flavor='raw')
2732 res = widen(c_readlinkat(dir_fd, pathname, buf, bufsize))
2733 if res < 0:
2734 lltype.free(buf, flavor='raw')
2735 error = get_saved_errno() # failed
2736 raise OSError(error, "readlinkat failed")
2737 elif res < bufsize:
2738 break # ok
2739 else:
2740 # buf too small, try again with a larger buffer
2741 lltype.free(buf, flavor='raw')
2742 bufsize *= 4
2743 # convert the result to a string
2744 result = rffi.charp2strn(buf, res)
2745 lltype.free(buf, flavor='raw')
2746 return result
2747
2748 if HAVE_RENAMEAT:
2749 c_renameat = external(
2750 'renameat',
2751 [rffi.INT, rffi.CCHARP, rffi.INT, rffi.CCHARP], rffi.INT,
2752 save_err=rffi.RFFI_SAVE_ERRNO)
2753
2754 def renameat(src, dst, src_dir_fd=AT_FDCWD, dst_dir_fd=AT_FDCWD):
2755 error = c_renameat(src_dir_fd, src, dst_dir_fd, dst)
2756 handle_posix_error('renameat', error)
2757
2758
2759 if HAVE_SYMLINKAT:
2760 c_symlinkat = external('symlinkat',
2761 [rffi.CCHARP, rffi.INT, rffi.CCHARP], rffi.INT,
2762 save_err=rffi.RFFI_SAVE_ERRNO)
2763
2764 def symlinkat(src, dst, dir_fd=AT_FDCWD):
2765 error = c_symlinkat(src, dir_fd, dst)
2766 handle_posix_error('symlinkat', error)
2767
2768 if HAVE_OPENAT:
2769 c_openat = external('openat',
2770 [rffi.INT, rffi.CCHARP, rffi.INT, rffi.MODE_T], rffi.INT,
2771 save_err=rffi.RFFI_SAVE_ERRNO)
2772
2773 @enforceargs(s_Str0, int, int, int, typecheck=False)
2774 def openat(path, flags, mode, dir_fd=AT_FDCWD):
2775 fd = c_openat(dir_fd, path, flags, mode)
2776 return handle_posix_error('open', fd)
2777
2778 if HAVE_MKFIFOAT:
2779 c_mkfifoat = external('mkfifoat',
2780 [rffi.INT, rffi.CCHARP, rffi.MODE_T], rffi.INT,
2781 save_err=rffi.RFFI_SAVE_ERRNO)
2782
2783 def mkfifoat(path, mode, dir_fd=AT_FDCWD):
2784 error = c_mkfifoat(dir_fd, path, mode)
2785 handle_posix_error('mkfifoat', error)
2786
2787 if HAVE_MKNODAT:
2788 c_mknodat = external('mknodat',
2789 [rffi.INT, rffi.CCHARP, rffi.MODE_T, rffi.INT], rffi.INT,
2790 save_err=rffi.RFFI_SAVE_ERRNO)
2791
2792 def mknodat(path, mode, device, dir_fd=AT_FDCWD):
2793 error = c_mknodat(dir_fd, path, mode, device)
2794 handle_posix_error('mknodat', error)
2795
2796
2797 if not _WIN32:
2798 eci_inheritable = eci.merge(ExternalCompilationInfo(
2799 separate_module_sources=[r"""
2800 #include <errno.h>
2801 #include <sys/ioctl.h>
2802
2803 RPY_EXTERN
2804 int rpy_set_inheritable(int fd, int inheritable)
2805 {
2806 static int ioctl_works = -1;
2807 int flags;
2808
2809 if (ioctl_works != 0) {
2810 int request = inheritable ? FIONCLEX : FIOCLEX;
2811 int err = ioctl(fd, request, NULL);
2812 if (!err) {
2813 ioctl_works = 1;
2814 return 0;
2815 }
2816
2817 if (errno != ENOTTY && errno != EACCES) {
2818 return -1;
2819 }
2820 else {
2821 /* ENOTTY: The ioctl is declared but not supported by the
2822 kernel. EACCES: SELinux policy, this can be the case on
2823 Android. */
2824 ioctl_works = 0;
2825 }
2826 /* fallback to fcntl() if ioctl() does not work */
2827 }
2828
2829 flags = fcntl(fd, F_GETFD);
2830 if (flags < 0)
2831 return -1;
2832
2833 if (inheritable)
2834 flags &= ~FD_CLOEXEC;
2835 else
2836 flags |= FD_CLOEXEC;
2837 return fcntl(fd, F_SETFD, flags);
2838 }
2839
2840 RPY_EXTERN
2841 int rpy_get_inheritable(int fd)
2842 {
2843 int flags = fcntl(fd, F_GETFD, 0);
2844 if (flags == -1)
2845 return -1;
2846 return !(flags & FD_CLOEXEC);
2847 }
2848
2849 RPY_EXTERN
2850 int rpy_dup_noninheritable(int fd)
2851 {
2852 #ifdef F_DUPFD_CLOEXEC
2853 return fcntl(fd, F_DUPFD_CLOEXEC, 0);
2854 #else
2855 fd = dup(fd);
2856 if (fd >= 0) {
2857 if (rpy_set_inheritable(fd, 0) != 0) {
2858 close(fd);
2859 return -1;
2860 }
2861 }
2862 return fd;
2863 #endif
2864 }
2865
2866 RPY_EXTERN
2867 int rpy_dup2_noninheritable(int fd, int fd2)
2868 {
2869 #ifdef F_DUP2FD_CLOEXEC
2870 return fcntl(fd, F_DUP2FD_CLOEXEC, fd2);
2871
2872 #else
2873 # if %(HAVE_DUP3)d /* HAVE_DUP3 */
2874 static int dup3_works = -1;
2875 if (dup3_works != 0) {
2876 if (dup3(fd, fd2, O_CLOEXEC) >= 0)
2877 return 0;
2878 if (dup3_works == -1)
2879 dup3_works = (errno != ENOSYS);
2880 if (dup3_works)
2881 return -1;
2882 }
2883 # endif
2884 if (dup2(fd, fd2) < 0)
2885 return -1;
2886 if (rpy_set_inheritable(fd2, 0) != 0) {
2887 close(fd2);
2888 return -1;
2889 }
2890 return 0;
2891 #endif
2892 }
2893 """ % {'HAVE_DUP3': HAVE_DUP3}],
2894 post_include_bits=['RPY_EXTERN int rpy_set_inheritable(int, int);\n'
2895 'RPY_EXTERN int rpy_get_inheritable(int);\n'
2896 'RPY_EXTERN int rpy_dup_noninheritable(int);\n'
2897 'RPY_EXTERN int rpy_dup2_noninheritable(int, int);\n'
2898 ]))
2899
2900 _c_set_inheritable = external('rpy_set_inheritable', [rffi.INT, rffi.INT],
2901 rffi.INT, save_err=rffi.RFFI_SAVE_ERRNO,
2902 compilation_info=eci_inheritable)
2903 _c_get_inheritable = external('rpy_get_inheritable', [rffi.INT],
2904 rffi.INT, save_err=rffi.RFFI_SAVE_ERRNO,
2905 compilation_info=eci_inheritable)
2906 c_dup_noninheritable = external('rpy_dup_noninheritable', [rffi.INT],
2907 rffi.INT, save_err=rffi.RFFI_SAVE_ERRNO,
2908 compilation_info=eci_inheritable)
2909 c_dup2_noninheritable = external('rpy_dup2_noninheritable', [rffi.INT,rffi.INT],
2910 rffi.INT, save_err=rffi.RFFI_SAVE_ERRNO,
2911 compilation_info=eci_inheritable)
2912
2913 def set_inheritable(fd, inheritable):
2914 result = _c_set_inheritable(fd, inheritable)
2915 handle_posix_error('set_inheritable', result)
2916
2917 def get_inheritable(fd):
2918 res = _c_get_inheritable(fd)
2919 res = handle_posix_error('get_inheritable', res)
2920 return res != 0
2921
2922 else:
2923 # _WIN32
2924 from rpython.rlib.rwin32 import set_inheritable, get_inheritable
2925 from rpython.rlib.rwin32 import c_dup_noninheritable
2926 from rpython.rlib.rwin32 import c_dup2_noninheritable
2927
2928
2929 class SetNonInheritableCache(object):
2930 """Make one prebuilt instance of this for each path that creates
2931 file descriptors, where you don't necessarily know if that function
2932 returns inheritable or non-inheritable file descriptors.
2933 """
2934 _immutable_fields_ = ['cached_inheritable?']
2935 cached_inheritable = -1 # -1 = don't know yet; 0 = off; 1 = on
2936
2937 def set_non_inheritable(self, fd):
2938 if self.cached_inheritable == -1:
2939 self.cached_inheritable = get_inheritable(fd)
2940 if self.cached_inheritable == 1:
2941 # 'fd' is inheritable; we must manually turn it off
2942 set_inheritable(fd, False)
2943
2944 def _cleanup_(self):
2945 self.cached_inheritable = -1
2946
2947 class ENoSysCache(object):
2948 """Cache whether a system call returns ENOSYS or not."""
2949 _immutable_fields_ = ['cached_nosys?']
2950 cached_nosys = -1 # -1 = don't know; 0 = no; 1 = yes, getting ENOSYS
2951
2952 def attempt_syscall(self):
2953 return self.cached_nosys != 1
2954
2955 def fallback(self, res):
2956 nosys = self.cached_nosys
2957 if nosys == -1:
2958 nosys = (widen(res) < 0 and get_saved_errno() == errno.ENOSYS)
2959 self.cached_nosys = nosys
2960 return nosys
2961
2962 def _cleanup_(self):
2963 self.cached_nosys = -1
2964
2965 _pipe2_syscall = ENoSysCache()
2966
2967 post_include_bits=['RPY_EXTERN int rpy_cpu_count(void);']
2968 # cpu count for linux, windows and mac (+ bsds)
2969 # note that the code is copied from cpython and split up here
2970 if sys.platform.startswith(('linux', 'gnu')):
2971 cpucount_eci = ExternalCompilationInfo(includes=["unistd.h"],
2972 separate_module_sources=["""
2973 RPY_EXTERN int rpy_cpu_count(void) {
2974 return sysconf(_SC_NPROCESSORS_ONLN);
2975 }
2976 """], post_include_bits=post_include_bits)
2977 elif sys.platform == "win32":
2978 cpucount_eci = ExternalCompilationInfo(includes=["Windows.h"],
2979 separate_module_sources=["""
2980 RPY_EXTERN int rpy_cpu_count(void) {
2981 SYSTEM_INFO sysinfo;
2982 GetSystemInfo(&sysinfo);
2983 return sysinfo.dwNumberOfProcessors;
2984 }
2985 """], post_include_bits=post_include_bits)
2986 else:
2987 cpucount_eci = ExternalCompilationInfo(includes=["sys/types.h", "sys/sysctl.h"],
2988 separate_module_sources=["""
2989 RPY_EXTERN int rpy_cpu_count(void) {
2990 int ncpu = 0;
2991 #if defined(__DragonFly__) || \
2992 defined(__OpenBSD__) || \
2993 defined(__FreeBSD__) || \
2994 defined(__NetBSD__) || \
2995 defined(__APPLE__)
2996 int mib[2];
2997 size_t len = sizeof(ncpu);
2998 mib[0] = CTL_HW;
2999 mib[1] = HW_NCPU;
3000 if (sysctl(mib, 2, &ncpu, &len, NULL, 0) != 0)
3001 ncpu = 0;
3002 #endif
3003 return ncpu;
3004 }
3005 """], post_include_bits=post_include_bits)
3006
3007 _cpu_count = rffi.llexternal('rpy_cpu_count', [], rffi.INT_real,
3008 compilation_info=cpucount_eci)
3009
3010 def cpu_count():
3011 return rffi.cast(lltype.Signed, _cpu_count())
3012
3013 if not _WIN32:
3014 eci_status_flags = eci.merge(ExternalCompilationInfo(separate_module_sources=["""
3015 RPY_EXTERN
3016 int rpy_get_status_flags(int fd)
3017 {
3018 int flags;
3019 flags = fcntl(fd, F_GETFL, 0);
3020 return flags;
3021 }
3022
3023 RPY_EXTERN
3024 int rpy_set_status_flags(int fd, int flags)
3025 {
3026 int res;
3027 res = fcntl(fd, F_SETFL, flags);
3028 return res;
3029 }
3030 """], post_include_bits=[
3031 "RPY_EXTERN int rpy_get_status_flags(int);\n"
3032 "RPY_EXTERN int rpy_set_status_flags(int, int);"]
3033 ))
3034
3035
3036 c_get_status_flags = external('rpy_get_status_flags', [rffi.INT],
3037 rffi.INT, save_err=rffi.RFFI_SAVE_ERRNO,
3038 compilation_info=eci_status_flags)
3039 c_set_status_flags = external('rpy_set_status_flags', [rffi.INT, rffi.INT],
3040 rffi.INT, save_err=rffi.RFFI_SAVE_ERRNO,
3041 compilation_info=eci_status_flags)
3042
3043 def get_status_flags(fd):
3044 res = c_get_status_flags(fd)
3045 res = handle_posix_error('get_status_flags', res)
3046 return res
3047
3048 def set_status_flags(fd, flags):
3049 res = c_set_status_flags(fd, flags)
3050 handle_posix_error('set_status_flags', res)
3051
3052 if sys.platform.startswith('linux'):
3053 sendfile_eci = ExternalCompilationInfo(includes=["sys/sendfile.h"])
3054 _OFF_PTR_T = rffi.CArrayPtr(OFF_T)
3055 c_sendfile = rffi.llexternal('sendfile',
3056 [rffi.INT, rffi.INT, _OFF_PTR_T, rffi.SIZE_T],
3057 rffi.SSIZE_T, save_err=rffi.RFFI_SAVE_ERRNO,
3058 compilation_info=sendfile_eci)
3059
3060 def sendfile(out_fd, in_fd, offset, count):
3061 with lltype.scoped_alloc(_OFF_PTR_T.TO, 1) as p_offset:
3062 p_offset[0] = rffi.cast(OFF_T, offset)
3063 res = c_sendfile(out_fd, in_fd, p_offset, count)
3064 return handle_posix_error('sendfile', res)
3065
3066 def sendfile_no_offset(out_fd, in_fd, count):
3067 """Passes offset==NULL; not support on all OSes"""
3068 res = c_sendfile(out_fd, in_fd, lltype.nullptr(_OFF_PTR_T.TO), count)
3069 return handle_posix_error('sendfile', res)
3070
3071 elif not _WIN32:
3072 # Neither on Windows nor on Linux, so probably a BSD derivative of
3073 # some sort. Please note that the implementation below is partial;
3074 # the VOIDP is an iovec for sending headers and trailers which
3075 # CPython uses for the headers and trailers argument, and it also
3076 # has a flags argument. None of these are currently supported.
3077 sendfile_eci = ExternalCompilationInfo(includes=["sys/socket.h"])
3078 _OFF_PTR_T = rffi.CArrayPtr(OFF_T)
3079 # NB: the VOIDP is an struct sf_hdtr for sending headers and trailers
3080 c_sendfile = rffi.llexternal('sendfile',
3081 [rffi.INT, rffi.INT, OFF_T, _OFF_PTR_T, rffi.VOIDP, rffi.INT],
3082 rffi.SSIZE_T, save_err=rffi.RFFI_SAVE_ERRNO,
3083 compilation_info=sendfile_eci)
3084
3085 def sendfile(out_fd, in_fd, offset, count):
3086 with lltype.scoped_alloc(_OFF_PTR_T.TO, 1) as p_len:
3087 p_len[0] = rffi.cast(OFF_T, count)
3088 res = c_sendfile(in_fd, out_fd, offset, p_len, lltype.nullptr(rffi.VOIDP.TO), 0)
3089 sbytes = p_len[0]
3090 if res != 0:
3091 if get_saved_errno() in (errno.EAGAIN, errno.EBUSY) and sbytes != 0:
3092 return sbytes
3093 return handle_posix_error('sendfile', res)
3094 return sbytes
3095
3096 # ____________________________________________________________
3097 # Support for *xattr functions
3098
3099 if sys.platform.startswith('linux'):
3100
3101 class CConfig:
3102 _compilation_info_ = ExternalCompilationInfo(
3103 includes=['sys/xattr.h', 'linux/limits.h'],)
3104 XATTR_SIZE_MAX = rffi_platform.DefinedConstantInteger('XATTR_SIZE_MAX')
3105 XATTR_CREATE = rffi_platform.DefinedConstantInteger('XATTR_CREATE')
3106 XATTR_REPLACE = rffi_platform.DefinedConstantInteger('XATTR_REPLACE')
3107
3108 cConfig = rffi_platform.configure(CConfig)
3109 globals().update(cConfig)
3110 c_fgetxattr = external('fgetxattr',
3111 [rffi.INT, rffi.CCHARP, rffi.VOIDP, rffi.SIZE_T], rffi.SSIZE_T,
3112 compilation_info=CConfig._compilation_info_,
3113 save_err=rffi.RFFI_SAVE_ERRNO)
3114 c_getxattr = external('getxattr',
3115 [rffi.CCHARP, rffi.CCHARP, rffi.VOIDP, rffi.SIZE_T], rffi.SSIZE_T,
3116 compilation_info=CConfig._compilation_info_,
3117 save_err=rffi.RFFI_SAVE_ERRNO)
3118 c_lgetxattr = external('lgetxattr',
3119 [rffi.CCHARP, rffi.CCHARP, rffi.VOIDP, rffi.SIZE_T], rffi.SSIZE_T,
3120 compilation_info=CConfig._compilation_info_,
3121 save_err=rffi.RFFI_SAVE_ERRNO)
3122 c_fsetxattr = external('fsetxattr',
3123 [rffi.INT, rffi.CCHARP, rffi.CCHARP, rffi.SIZE_T, rffi.INT],
3124 rffi.INT,
3125 compilation_info=CConfig._compilation_info_,
3126 save_err=rffi.RFFI_SAVE_ERRNO)
3127 c_setxattr = external('setxattr',
3128 [rffi.CCHARP, rffi.CCHARP, rffi.CCHARP, rffi.SIZE_T, rffi.INT],
3129 rffi.INT,
3130 compilation_info=CConfig._compilation_info_,
3131 save_err=rffi.RFFI_SAVE_ERRNO)
3132 c_lsetxattr = external('lsetxattr',
3133 [rffi.CCHARP, rffi.CCHARP, rffi.CCHARP, rffi.SIZE_T, rffi.INT],
3134 rffi.INT,
3135 compilation_info=CConfig._compilation_info_,
3136 save_err=rffi.RFFI_SAVE_ERRNO)
3137 c_fremovexattr = external('fremovexattr',
3138 [rffi.INT, rffi.CCHARP], rffi.INT,
3139 compilation_info=CConfig._compilation_info_,
3140 save_err=rffi.RFFI_SAVE_ERRNO)
3141 c_removexattr = external('removexattr',
3142 [rffi.CCHARP, rffi.CCHARP], rffi.INT,
3143 compilation_info=CConfig._compilation_info_,
3144 save_err=rffi.RFFI_SAVE_ERRNO)
3145 c_lremovexattr = external('lremovexattr',
3146 [rffi.CCHARP, rffi.CCHARP], rffi.INT,
3147 compilation_info=CConfig._compilation_info_,
3148 save_err=rffi.RFFI_SAVE_ERRNO)
3149 c_flistxattr = external('flistxattr',
3150 [rffi.INT, rffi.CCHARP, rffi.SIZE_T], rffi.SSIZE_T,
3151 compilation_info=CConfig._compilation_info_,
3152 save_err=rffi.RFFI_SAVE_ERRNO)
3153 c_listxattr = external('listxattr',
3154 [rffi.CCHARP, rffi.CCHARP, rffi.SIZE_T], rffi.SSIZE_T,
3155 compilation_info=CConfig._compilation_info_,
3156 save_err=rffi.RFFI_SAVE_ERRNO)
3157 c_llistxattr = external('llistxattr',
3158 [rffi.CCHARP, rffi.CCHARP, rffi.SIZE_T], rffi.SSIZE_T,
3159 compilation_info=CConfig._compilation_info_,
3160 save_err=rffi.RFFI_SAVE_ERRNO)
3161 buf_sizes = [256, XATTR_SIZE_MAX]
3162
3163 def fgetxattr(fd, name):
3164 for size in buf_sizes:
3165 with rffi.scoped_alloc_buffer(size) as buf:
3166 void_buf = rffi.cast(rffi.VOIDP, buf.raw)
3167 res = c_fgetxattr(fd, name, void_buf, size)
3168 if res < 0:
3169 err = get_saved_errno()
3170 if err != errno.ERANGE:
3171 raise OSError(err, 'fgetxattr failed')
3172 else:
3173 return buf.str(res)
3174 else:
3175 raise OSError(errno.ERANGE, 'fgetxattr failed')
3176
3177 def getxattr(path, name, follow_symlinks=True):
3178 for size in buf_sizes:
3179 with rffi.scoped_alloc_buffer(size) as buf:
3180 void_buf = rffi.cast(rffi.VOIDP, buf.raw)
3181 if follow_symlinks:
3182 res = c_getxattr(path, name, void_buf, size)
3183 else:
3184 res = c_lgetxattr(path, name, void_buf, size)
3185 if res < 0:
3186 err = get_saved_errno()
3187 if err != errno.ERANGE:
3188 c_name = 'getxattr' if follow_symlinks else 'lgetxattr'
3189 raise OSError(err, c_name + 'failed')
3190 else:
3191 return buf.str(res)
3192 else:
3193 c_name = 'getxattr' if follow_symlinks else 'lgetxattr'
3194 raise OSError(errno.ERANGE, c_name + 'failed')
3195
3196 def fsetxattr(fd, name, value, flags=0):
3197 return handle_posix_error(
3198 'fsetxattr', c_fsetxattr(fd, name, value, len(value), flags))
3199
3200 def setxattr(path, name, value, flags=0, follow_symlinks=True):
3201 if follow_symlinks:
3202 return handle_posix_error(
3203 'setxattr', c_setxattr(path, name, value, len(value), flags))
3204 else:
3205 return handle_posix_error(
3206 'lsetxattr', c_lsetxattr(path, name, value, len(value), flags))
3207
3208 def fremovexattr(fd, name):
3209 return handle_posix_error('fremovexattr', c_fremovexattr(fd, name))
3210
3211 def removexattr(path, name, follow_symlinks=True):
3212 if follow_symlinks:
3213 return handle_posix_error('removexattr', c_removexattr(path, name))
3214 else:
3215 return handle_posix_error('lremovexattr', c_lremovexattr(path, name))
3216
3217 def _unpack_attrs(attr_string):
3218 result = attr_string.split('\0')
3219 del result[-1]
3220 return result
3221
3222 def flistxattr(fd):
3223 for size in buf_sizes:
3224 with rffi.scoped_alloc_buffer(size) as buf:
3225 res = c_flistxattr(fd, buf.raw, size)
3226 if res < 0:
3227 err = get_saved_errno()
3228 if err != errno.ERANGE:
3229 raise OSError(err, 'flistxattr failed')
3230 else:
3231 return _unpack_attrs(buf.str(res))
3232 else:
3233 raise OSError(errno.ERANGE, 'flistxattr failed')
3234
3235 def listxattr(path, follow_symlinks=True):
3236 for size in buf_sizes:
3237 with rffi.scoped_alloc_buffer(size) as buf:
3238 if follow_symlinks:
3239 res = c_listxattr(path, buf.raw, size)
3240 else:
3241 res = c_llistxattr(path, buf.raw, size)
3242 if res < 0:
3243 err = get_saved_errno()
3244 if err != errno.ERANGE:
3245 c_name = 'listxattr' if follow_symlinks else 'llistxattr'
3246 raise OSError(err, c_name + 'failed')
3247 else:
3248 return _unpack_attrs(buf.str(res))
3249 else:
3250 c_name = 'listxattr' if follow_symlinks else 'llistxattr'
3251 raise OSError(errno.ERANGE, c_name + 'failed')
3252
3253
3254 # ____________________________________________________________
3255 # Support for memfd_create function
3256
3257 if sys.platform.startswith('linux'):
3258 class CConfig:
3259 _compilation_info_ = ExternalCompilationInfo(
3260 includes=['sys/mman.h'],)
3261 for name in """
3262 MFD_CLOEXEC
3263 MFD_ALLOW_SEALING
3264 MFD_HUGETLB
3265 MFD_HUGE_SHIFT
3266 MFD_HUGE_MASK
3267 MFD_HUGE_64KB
3268 MFD_HUGE_512KB
3269 MFD_HUGE_1MB
3270 MFD_HUGE_2MB
3271 MFD_HUGE_8MB
3272 MFD_HUGE_16MB
3273 MFD_HUGE_32MB
3274 MFD_HUGE_256MB
3275 MFD_HUGE_512MB
3276 MFD_HUGE_1GB
3277 MFD_HUGE_2GB
3278 MFD_HUGE_16GB
3279 """.split():
3280 locals()[name] = rffi_platform.DefinedConstantInteger(name)
3281 HAVE_MEMFD_CREATE = rffi_platform.Has('memfd_create')
3282
3283 cConfig = rffi_platform.configure(CConfig)
3284 for key, value in cConfig.items():
3285 if value is not None and key.startswith("MFD_"):
3286 globals()[key] = value
3287
3288 if cConfig['HAVE_MEMFD_CREATE']:
3289 c_memfd_create = external('memfd_create',
3290 [rffi.CCHARP, rffi.UINT], rffi.INT,
3291 compilation_info=CConfig._compilation_info_,
3292 save_err=rffi.RFFI_SAVE_ERRNO)
3293 def memfd_create(name, flags):
3294 return handle_posix_error(
3295 'memfd_create', c_memfd_create(name, flags))
3296
3297