PageRenderTime 73ms CodeModel.GetById 18ms RepoModel.GetById 0ms app.codeStats 0ms

/pypy/rpython/module/ll_os.py

https://bitbucket.org/pypy/pypy/
Python | 1612 lines | 1608 code | 2 blank | 2 comment | 3 complexity | a71cdb1d24fe7b15b5c0222a833cc70d MD5 | raw file
Possible License(s): AGPL-3.0, BSD-3-Clause, Apache-2.0
  1. """
  2. Low-level implementations for the external functions of the 'os' module.
  3. """
  4. # Implementation details about those functions
  5. # might be found in doc/rffi.txt
  6. import os, sys, errno
  7. import py
  8. from pypy.rpython.module.support import ll_strcpy, OOSupport
  9. from pypy.tool.sourcetools import func_with_new_name, func_renamer
  10. from pypy.rlib.rarithmetic import r_longlong
  11. from pypy.rpython.extfunc import (
  12. BaseLazyRegistering, lazy_register, register_external)
  13. from pypy.rpython.extfunc import registering, registering_if, extdef
  14. from pypy.annotation.model import (
  15. SomeInteger, SomeString, SomeTuple, SomeFloat, SomeUnicodeString)
  16. from pypy.annotation.model import s_ImpossibleValue, s_None, s_Bool
  17. from pypy.rpython.lltypesystem import rffi
  18. from pypy.rpython.lltypesystem import lltype
  19. from pypy.rpython.tool import rffi_platform as platform
  20. from pypy.rlib import rposix
  21. from pypy.tool.udir import udir
  22. from pypy.translator.tool.cbuild import ExternalCompilationInfo
  23. from pypy.rpython.lltypesystem.rstr import mallocstr
  24. from pypy.rpython.annlowlevel import llstr
  25. from pypy.rpython.lltypesystem.llmemory import sizeof,\
  26. itemoffsetof, cast_ptr_to_adr, cast_adr_to_ptr, offsetof
  27. from pypy.rpython.lltypesystem.rstr import STR
  28. from pypy.rpython.annlowlevel import llstr
  29. from pypy.rlib import rgc
  30. from pypy.rlib.objectmodel import specialize
  31. str0 = SomeString(no_nul=True)
  32. unicode0 = SomeUnicodeString(no_nul=True)
  33. def monkeypatch_rposix(posixfunc, unicodefunc, signature):
  34. func_name = posixfunc.__name__
  35. if hasattr(signature, '_default_signature_'):
  36. signature = signature._default_signature_
  37. arglist = ['arg%d' % (i,) for i in range(len(signature))]
  38. transformed_arglist = arglist[:]
  39. for i, arg in enumerate(signature):
  40. if arg is unicode:
  41. transformed_arglist[i] = transformed_arglist[i] + '.as_unicode()'
  42. args = ', '.join(arglist)
  43. transformed_args = ', '.join(transformed_arglist)
  44. try:
  45. main_arg = 'arg%d' % (signature.index(unicode0),)
  46. except ValueError:
  47. main_arg = 'arg%d' % (signature.index(unicode),)
  48. source = py.code.Source("""
  49. def %(func_name)s(%(args)s):
  50. if isinstance(%(main_arg)s, str):
  51. return posixfunc(%(args)s)
  52. else:
  53. return unicodefunc(%(transformed_args)s)
  54. """ % locals())
  55. miniglobals = {'posixfunc' : posixfunc,
  56. 'unicodefunc': unicodefunc,
  57. '__name__': __name__, # for module name propagation
  58. }
  59. exec source.compile() in miniglobals
  60. new_func = miniglobals[func_name]
  61. specialized_args = [i for i in range(len(signature))
  62. if signature[i] in (unicode, None)]
  63. new_func = specialize.argtype(*specialized_args)(new_func)
  64. # Monkeypatch the function in pypy.rlib.rposix
  65. setattr(rposix, func_name, new_func)
  66. class StringTraits:
  67. str = str
  68. str0 = str0
  69. CHAR = rffi.CHAR
  70. CCHARP = rffi.CCHARP
  71. charp2str = staticmethod(rffi.charp2str)
  72. str2charp = staticmethod(rffi.str2charp)
  73. free_charp = staticmethod(rffi.free_charp)
  74. scoped_alloc_buffer = staticmethod(rffi.scoped_alloc_buffer)
  75. @staticmethod
  76. def posix_function_name(name):
  77. return underscore_on_windows + name
  78. @staticmethod
  79. def ll_os_name(name):
  80. return 'll_os.ll_os_' + name
  81. class UnicodeTraits:
  82. str = unicode
  83. str0 = unicode0
  84. CHAR = rffi.WCHAR_T
  85. CCHARP = rffi.CWCHARP
  86. charp2str = staticmethod(rffi.wcharp2unicode)
  87. str2charp = staticmethod(rffi.unicode2wcharp)
  88. free_charp = staticmethod(rffi.free_wcharp)
  89. scoped_alloc_buffer = staticmethod(rffi.scoped_alloc_unicodebuffer)
  90. @staticmethod
  91. def posix_function_name(name):
  92. return underscore_on_windows + 'w' + name
  93. @staticmethod
  94. def ll_os_name(name):
  95. return 'll_os.ll_os_w' + name
  96. def registering_str_unicode(posixfunc, condition=True):
  97. if not condition or posixfunc is None:
  98. return registering(None, condition=False)
  99. func_name = posixfunc.__name__
  100. def register_posixfunc(self, method):
  101. val = method(self, StringTraits())
  102. register_external(posixfunc, *val.def_args, **val.def_kwds)
  103. if sys.platform == 'win32':
  104. val = method(self, UnicodeTraits())
  105. @func_renamer(func_name + "_unicode")
  106. def unicodefunc(*args):
  107. return posixfunc(*args)
  108. register_external(unicodefunc, *val.def_args, **val.def_kwds)
  109. signature = val.def_args[0]
  110. monkeypatch_rposix(posixfunc, unicodefunc, signature)
  111. def decorator(method):
  112. decorated = lambda self: register_posixfunc(self, method)
  113. decorated._registering_func = posixfunc
  114. return decorated
  115. return decorator
  116. posix = __import__(os.name)
  117. if sys.platform.startswith('win'):
  118. _WIN32 = True
  119. else:
  120. _WIN32 = False
  121. if _WIN32:
  122. underscore_on_windows = '_'
  123. else:
  124. underscore_on_windows = ''
  125. includes = []
  126. if not _WIN32:
  127. # XXX many of these includes are not portable at all
  128. includes += ['dirent.h', 'sys/stat.h',
  129. 'sys/times.h', 'utime.h', 'sys/types.h', 'unistd.h',
  130. 'signal.h', 'sys/wait.h', 'fcntl.h']
  131. else:
  132. includes += ['sys/utime.h']
  133. class CConfig:
  134. """
  135. Definitions for platform integration.
  136. Note: this must be processed through platform.configure() to provide
  137. usable objects. For example::
  138. CLOCK_T = platform.configure(CConfig)['CLOCK_T']
  139. register(function, [CLOCK_T], ...)
  140. """
  141. _compilation_info_ = ExternalCompilationInfo(
  142. includes=includes
  143. )
  144. if not _WIN32:
  145. CLOCK_T = platform.SimpleType('clock_t', rffi.INT)
  146. TMS = platform.Struct(
  147. 'struct tms', [('tms_utime', rffi.INT),
  148. ('tms_stime', rffi.INT),
  149. ('tms_cutime', rffi.INT),
  150. ('tms_cstime', rffi.INT)])
  151. GID_T = platform.SimpleType('gid_t',rffi.INT)
  152. #TODO right now is used only in getgroups, may need to update other
  153. #functions like setgid
  154. SEEK_SET = platform.DefinedConstantInteger('SEEK_SET')
  155. SEEK_CUR = platform.DefinedConstantInteger('SEEK_CUR')
  156. SEEK_END = platform.DefinedConstantInteger('SEEK_END')
  157. UTIMBUF = platform.Struct('struct '+underscore_on_windows+'utimbuf',
  158. [('actime', rffi.INT),
  159. ('modtime', rffi.INT)])
  160. class RegisterOs(BaseLazyRegistering):
  161. def __init__(self):
  162. self.configure(CConfig)
  163. if hasattr(os, 'getpgrp'):
  164. self.GETPGRP_HAVE_ARG = platform.checkcompiles(
  165. "getpgrp(0)",
  166. '#include <unistd.h>',
  167. [])
  168. if hasattr(os, 'setpgrp'):
  169. self.SETPGRP_HAVE_ARG = platform.checkcompiles(
  170. "setpgrp(0,0)",
  171. '#include <unistd.h>',
  172. [])
  173. # we need an indirection via c functions to get macro calls working on llvm XXX still?
  174. if hasattr(os, 'WCOREDUMP'):
  175. decl_snippet = """
  176. %(ret_type)s pypy_macro_wrapper_%(name)s (int status);
  177. """
  178. def_snippet = """
  179. %(ret_type)s pypy_macro_wrapper_%(name)s (int status) {
  180. return %(name)s(status);
  181. }
  182. """
  183. decls = []
  184. defs = []
  185. for name in self.w_star:
  186. data = {'ret_type': 'int', 'name': name}
  187. decls.append((decl_snippet % data).strip())
  188. defs.append((def_snippet % data).strip())
  189. self.compilation_info = self.compilation_info.merge(
  190. ExternalCompilationInfo(
  191. post_include_bits = decls,
  192. separate_module_sources = ["\n".join(defs)]
  193. ))
  194. # a simple, yet useful factory
  195. def extdef_for_os_function_returning_int(self, name, **kwds):
  196. c_func = self.llexternal(name, [], rffi.INT, **kwds)
  197. def c_func_llimpl():
  198. res = rffi.cast(rffi.LONG, c_func())
  199. if res == -1:
  200. raise OSError(rposix.get_errno(), "%s failed" % name)
  201. return res
  202. c_func_llimpl.func_name = name + '_llimpl'
  203. return extdef([], int, llimpl=c_func_llimpl,
  204. export_name='ll_os.ll_os_' + name)
  205. def extdef_for_os_function_accepting_int(self, name, **kwds):
  206. c_func = self.llexternal(name, [rffi.INT], rffi.INT, **kwds)
  207. def c_func_llimpl(arg):
  208. res = rffi.cast(rffi.LONG, c_func(arg))
  209. if res == -1:
  210. raise OSError(rposix.get_errno(), "%s failed" % name)
  211. c_func_llimpl.func_name = name + '_llimpl'
  212. return extdef([int], None, llimpl=c_func_llimpl,
  213. export_name='ll_os.ll_os_' + name)
  214. def extdef_for_os_function_accepting_2int(self, name, **kwds):
  215. c_func = self.llexternal(name, [rffi.INT, rffi.INT], rffi.INT, **kwds)
  216. def c_func_llimpl(arg, arg2):
  217. res = rffi.cast(rffi.LONG, c_func(arg, arg2))
  218. if res == -1:
  219. raise OSError(rposix.get_errno(), "%s failed" % name)
  220. c_func_llimpl.func_name = name + '_llimpl'
  221. return extdef([int, int], None, llimpl=c_func_llimpl,
  222. export_name='ll_os.ll_os_' + name)
  223. def extdef_for_os_function_accepting_0int(self, name, **kwds):
  224. c_func = self.llexternal(name, [], rffi.INT, **kwds)
  225. def c_func_llimpl():
  226. res = rffi.cast(rffi.LONG, c_func())
  227. if res == -1:
  228. raise OSError(rposix.get_errno(), "%s failed" % name)
  229. c_func_llimpl.func_name = name + '_llimpl'
  230. return extdef([], None, llimpl=c_func_llimpl,
  231. export_name='ll_os.ll_os_' + name)
  232. def extdef_for_os_function_int_to_int(self, name, **kwds):
  233. c_func = self.llexternal(name, [rffi.INT], rffi.INT, **kwds)
  234. def c_func_llimpl(arg):
  235. res = rffi.cast(rffi.LONG, c_func(arg))
  236. if res == -1:
  237. raise OSError(rposix.get_errno(), "%s failed" % name)
  238. return res
  239. c_func_llimpl.func_name = name + '_llimpl'
  240. return extdef([int], int, llimpl=c_func_llimpl,
  241. export_name='ll_os.ll_os_' + name)
  242. @registering_if(os, 'execv')
  243. def register_os_execv(self):
  244. eci = self.gcc_profiling_bug_workaround(
  245. 'int _noprof_execv(char *path, char *argv[])',
  246. 'return execv(path, argv);')
  247. os_execv = self.llexternal('_noprof_execv',
  248. [rffi.CCHARP, rffi.CCHARPP],
  249. rffi.INT, compilation_info = eci)
  250. def execv_llimpl(path, args):
  251. l_args = rffi.liststr2charpp(args)
  252. os_execv(path, l_args)
  253. rffi.free_charpp(l_args)
  254. raise OSError(rposix.get_errno(), "execv failed")
  255. return extdef([str0, [str0]], s_ImpossibleValue, llimpl=execv_llimpl,
  256. export_name="ll_os.ll_os_execv")
  257. @registering_if(os, 'execve')
  258. def register_os_execve(self):
  259. eci = self.gcc_profiling_bug_workaround(
  260. 'int _noprof_execve(char *filename, char *argv[], char *envp[])',
  261. 'return execve(filename, argv, envp);')
  262. os_execve = self.llexternal(
  263. '_noprof_execve', [rffi.CCHARP, rffi.CCHARPP, rffi.CCHARPP],
  264. rffi.INT, compilation_info = eci)
  265. def execve_llimpl(path, args, env):
  266. # XXX Check path, args, env for \0 and raise TypeErrors as
  267. # appropriate
  268. envstrs = []
  269. for item in env.iteritems():
  270. envstr = "%s=%s" % item
  271. envstrs.append(envstr)
  272. l_args = rffi.liststr2charpp(args)
  273. l_env = rffi.liststr2charpp(envstrs)
  274. os_execve(path, l_args, l_env)
  275. # XXX untested
  276. rffi.free_charpp(l_env)
  277. rffi.free_charpp(l_args)
  278. raise OSError(rposix.get_errno(), "execve failed")
  279. return extdef(
  280. [str0, [str0], {str0: str0}],
  281. s_ImpossibleValue,
  282. llimpl=execve_llimpl,
  283. export_name="ll_os.ll_os_execve")
  284. @registering_if(posix, 'spawnv')
  285. def register_os_spawnv(self):
  286. os_spawnv = self.llexternal('spawnv',
  287. [rffi.INT, rffi.CCHARP, rffi.CCHARPP],
  288. rffi.INT)
  289. def spawnv_llimpl(mode, path, args):
  290. mode = rffi.cast(rffi.INT, mode)
  291. l_args = rffi.liststr2charpp(args)
  292. childpid = os_spawnv(mode, path, l_args)
  293. rffi.free_charpp(l_args)
  294. if childpid == -1:
  295. raise OSError(rposix.get_errno(), "os_spawnv failed")
  296. return rffi.cast(lltype.Signed, childpid)
  297. return extdef([int, str0, [str0]], int, llimpl=spawnv_llimpl,
  298. export_name="ll_os.ll_os_spawnv")
  299. @registering_if(os, 'spawnve')
  300. def register_os_spawnve(self):
  301. os_spawnve = self.llexternal('spawnve',
  302. [rffi.INT, rffi.CCHARP, rffi.CCHARPP,
  303. rffi.CCHARPP],
  304. rffi.INT)
  305. def spawnve_llimpl(mode, path, args, env):
  306. envstrs = []
  307. for item in env.iteritems():
  308. envstrs.append("%s=%s" % item)
  309. mode = rffi.cast(rffi.INT, mode)
  310. l_args = rffi.liststr2charpp(args)
  311. l_env = rffi.liststr2charpp(envstrs)
  312. childpid = os_spawnve(mode, path, l_args, l_env)
  313. rffi.free_charpp(l_env)
  314. rffi.free_charpp(l_args)
  315. if childpid == -1:
  316. raise OSError(rposix.get_errno(), "os_spawnve failed")
  317. return rffi.cast(lltype.Signed, childpid)
  318. return extdef([int, str0, [str0], {str0: str0}], int,
  319. llimpl=spawnve_llimpl,
  320. export_name="ll_os.ll_os_spawnve")
  321. @registering(os.dup)
  322. def register_os_dup(self):
  323. os_dup = self.llexternal(underscore_on_windows+'dup', [rffi.INT], rffi.INT)
  324. def dup_llimpl(fd):
  325. newfd = rffi.cast(lltype.Signed, os_dup(rffi.cast(rffi.INT, fd)))
  326. if newfd == -1:
  327. raise OSError(rposix.get_errno(), "dup failed")
  328. return newfd
  329. return extdef([int], int, llimpl=dup_llimpl,
  330. export_name="ll_os.ll_os_dup", oofakeimpl=os.dup)
  331. @registering(os.dup2)
  332. def register_os_dup2(self):
  333. os_dup2 = self.llexternal(underscore_on_windows+'dup2',
  334. [rffi.INT, rffi.INT], rffi.INT)
  335. def dup2_llimpl(fd, newfd):
  336. error = rffi.cast(lltype.Signed, os_dup2(rffi.cast(rffi.INT, fd),
  337. rffi.cast(rffi.INT, newfd)))
  338. if error == -1:
  339. raise OSError(rposix.get_errno(), "dup2 failed")
  340. return extdef([int, int], s_None, llimpl=dup2_llimpl,
  341. export_name="ll_os.ll_os_dup2")
  342. @registering_if(os, "getlogin", condition=not _WIN32)
  343. def register_os_getlogin(self):
  344. os_getlogin = self.llexternal('getlogin', [], rffi.CCHARP)
  345. def getlogin_llimpl():
  346. result = os_getlogin()
  347. if not result:
  348. raise OSError(rposix.get_errno(), "getlogin failed")
  349. return rffi.charp2str(result)
  350. return extdef([], str, llimpl=getlogin_llimpl,
  351. export_name="ll_os.ll_os_getlogin")
  352. @registering_str_unicode(os.utime)
  353. def register_os_utime(self, traits):
  354. UTIMBUFP = lltype.Ptr(self.UTIMBUF)
  355. os_utime = self.llexternal('utime', [rffi.CCHARP, UTIMBUFP], rffi.INT)
  356. class CConfig:
  357. _compilation_info_ = ExternalCompilationInfo(
  358. includes=['sys/time.h']
  359. )
  360. HAVE_UTIMES = platform.Has('utimes')
  361. config = platform.configure(CConfig)
  362. # XXX note that on Windows, calls to os.utime() are ignored on
  363. # directories. Remove that hack over there once it's fixed here!
  364. if config['HAVE_UTIMES']:
  365. class CConfig:
  366. _compilation_info_ = ExternalCompilationInfo(
  367. includes = ['sys/time.h']
  368. )
  369. TIMEVAL = platform.Struct('struct timeval', [('tv_sec', rffi.LONG),
  370. ('tv_usec', rffi.LONG)])
  371. config = platform.configure(CConfig)
  372. TIMEVAL = config['TIMEVAL']
  373. TIMEVAL2P = rffi.CArrayPtr(TIMEVAL)
  374. os_utimes = self.llexternal('utimes', [rffi.CCHARP, TIMEVAL2P],
  375. rffi.INT, compilation_info=CConfig._compilation_info_)
  376. def os_utime_platform(path, actime, modtime):
  377. import math
  378. l_times = lltype.malloc(TIMEVAL2P.TO, 2, flavor='raw')
  379. fracpart, intpart = math.modf(actime)
  380. rffi.setintfield(l_times[0], 'c_tv_sec', int(intpart))
  381. rffi.setintfield(l_times[0], 'c_tv_usec', int(fracpart * 1E6))
  382. fracpart, intpart = math.modf(modtime)
  383. rffi.setintfield(l_times[1], 'c_tv_sec', int(intpart))
  384. rffi.setintfield(l_times[1], 'c_tv_usec', int(fracpart * 1E6))
  385. error = os_utimes(path, l_times)
  386. lltype.free(l_times, flavor='raw')
  387. return error
  388. else:
  389. # we only have utime(), which does not allow sub-second resolution
  390. def os_utime_platform(path, actime, modtime):
  391. l_utimbuf = lltype.malloc(UTIMBUFP.TO, flavor='raw')
  392. l_utimbuf.c_actime = rffi.r_time_t(actime)
  393. l_utimbuf.c_modtime = rffi.r_time_t(modtime)
  394. error = os_utime(path, l_utimbuf)
  395. lltype.free(l_utimbuf, flavor='raw')
  396. return error
  397. # NB. this function is specialized; we get one version where
  398. # tp is known to be None, and one version where it is known
  399. # to be a tuple of 2 floats.
  400. if not _WIN32:
  401. assert traits.str is str
  402. @specialize.argtype(1)
  403. def os_utime_llimpl(path, tp):
  404. if tp is None:
  405. error = os_utime(path, lltype.nullptr(UTIMBUFP.TO))
  406. else:
  407. actime, modtime = tp
  408. error = os_utime_platform(path, actime, modtime)
  409. error = rffi.cast(lltype.Signed, error)
  410. if error == -1:
  411. raise OSError(rposix.get_errno(), "os_utime failed")
  412. else:
  413. from pypy.rpython.module.ll_win32file import make_utime_impl
  414. os_utime_llimpl = make_utime_impl(traits)
  415. if traits.str is str:
  416. s_string = SomeString()
  417. else:
  418. s_string = SomeUnicodeString()
  419. s_tuple_of_2_floats = SomeTuple([SomeFloat(), SomeFloat()])
  420. def os_utime_normalize_args(s_path, s_times):
  421. # special handling of the arguments: they can be either
  422. # [str, (float, float)] or [str, s_None], and get normalized
  423. # to exactly one of these two.
  424. if not s_string.contains(s_path):
  425. raise Exception("os.utime() arg 1 must be a string, got %s" % (
  426. s_path,))
  427. case1 = s_None.contains(s_times)
  428. case2 = s_tuple_of_2_floats.contains(s_times)
  429. if case1 and case2:
  430. return [s_string, s_ImpossibleValue] #don't know which case yet
  431. elif case1:
  432. return [s_string, s_None]
  433. elif case2:
  434. return [s_string, s_tuple_of_2_floats]
  435. else:
  436. raise Exception("os.utime() arg 2 must be None or a tuple of "
  437. "2 floats, got %s" % (s_times,))
  438. os_utime_normalize_args._default_signature_ = [traits.str0, None]
  439. return extdef(os_utime_normalize_args, s_None,
  440. "ll_os.ll_os_utime",
  441. llimpl=os_utime_llimpl)
  442. @registering(os.times)
  443. def register_os_times(self):
  444. if sys.platform.startswith('win'):
  445. from pypy.rlib import rwin32
  446. GetCurrentProcess = self.llexternal('GetCurrentProcess', [],
  447. rwin32.HANDLE)
  448. GetProcessTimes = self.llexternal('GetProcessTimes',
  449. [rwin32.HANDLE,
  450. lltype.Ptr(rwin32.FILETIME),
  451. lltype.Ptr(rwin32.FILETIME),
  452. lltype.Ptr(rwin32.FILETIME),
  453. lltype.Ptr(rwin32.FILETIME)],
  454. rwin32.BOOL)
  455. def times_lltypeimpl():
  456. pcreate = lltype.malloc(rwin32.FILETIME, flavor='raw')
  457. pexit = lltype.malloc(rwin32.FILETIME, flavor='raw')
  458. pkernel = lltype.malloc(rwin32.FILETIME, flavor='raw')
  459. puser = lltype.malloc(rwin32.FILETIME, flavor='raw')
  460. hProc = GetCurrentProcess()
  461. GetProcessTimes(hProc, pcreate, pexit, pkernel, puser)
  462. # The fields of a FILETIME structure are the hi and lo parts
  463. # of a 64-bit value expressed in 100 nanosecond units
  464. # (of course).
  465. result = (pkernel.c_dwHighDateTime*429.4967296 +
  466. pkernel.c_dwLowDateTime*1E-7,
  467. puser.c_dwHighDateTime*429.4967296 +
  468. puser.c_dwLowDateTime*1E-7,
  469. 0, 0, 0)
  470. lltype.free(puser, flavor='raw')
  471. lltype.free(pkernel, flavor='raw')
  472. lltype.free(pexit, flavor='raw')
  473. lltype.free(pcreate, flavor='raw')
  474. return result
  475. self.register(os.times, [], (float, float, float, float, float),
  476. "ll_os.ll_times", llimpl=times_lltypeimpl)
  477. return
  478. TMSP = lltype.Ptr(self.TMS)
  479. os_times = self.llexternal('times', [TMSP], self.CLOCK_T)
  480. # Here is a random extra platform parameter which is important.
  481. # Strictly speaking, this should probably be retrieved at runtime, not
  482. # at translation time.
  483. CLOCK_TICKS_PER_SECOND = float(os.sysconf('SC_CLK_TCK'))
  484. def times_lltypeimpl():
  485. l_tmsbuf = lltype.malloc(TMSP.TO, flavor='raw')
  486. try:
  487. result = os_times(l_tmsbuf)
  488. result = rffi.cast(lltype.Signed, result)
  489. if result == -1:
  490. raise OSError(rposix.get_errno(), "times failed")
  491. return (
  492. rffi.cast(lltype.Signed, l_tmsbuf.c_tms_utime)
  493. / CLOCK_TICKS_PER_SECOND,
  494. rffi.cast(lltype.Signed, l_tmsbuf.c_tms_stime)
  495. / CLOCK_TICKS_PER_SECOND,
  496. rffi.cast(lltype.Signed, l_tmsbuf.c_tms_cutime)
  497. / CLOCK_TICKS_PER_SECOND,
  498. rffi.cast(lltype.Signed, l_tmsbuf.c_tms_cstime)
  499. / CLOCK_TICKS_PER_SECOND,
  500. result / CLOCK_TICKS_PER_SECOND)
  501. finally:
  502. lltype.free(l_tmsbuf, flavor='raw')
  503. self.register(os.times, [], (float, float, float, float, float),
  504. "ll_os.ll_times", llimpl=times_lltypeimpl)
  505. @registering_if(os, 'setsid')
  506. def register_os_setsid(self):
  507. os_setsid = self.llexternal('setsid', [], rffi.PID_T)
  508. def setsid_llimpl():
  509. result = rffi.cast(lltype.Signed, os_setsid())
  510. if result == -1:
  511. raise OSError(rposix.get_errno(), "os_setsid failed")
  512. return result
  513. return extdef([], int, export_name="ll_os.ll_os_setsid",
  514. llimpl=setsid_llimpl)
  515. @registering_if(os, 'chroot')
  516. def register_os_chroot(self):
  517. os_chroot = self.llexternal('chroot', [rffi.CCHARP], rffi.INT)
  518. def chroot_llimpl(arg):
  519. result = os_chroot(arg)
  520. if result == -1:
  521. raise OSError(rposix.get_errno(), "os_chroot failed")
  522. return extdef([str0], None, export_name="ll_os.ll_os_chroot",
  523. llimpl=chroot_llimpl)
  524. @registering_if(os, 'uname')
  525. def register_os_uname(self):
  526. CHARARRAY = lltype.FixedSizeArray(lltype.Char, 1)
  527. class CConfig:
  528. _compilation_info_ = ExternalCompilationInfo(
  529. includes = ['sys/utsname.h']
  530. )
  531. UTSNAME = platform.Struct('struct utsname', [
  532. ('sysname', CHARARRAY),
  533. ('nodename', CHARARRAY),
  534. ('release', CHARARRAY),
  535. ('version', CHARARRAY),
  536. ('machine', CHARARRAY)])
  537. config = platform.configure(CConfig)
  538. UTSNAMEP = lltype.Ptr(config['UTSNAME'])
  539. os_uname = self.llexternal('uname', [UTSNAMEP], rffi.INT,
  540. compilation_info=CConfig._compilation_info_)
  541. def uname_llimpl():
  542. l_utsbuf = lltype.malloc(UTSNAMEP.TO, flavor='raw')
  543. result = os_uname(l_utsbuf)
  544. if result == -1:
  545. raise OSError(rposix.get_errno(), "os_uname failed")
  546. retval = (
  547. rffi.charp2str(rffi.cast(rffi.CCHARP, l_utsbuf.c_sysname)),
  548. rffi.charp2str(rffi.cast(rffi.CCHARP, l_utsbuf.c_nodename)),
  549. rffi.charp2str(rffi.cast(rffi.CCHARP, l_utsbuf.c_release)),
  550. rffi.charp2str(rffi.cast(rffi.CCHARP, l_utsbuf.c_version)),
  551. rffi.charp2str(rffi.cast(rffi.CCHARP, l_utsbuf.c_machine)),
  552. )
  553. lltype.free(l_utsbuf, flavor='raw')
  554. return retval
  555. return extdef([], (str, str, str, str, str),
  556. "ll_os.ll_uname", llimpl=uname_llimpl)
  557. @registering_if(os, 'sysconf')
  558. def register_os_sysconf(self):
  559. c_sysconf = self.llexternal('sysconf', [rffi.INT], rffi.LONG)
  560. def sysconf_llimpl(i):
  561. rposix.set_errno(0)
  562. res = c_sysconf(i)
  563. if res == -1:
  564. errno = rposix.get_errno()
  565. if errno != 0:
  566. raise OSError(errno, "sysconf failed")
  567. return res
  568. return extdef([int], int, "ll_os.ll_sysconf", llimpl=sysconf_llimpl)
  569. @registering_if(os, 'fpathconf')
  570. def register_os_fpathconf(self):
  571. c_fpathconf = self.llexternal('fpathconf',
  572. [rffi.INT, rffi.INT], rffi.LONG)
  573. def fpathconf_llimpl(fd, i):
  574. rposix.set_errno(0)
  575. res = c_fpathconf(fd, i)
  576. if res == -1:
  577. errno = rposix.get_errno()
  578. if errno != 0:
  579. raise OSError(errno, "fpathconf failed")
  580. return res
  581. return extdef([int, int], int, "ll_os.ll_fpathconf",
  582. llimpl=fpathconf_llimpl)
  583. @registering_if(os, 'getuid')
  584. def register_os_getuid(self):
  585. return self.extdef_for_os_function_returning_int('getuid')
  586. @registering_if(os, 'geteuid')
  587. def register_os_geteuid(self):
  588. return self.extdef_for_os_function_returning_int('geteuid')
  589. @registering_if(os, 'setuid')
  590. def register_os_setuid(self):
  591. return self.extdef_for_os_function_accepting_int('setuid')
  592. @registering_if(os, 'seteuid')
  593. def register_os_seteuid(self):
  594. return self.extdef_for_os_function_accepting_int('seteuid')
  595. @registering_if(os, 'setgid')
  596. def register_os_setgid(self):
  597. return self.extdef_for_os_function_accepting_int('setgid')
  598. @registering_if(os, 'setegid')
  599. def register_os_setegid(self):
  600. return self.extdef_for_os_function_accepting_int('setegid')
  601. @registering_if(os, 'getpid')
  602. def register_os_getpid(self):
  603. return self.extdef_for_os_function_returning_int('getpid')
  604. @registering_if(os, 'getgid')
  605. def register_os_getgid(self):
  606. return self.extdef_for_os_function_returning_int('getgid')
  607. @registering_if(os, 'getegid')
  608. def register_os_getegid(self):
  609. return self.extdef_for_os_function_returning_int('getegid')
  610. @registering_if(os, 'getgroups')
  611. def register_os_getgroups(self):
  612. GP = rffi.CArrayPtr(self.GID_T)
  613. c_getgroups = self.llexternal('getgroups', [rffi.INT, GP], rffi.INT)
  614. def getgroups_llimpl():
  615. n = c_getgroups(0, lltype.nullptr(GP.TO))
  616. if n >= 0:
  617. groups = lltype.malloc(GP.TO, n, flavor='raw')
  618. try:
  619. n = c_getgroups(n, groups)
  620. result = [groups[i] for i in range(n)]
  621. finally:
  622. lltype.free(groups, flavor='raw')
  623. if n >= 0:
  624. return result
  625. raise OSError(rposix.get_errno(), "os_getgroups failed")
  626. return extdef([], [self.GID_T], llimpl=getgroups_llimpl,
  627. export_name="ll_os.ll_getgroups")
  628. @registering_if(os, 'getpgrp')
  629. def register_os_getpgrp(self):
  630. name = 'getpgrp'
  631. if self.GETPGRP_HAVE_ARG:
  632. c_func = self.llexternal(name, [rffi.INT], rffi.INT)
  633. def c_func_llimpl():
  634. res = rffi.cast(rffi.LONG, c_func(0))
  635. if res == -1:
  636. raise OSError(rposix.get_errno(), "%s failed" % name)
  637. return res
  638. c_func_llimpl.func_name = name + '_llimpl'
  639. return extdef([], int, llimpl=c_func_llimpl,
  640. export_name='ll_os.ll_os_' + name)
  641. else:
  642. return self.extdef_for_os_function_returning_int('getpgrp')
  643. @registering_if(os, 'setpgrp')
  644. def register_os_setpgrp(self):
  645. name = 'setpgrp'
  646. if self.SETPGRP_HAVE_ARG:
  647. c_func = self.llexternal(name, [rffi.INT, rffi.INT], rffi.INT)
  648. def c_func_llimpl():
  649. res = rffi.cast(rffi.LONG, c_func(0, 0))
  650. if res == -1:
  651. raise OSError(rposix.get_errno(), "%s failed" % name)
  652. c_func_llimpl.func_name = name + '_llimpl'
  653. return extdef([], None, llimpl=c_func_llimpl,
  654. export_name='ll_os.ll_os_' + name)
  655. else:
  656. return self.extdef_for_os_function_accepting_0int(name)
  657. @registering_if(os, 'getppid')
  658. def register_os_getppid(self):
  659. return self.extdef_for_os_function_returning_int('getppid')
  660. @registering_if(os, 'getpgid')
  661. def register_os_getpgid(self):
  662. return self.extdef_for_os_function_int_to_int('getpgid')
  663. @registering_if(os, 'setpgid')
  664. def register_os_setpgid(self):
  665. return self.extdef_for_os_function_accepting_2int('setpgid')
  666. @registering_if(os, 'setreuid')
  667. def register_os_setreuid(self):
  668. return self.extdef_for_os_function_accepting_2int('setreuid')
  669. @registering_if(os, 'setregid')
  670. def register_os_setregid(self):
  671. return self.extdef_for_os_function_accepting_2int('setregid')
  672. @registering_if(os, 'getsid')
  673. def register_os_getsid(self):
  674. return self.extdef_for_os_function_int_to_int('getsid')
  675. @registering_if(os, 'setsid')
  676. def register_os_setsid(self):
  677. return self.extdef_for_os_function_returning_int('setsid')
  678. @registering_str_unicode(os.open)
  679. def register_os_open(self, traits):
  680. os_open = self.llexternal(traits.posix_function_name('open'),
  681. [traits.CCHARP, rffi.INT, rffi.MODE_T],
  682. rffi.INT)
  683. def os_open_llimpl(path, flags, mode):
  684. result = rffi.cast(rffi.LONG, os_open(path, flags, mode))
  685. if result == -1:
  686. raise OSError(rposix.get_errno(), "os_open failed")
  687. return result
  688. def os_open_oofakeimpl(path, flags, mode):
  689. return os.open(OOSupport.from_rstr(path), flags, mode)
  690. return extdef([traits.str0, int, int], int, traits.ll_os_name('open'),
  691. llimpl=os_open_llimpl, oofakeimpl=os_open_oofakeimpl)
  692. @registering_if(os, 'getloadavg')
  693. def register_os_getloadavg(self):
  694. AP = rffi.CArrayPtr(lltype.Float)
  695. c_getloadavg = self.llexternal('getloadavg', [AP, rffi.INT], rffi.INT)
  696. def getloadavg_llimpl():
  697. load = lltype.malloc(AP.TO, 3, flavor='raw')
  698. r = c_getloadavg(load, 3)
  699. result_tuple = load[0], load[1], load[2]
  700. lltype.free(load, flavor='raw')
  701. if r != 3:
  702. raise OSError
  703. return result_tuple
  704. return extdef([], (float, float, float),
  705. "ll_os.ll_getloadavg", llimpl=getloadavg_llimpl)
  706. @registering_if(os, 'makedev')
  707. def register_os_makedev(self):
  708. c_makedev = self.llexternal('makedev', [rffi.INT, rffi.INT], rffi.INT)
  709. def makedev_llimpl(maj, min):
  710. return c_makedev(maj, min)
  711. return extdef([int, int], int,
  712. "ll_os.ll_makedev", llimpl=makedev_llimpl)
  713. @registering_if(os, 'major')
  714. def register_os_major(self):
  715. c_major = self.llexternal('major', [rffi.INT], rffi.INT)
  716. def major_llimpl(dev):
  717. return c_major(dev)
  718. return extdef([int], int,
  719. "ll_os.ll_major", llimpl=major_llimpl)
  720. @registering_if(os, 'minor')
  721. def register_os_minor(self):
  722. c_minor = self.llexternal('minor', [rffi.INT], rffi.INT)
  723. def minor_llimpl(dev):
  724. return c_minor(dev)
  725. return extdef([int], int,
  726. "ll_os.ll_minor", llimpl=minor_llimpl)
  727. # ------------------------------- os.read -------------------------------
  728. @registering(os.read)
  729. def register_os_read(self):
  730. os_read = self.llexternal(underscore_on_windows+'read',
  731. [rffi.INT, rffi.VOIDP, rffi.SIZE_T],
  732. rffi.SIZE_T)
  733. offset = offsetof(STR, 'chars') + itemoffsetof(STR.chars, 0)
  734. def os_read_llimpl(fd, count):
  735. if count < 0:
  736. raise OSError(errno.EINVAL, None)
  737. raw_buf, gc_buf = rffi.alloc_buffer(count)
  738. try:
  739. void_buf = rffi.cast(rffi.VOIDP, raw_buf)
  740. got = rffi.cast(lltype.Signed, os_read(fd, void_buf, count))
  741. if got < 0:
  742. raise OSError(rposix.get_errno(), "os_read failed")
  743. return rffi.str_from_buffer(raw_buf, gc_buf, count, got)
  744. finally:
  745. rffi.keep_buffer_alive_until_here(raw_buf, gc_buf)
  746. def os_read_oofakeimpl(fd, count):
  747. return OOSupport.to_rstr(os.read(fd, count))
  748. return extdef([int, int], SomeString(can_be_None=True),
  749. "ll_os.ll_os_read",
  750. llimpl=os_read_llimpl, oofakeimpl=os_read_oofakeimpl)
  751. @registering(os.write)
  752. def register_os_write(self):
  753. os_write = self.llexternal(underscore_on_windows+'write',
  754. [rffi.INT, rffi.VOIDP, rffi.SIZE_T],
  755. rffi.SIZE_T)
  756. def os_write_llimpl(fd, data):
  757. count = len(data)
  758. buf = rffi.get_nonmovingbuffer(data)
  759. try:
  760. written = rffi.cast(lltype.Signed, os_write(
  761. rffi.cast(rffi.INT, fd),
  762. buf, rffi.cast(rffi.SIZE_T, count)))
  763. if written < 0:
  764. raise OSError(rposix.get_errno(), "os_write failed")
  765. finally:
  766. rffi.free_nonmovingbuffer(data, buf)
  767. return written
  768. def os_write_oofakeimpl(fd, data):
  769. return os.write(fd, OOSupport.from_rstr(data))
  770. return extdef([int, str], SomeInteger(nonneg=True),
  771. "ll_os.ll_os_write", llimpl=os_write_llimpl,
  772. oofakeimpl=os_write_oofakeimpl)
  773. @registering(os.close)
  774. def register_os_close(self):
  775. os_close = self.llexternal(underscore_on_windows+'close', [rffi.INT],
  776. rffi.INT, threadsafe=False)
  777. def close_llimpl(fd):
  778. error = rffi.cast(lltype.Signed, os_close(rffi.cast(rffi.INT, fd)))
  779. if error == -1:
  780. raise OSError(rposix.get_errno(), "close failed")
  781. return extdef([int], s_None, llimpl=close_llimpl,
  782. export_name="ll_os.ll_os_close", oofakeimpl=os.close)
  783. @registering(os.lseek)
  784. def register_os_lseek(self):
  785. if sys.platform.startswith('win'):
  786. funcname = '_lseeki64'
  787. else:
  788. funcname = 'lseek'
  789. if self.SEEK_SET is not None:
  790. SEEK_SET = self.SEEK_SET
  791. SEEK_CUR = self.SEEK_CUR
  792. SEEK_END = self.SEEK_END
  793. else:
  794. SEEK_SET, SEEK_CUR, SEEK_END = 0, 1, 2
  795. if (SEEK_SET, SEEK_CUR, SEEK_END) != (0, 1, 2):
  796. # Turn 0, 1, 2 into SEEK_{SET,CUR,END}
  797. def fix_seek_arg(n):
  798. if n == 0: return SEEK_SET
  799. if n == 1: return SEEK_CUR
  800. if n == 2: return SEEK_END
  801. return n
  802. else:
  803. def fix_seek_arg(n):
  804. return n
  805. os_lseek = self.llexternal(funcname,
  806. [rffi.INT, rffi.LONGLONG, rffi.INT],
  807. rffi.LONGLONG)
  808. def lseek_llimpl(fd, pos, how):
  809. how = fix_seek_arg(how)
  810. res = os_lseek(rffi.cast(rffi.INT, fd),
  811. rffi.cast(rffi.LONGLONG, pos),
  812. rffi.cast(rffi.INT, how))
  813. res = rffi.cast(lltype.SignedLongLong, res)
  814. if res < 0:
  815. raise OSError(rposix.get_errno(), "os_lseek failed")
  816. return res
  817. def os_lseek_oofakeimpl(fd, pos, how):
  818. res = os.lseek(fd, pos, how)
  819. return r_longlong(res)
  820. return extdef([int, r_longlong, int],
  821. r_longlong,
  822. llimpl = lseek_llimpl,
  823. export_name = "ll_os.ll_os_lseek",
  824. oofakeimpl = os_lseek_oofakeimpl)
  825. @registering_if(os, 'ftruncate')
  826. def register_os_ftruncate(self):
  827. os_ftruncate = self.llexternal('ftruncate',
  828. [rffi.INT, rffi.LONGLONG], rffi.INT)
  829. def ftruncate_llimpl(fd, length):
  830. res = rffi.cast(rffi.LONG,
  831. os_ftruncate(rffi.cast(rffi.INT, fd),
  832. rffi.cast(rffi.LONGLONG, length)))
  833. if res < 0:
  834. raise OSError(rposix.get_errno(), "os_ftruncate failed")
  835. return extdef([int, r_longlong], s_None,
  836. llimpl = ftruncate_llimpl,
  837. export_name = "ll_os.ll_os_ftruncate")
  838. @registering_if(os, 'fsync')
  839. def register_os_fsync(self):
  840. if not _WIN32:
  841. os_fsync = self.llexternal('fsync', [rffi.INT], rffi.INT)
  842. else:
  843. os_fsync = self.llexternal('_commit', [rffi.INT], rffi.INT)
  844. def fsync_llimpl(fd):
  845. res = rffi.cast(rffi.LONG, os_fsync(rffi.cast(rffi.INT, fd)))
  846. if res < 0:
  847. raise OSError(rposix.get_errno(), "fsync failed")
  848. return extdef([int], s_None,
  849. llimpl=fsync_llimpl,
  850. export_name="ll_os.ll_os_fsync")
  851. @registering_if(os, 'fdatasync')
  852. def register_os_fdatasync(self):
  853. os_fdatasync = self.llexternal('fdatasync', [rffi.INT], rffi.INT)
  854. def fdatasync_llimpl(fd):
  855. res = rffi.cast(rffi.LONG, os_fdatasync(rffi.cast(rffi.INT, fd)))
  856. if res < 0:
  857. raise OSError(rposix.get_errno(), "fdatasync failed")
  858. return extdef([int], s_None,
  859. llimpl=fdatasync_llimpl,
  860. export_name="ll_os.ll_os_fdatasync")
  861. @registering_if(os, 'fchdir')
  862. def register_os_fchdir(self):
  863. os_fchdir = self.llexternal('fchdir', [rffi.INT], rffi.INT)
  864. def fchdir_llimpl(fd):
  865. res = rffi.cast(rffi.LONG, os_fchdir(rffi.cast(rffi.INT, fd)))
  866. if res < 0:
  867. raise OSError(rposix.get_errno(), "fchdir failed")
  868. return extdef([int], s_None,
  869. llimpl=fchdir_llimpl,
  870. export_name="ll_os.ll_os_fchdir")
  871. @registering_str_unicode(os.access)
  872. def register_os_access(self, traits):
  873. os_access = self.llexternal(traits.posix_function_name('access'),
  874. [traits.CCHARP, rffi.INT],
  875. rffi.INT)
  876. if sys.platform.startswith('win'):
  877. # All files are executable on Windows
  878. def access_llimpl(path, mode):
  879. mode = mode & ~os.X_OK
  880. error = rffi.cast(lltype.Signed, os_access(path, mode))
  881. return error == 0
  882. else:
  883. def access_llimpl(path, mode):
  884. error = rffi.cast(lltype.Signed, os_access(path, mode))
  885. return error == 0
  886. def os_access_oofakeimpl(path, mode):
  887. return os.access(OOSupport.from_rstr(path), mode)
  888. return extdef([traits.str0, int], s_Bool, llimpl=access_llimpl,
  889. export_name=traits.ll_os_name("access"),
  890. oofakeimpl=os_access_oofakeimpl)
  891. @registering_str_unicode(getattr(posix, '_getfullpathname', None),
  892. condition=sys.platform=='win32')
  893. def register_posix__getfullpathname(self, traits):
  894. # this nt function is not exposed via os, but needed
  895. # to get a correct implementation of os.abspath
  896. from pypy.rpython.module.ll_win32file import make_getfullpathname_impl
  897. getfullpathname_llimpl = make_getfullpathname_impl(traits)
  898. return extdef([traits.str0], # a single argument which is a str
  899. traits.str0, # returns a string
  900. traits.ll_os_name('_getfullpathname'),
  901. llimpl=getfullpathname_llimpl)
  902. @registering(os.getcwd)
  903. def register_os_getcwd(self):
  904. os_getcwd = self.llexternal(underscore_on_windows + 'getcwd',
  905. [rffi.CCHARP, rffi.SIZE_T],
  906. rffi.CCHARP)
  907. def os_getcwd_llimpl():
  908. bufsize = 256
  909. while True:
  910. buf = lltype.malloc(rffi.CCHARP.TO, bufsize, flavor='raw')
  911. res = os_getcwd(buf, rffi.cast(rffi.SIZE_T, bufsize))
  912. if res:
  913. break # ok
  914. error = rposix.get_errno()
  915. lltype.free(buf, flavor='raw')
  916. if error != errno.ERANGE:
  917. raise OSError(error, "getcwd failed")
  918. # else try again with a larger buffer, up to some sane limit
  919. bufsize *= 4
  920. if bufsize > 1024*1024: # xxx hard-coded upper limit
  921. raise OSError(error, "getcwd result too large")
  922. result = rffi.charp2str(res)
  923. lltype.free(buf, flavor='raw')
  924. return result
  925. def os_getcwd_oofakeimpl():
  926. return OOSupport.to_rstr(os.getcwd())
  927. return extdef([], str,
  928. "ll_os.ll_os_getcwd", llimpl=os_getcwd_llimpl,
  929. oofakeimpl=os_getcwd_oofakeimpl)
  930. @registering(os.getcwdu, condition=sys.platform=='win32')
  931. def register_os_getcwdu(self):
  932. os_wgetcwd = self.llexternal(underscore_on_windows + 'wgetcwd',
  933. [rffi.CWCHARP, rffi.SIZE_T],
  934. rffi.CWCHARP)
  935. def os_getcwd_llimpl():
  936. bufsize = 256
  937. while True:
  938. buf = lltype.malloc(rffi.CWCHARP.TO, bufsize, flavor='raw')
  939. res = os_wgetcwd(buf, rffi.cast(rffi.SIZE_T, bufsize))
  940. if res:
  941. break # ok
  942. error = rposix.get_errno()
  943. lltype.free(buf, flavor='raw')
  944. if error != errno.ERANGE:
  945. raise OSError(error, "getcwd failed")
  946. # else try again with a larger buffer, up to some sane limit
  947. bufsize *= 4
  948. if bufsize > 1024*1024: # xxx hard-coded upper limit
  949. raise OSError(error, "getcwd result too large")
  950. result = rffi.wcharp2unicode(res)
  951. lltype.free(buf, flavor='raw')
  952. return result
  953. return extdef([], unicode,
  954. "ll_os.ll_os_wgetcwd", llimpl=os_getcwd_llimpl)
  955. @registering_str_unicode(os.listdir)
  956. def register_os_listdir(self, traits):
  957. # we need a different approach on Windows and on Posix
  958. if sys.platform.startswith('win'):
  959. from pypy.rpython.module.ll_win32file import make_listdir_impl
  960. os_listdir_llimpl = make_listdir_impl(traits)
  961. else:
  962. assert traits.str is str
  963. compilation_info = ExternalCompilationInfo(
  964. includes = ['sys/types.h', 'dirent.h']
  965. )
  966. class CConfig:
  967. _compilation_info_ = compilation_info
  968. DIRENT = platform.Struct('struct dirent',
  969. [('d_name', lltype.FixedSizeArray(rffi.CHAR, 1))])
  970. DIRP = rffi.COpaquePtr('DIR')
  971. config = platform.configure(CConfig)
  972. DIRENT = config['DIRENT']
  973. DIRENTP = lltype.Ptr(DIRENT)
  974. os_opendir = self.llexternal('opendir', [rffi.CCHARP], DIRP,
  975. compilation_info=compilation_info)
  976. os_readdir = self.llexternal('readdir', [DIRP], DIRENTP,
  977. compilation_info=compilation_info)
  978. os_closedir = self.llexternal('closedir', [DIRP], rffi.INT,
  979. compilation_info=compilation_info)
  980. def os_listdir_llimpl(path):
  981. dirp = os_opendir(path)
  982. if not dirp:
  983. raise OSError(rposix.get_errno(), "os_opendir failed")
  984. rposix.set_errno(0)
  985. result = []
  986. while True:
  987. direntp = os_readdir(dirp)
  988. if not direntp:
  989. error = rposix.get_errno()
  990. break
  991. namep = rffi.cast(rffi.CCHARP, direntp.c_d_name)
  992. name = rffi.charp2str(namep)
  993. if name != '.' and name != '..':
  994. result.append(name)
  995. os_closedir(dirp)
  996. if error:
  997. raise OSError(error, "os_readdir failed")
  998. return result
  999. return extdef([traits.str0], # a single argument which is a str
  1000. [traits.str0], # returns a list of strings
  1001. traits.ll_os_name('listdir'),
  1002. llimpl=os_listdir_llimpl)
  1003. @registering(os.pipe)
  1004. def register_os_pipe(self):
  1005. # we need a different approach on Windows and on Posix
  1006. if sys.platform.startswith('win'):
  1007. from pypy.rlib import rwin32
  1008. CreatePipe = self.llexternal('CreatePipe', [rwin32.LPHANDLE,
  1009. rwin32.LPHANDLE,
  1010. rffi.VOIDP,
  1011. rwin32.DWORD],
  1012. rwin32.BOOL)
  1013. _open_osfhandle = self.llexternal('_open_osfhandle', [rffi.INTPTR_T,
  1014. rffi.INT],
  1015. rffi.INT)
  1016. null = lltype.nullptr(rffi.VOIDP.TO)
  1017. def os_pipe_llimpl():
  1018. pread = lltype.malloc(rwin32.LPHANDLE.TO, 1, flavor='raw')
  1019. pwrite = lltype.malloc(rwin32.LPHANDLE.TO, 1, flavor='raw')
  1020. ok = CreatePipe(pread, pwrite, null, 0)
  1021. if ok:
  1022. error = 0
  1023. else:
  1024. error = rwin32.GetLastError()
  1025. hread = rffi.cast(rffi.INTPTR_T, pread[0])
  1026. hwrite = rffi.cast(rffi.INTPTR_T, pwrite[0])
  1027. lltype.free(pwrite, flavor='raw')
  1028. lltype.free(pread, flavor='raw')
  1029. if error:
  1030. raise WindowsError(error, "os_pipe failed")
  1031. fdread = _open_osfhandle(hread, 0)
  1032. fdwrite = _open_osfhandle(hwrite, 1)
  1033. return (fdread, fdwrite)
  1034. else:
  1035. INT_ARRAY_P = rffi.CArrayPtr(rffi.INT)
  1036. os_pipe = self.llexternal('pipe', [INT_ARRAY_P], rffi.INT)
  1037. def os_pipe_llimpl():
  1038. filedes = lltype.malloc(INT_ARRAY_P.TO, 2, flavor='raw')
  1039. error = rffi.cast(lltype.Signed, os_pipe(filedes))
  1040. read_fd = filedes[0]
  1041. write_fd = filedes[1]
  1042. lltype.free(filedes, flavor='raw')
  1043. if error != 0:
  1044. raise OSError(rposix.get_errno(), "os_pipe failed")
  1045. return (rffi.cast(lltype.Signed, read_fd),
  1046. rffi.cast(lltype.Signed, write_fd))
  1047. return extdef([], (int, int),
  1048. "ll_os.ll_os_pipe",
  1049. llimpl=os_pipe_llimpl)
  1050. @registering_if(os, 'chown')
  1051. def register_os_chown(self):
  1052. os_chown = self.llexternal('chown', [rffi.CCHARP, rffi.INT, rffi.INT],
  1053. rffi.INT)
  1054. def os_chown_llimpl(path, uid, gid):
  1055. res = os_chown(path, uid, gid)
  1056. if res == -1:
  1057. raise OSError(rposix.get_errno(), "os_chown failed")
  1058. return extdef([str0, int, int], None, "ll_os.ll_os_chown",
  1059. llimpl=os_chown_llimpl)
  1060. @registering_if(os, 'lchown')
  1061. def register_os_lchown(self):
  1062. os_lchown = self.llexternal('lchown',[rffi.CCHARP, rffi.INT, rffi.INT],
  1063. rffi.INT)
  1064. def os_lchown_llimpl(path, uid, gid):
  1065. res = os_lchown(path, uid, gid)
  1066. if res == -1:
  1067. raise OSError(rposix.get_errno(), "os_lchown failed")
  1068. return extdef([str0, int, int], None, "ll_os.ll_os_lchown",
  1069. llimpl=os_lchown_llimpl)
  1070. @registering_if(os, 'readlink')
  1071. def register_os_readlink(self):
  1072. os_readlink = self.llexternal('readlink',
  1073. [rffi.CCHARP, rffi.CCHARP, rffi.SIZE_T],
  1074. rffi.INT)
  1075. # XXX SSIZE_T in POSIX.1-2001
  1076. def os_readlink_llimpl(path):
  1077. bufsize = 1023
  1078. while True:
  1079. l_path = rffi.str2charp(path)
  1080. buf = lltype.malloc(rffi.CCHARP.TO, bufsize,
  1081. flavor='raw')
  1082. res = rffi.cast(lltype.Signed, os_readlink(l_path, buf, bufsize))
  1083. lltype.free(l_path, flavor='raw')
  1084. if res < 0:
  1085. error = rposix.get_errno() # failed
  1086. lltype.free(buf, flavor='raw')
  1087. raise OSError(error, "readlink failed")
  1088. elif res < bufsize:
  1089. break # ok
  1090. else:
  1091. # buf too small, try again with a larger buffer
  1092. lltype.free(buf, flavor='raw')
  1093. bufsize *= 4
  1094. # convert the result to a string
  1095. result = rffi.charp2strn(buf, res)
  1096. lltype.free(buf, flavor='raw')
  1097. return result
  1098. return extdef([str0], str0,
  1099. "ll_os.ll_os_readlink",
  1100. llimpl=os_readlink_llimpl)
  1101. @registering(os.waitpid)
  1102. def register_os_waitpid(self):
  1103. if sys.platform.startswith('win'):
  1104. # emulate waitpid() with the _cwait() of Microsoft's compiler
  1105. os__cwait = self.llexternal('_cwait',
  1106. [rffi.INTP, rffi.PID_T, rffi.INT],
  1107. rffi.PID_T)
  1108. def os_waitpid(pid, status_p, options):
  1109. result = os__cwait(status_p, pid, options)
  1110. # shift the status left a byte so this is more
  1111. # like the POSIX waitpid
  1112. status_p[0] <<= 8
  1113. return result
  1114. else:
  1115. # Posix
  1116. os_waitpid = self.llexternal('waitpid',
  1117. [rffi.PID_T, rffi.INTP, rffi.INT],
  1118. rffi.PID_T)
  1119. def os_waitpid_llimpl(pid, options):
  1120. status_p = lltype.malloc(rffi.INTP.TO, 1, flavor='raw')
  1121. status_p[0] = rffi.cast(rffi.INT, 0)
  1122. result = os_waitpid(rffi.cast(rffi.PID_T, pid),
  1123. status_p,
  1124. rffi.cast(rffi.INT, options))
  1125. result = rffi.cast(lltype.Signed, result)
  1126. status = status_p[0]
  1127. lltype.free(status_p, flavor='raw')
  1128. if result == -1:
  1129. raise OSError(rposix.get_errno(), "os_waitpid failed")
  1130. return (rffi.cast(lltype.Signed, result),
  1131. rffi.cast(lltype.Signed, status))
  1132. return extdef([int, int], (int, int),
  1133. "ll_os.ll_os_waitpid",
  1134. llimpl=os_waitpid_llimpl)
  1135. @registering(os.isatty)
  1136. def register_os_isatty(self):
  1137. os_isatty = self.llexternal(underscore_on_windows+'isatty', [rffi.INT], rffi.INT)
  1138. def isatty_llimpl(fd):
  1139. res = rffi.cast(rffi.LONG, os_isatty(rffi.cast(rffi.INT, fd)))
  1140. return res != 0
  1141. return extdef([int], bool, llimpl=isatty_llimpl,
  1142. export_name="ll_os.ll_os_isatty")
  1143. @registering(os.strerror)
  1144. def register_os_strerror(self):
  1145. os_strerror = self.llexternal('strerror', [rffi.INT], rffi.CCHARP)
  1146. def strerror_llimpl(errnum):
  1147. res = os_strerror(rffi.cast(rffi.INT, errnum))
  1148. if not res:
  1149. raise ValueError("os_strerror failed")
  1150. return rffi.charp2str(res)
  1151. return extdef([int], str, llimpl=strerror_llimpl,
  1152. export_name="ll_os.ll_os_strerror")
  1153. @registering(os.system)
  1154. def register_os_system(self):
  1155. os_system = self.llexternal('system', [rffi.CCHARP], rffi.INT)
  1156. def system_llimpl(command):
  1157. res = os_system(command)
  1158. return rffi.cast(lltype.Signed, res)
  1159. return extdef([str0], int, llimpl=system_llimpl,
  1160. export_name="ll_os.ll_os_system")
  1161. @registering_str_unicode(os.unlink)
  1162. def register_os_unlink(self, traits):
  1163. os_unlink = self.llexternal(traits.posix_function_name('unlink'),
  1164. [traits.CCHARP], rffi.INT)
  1165. def unlink_llimpl(pathname):
  1166. res = rffi.cast(lltype.Signed, os_unlink(pathname))
  1167. if res < 0:
  1168. raise OSError(rposix.get_errno(), "os_unlink failed")
  1169. if sys.platform == 'win32':
  1170. from pypy.rpython.module.ll_win32file import make_win32_traits
  1171. win32traits = make_win32_traits(traits)
  1172. @func_renamer('unlink_llimpl_%s' % traits.str.__name__)
  1173. def unlink_llimpl(path):
  1174. if not win32traits.DeleteFile(path):
  1175. raise rwin32.lastWindowsError()
  1176. return extdef([traits.str0], s_None, llimpl=unlink_llimpl,
  1177. export_name=traits.ll_os_name('unlink'))
  1178. @registering_str_unicode(os.chdir)
  1179. def register_os_chdir(self, traits):
  1180. os_chdir = self.llexternal(traits.posix_function_name('chdir'),
  1181. [traits.CCHARP], rffi.INT)
  1182. def os_chdir_llimpl(path):
  1183. res = rffi.cast(lltype.Signed, os_chdir(path))
  1184. if res < 0:
  1185. raise OSError(rposix.get_errno(), "os_chdir failed")
  1186. # On Windows, use an implementation that will produce Win32 errors
  1187. if sys.platform == 'win32':
  1188. from pypy.rpython.module.ll_win32file import make_chdir_impl
  1189. os_chdir_llimpl = make_chdir_impl(traits)
  1190. return extdef([traits.str0], s_None, llimpl=os_chdir_llimpl,
  1191. export_name=traits.ll_os_name('chdir'))
  1192. @registering_str_unicode(os.mkdir)
  1193. def register_os_mkdir(self, traits):
  1194. os_mkdir = self.llexternal(traits.posix_function_name('mkdir'),
  1195. [traits.CCHARP, rffi.MODE_T], rffi.INT)
  1196. if sys.platform == 'win32':
  1197. from pypy.rpython.module.ll_win32file import make_win32_traits
  1198. win32traits = make_win32_traits(traits)
  1199. @func_renamer('mkdir_llimpl_%s' % traits.str.__name__)
  1200. def os_mkdir_llimpl(path, mode):
  1201. if not win32traits.CreateDirectory(path, None):
  1202. raise rwin32.lastWindowsError()
  1203. else:
  1204. def os_mkdir_llimpl(pathname, mode):
  1205. res = os_mkdir(pathname, mode)
  1206. res = rffi.cast(lltype.Signed, res)
  1207. if res < 0:
  1208. raise OSError(rposix.get_errno(), "os_mkdir failed")
  1209. return extdef([traits.str0, int], s_None, llimpl=os_mkdir_llimpl,
  1210. export_name=traits.ll_os_name('mkdir'))
  1211. @registering_str_unicode(os.rmdir)
  1212. def register_os_rmdir(self, traits):
  1213. os_rmdir = self.llexternal(traits.posix_function_name('rmdir'),
  1214. [traits.CCHARP], rffi.INT)
  1215. def rmdir_llimpl(pathname):
  1216. res = rffi.cast(lltype.Signed, os_rmdir(pathname))
  1217. if res < 0:
  1218. raise OSError(rposix.get_errno(), "os_rmdir failed")
  1219. return extdef([traits.str0], s_None, llimpl=rmdir_llimpl,
  1220. export_name=traits.ll_os_name('rmdir'))
  1221. @registering_str_unicode(os.chmod)
  1222. def register_os_chmod(self, traits):
  1223. os_chmod = self.llexternal(traits.posix_function_name('chmod'),
  1224. [traits.CCHARP, rffi.MODE_T], rffi.INT)
  1225. def chmod_llimpl(path, mode):
  1226. res = rffi.cast(lltype.Signed, os_chmod(path, rffi.cast(rffi.MODE_T, mode)))
  1227. if res < 0:
  1228. raise OSError(rposix.get_errno(), "os_chmod failed")
  1229. if sys.platform == 'win32':
  1230. from pypy.rpython.module.ll_win32file import make_chmod_impl
  1231. chmod_llimpl = make_chmod_impl(traits)
  1232. return extdef([traits.str0, int], s_None, llimpl=chmod_llimpl,
  1233. export_name=traits.ll_os_name('chmod'))
  1234. @registering_str_unicode(os.rename)
  1235. def register_os_rename(self, traits):
  1236. os_rename = self.llexternal(traits.posix_function_name('rename'),
  1237. [traits.CCHARP, traits.CCHARP], rffi.INT)
  1238. def rename_llimpl(oldpath, newpath):
  1239. res = rffi.cast(lltype.Signed, os_rename(oldpath, newpath))
  1240. if res < 0:
  1241. raise OSError(rposix.get_errno(), "os_rename failed")
  1242. if sys.platform == 'win32':
  1243. from pypy.rpython.module.ll_win32file import make_win32_traits
  1244. win32traits = make_win32_traits(traits)
  1245. @func_renamer('rename_llimpl_%s' % traits.str.__name__)
  1246. def rename_llimpl(oldpath, newpath):
  1247. if not win32traits.MoveFile(oldpath, newpath):
  1248. raise rwin32.lastWindowsError()
  1249. return extdef([traits.str0, traits.str0], s_None, llimpl=rename_llimpl,
  1250. export_name=traits.ll_os_name('rename'))
  1251. @registering_str_unicode(getattr(os, 'mkfifo', None))
  1252. def register_os_mkfifo(self, traits):
  1253. os_mkfifo = self.llexternal(traits.posix_function_name('mkfifo'),
  1254. [traits.CCHARP, rffi.MODE_T], rffi.INT)
  1255. def mkfifo_llimpl(path, mode):
  1256. res = rffi.cast(lltype.Signed, os_mkfifo(path, mode))
  1257. if res < 0:
  1258. raise OSError(rposix.get_errno(), "os_mkfifo failed")
  1259. return extdef([traits.str0, int], s_None, llimpl=mkfifo_llimpl,
  1260. export_name=traits.ll_os_name('mkfifo'))
  1261. @registering_str_unicode(getattr(os, 'mknod', None))
  1262. def register_os_mknod(self, traits):
  1263. os_mknod = self.llexternal(traits.posix_function_name('mknod'),
  1264. [traits.CCHARP, rffi.MODE_T, rffi.INT],
  1265. rffi.INT) # xxx: actually ^^^ dev_t
  1266. def mknod_llimpl(path, mode, dev):
  1267. res = rffi.cast(lltype.Signed, os_mknod(path, mode, dev))
  1268. if res < 0:
  1269. raise OSError(rposix.get_errno(), "os_mknod failed")
  1270. return extdef([traits.str0, int, int], s_None, llimpl=mknod_llimpl,
  1271. export_name=traits.ll_os_name('mknod'))
  1272. @registering(os.umask)
  1273. def register_os_umask(self):
  1274. os_umask = self.llexternal(underscore_on_windows+'umask', [rffi.MODE_T], rffi.MODE_T)
  1275. def umask_llimpl(fd):
  1276. res = os_umask(rffi.cast(rffi.MODE_T, fd))
  1277. return rffi.cast(lltype.Signed, res)
  1278. return extdef([int], int, llimpl=umask_llimpl,
  1279. export_name="ll_os.ll_os_umask")
  1280. @registering_if(os, 'kill', sys.platform != 'win32')
  1281. def register_os_kill(self):
  1282. os_kill = self.llexternal('kill', [rffi.PID_T, rffi.INT],
  1283. rffi.INT)
  1284. def kill_llimpl(pid, sig):
  1285. res = rffi.cast(lltype.Signed, os_kill(rffi.cast(rffi.PID_T, pid),
  1286. rffi.cast(rffi.INT, sig)))
  1287. if res < 0:
  1288. raise OSError(rposix.get_errno(), "os_kill failed")
  1289. return extdef([int, int], s_None, llimpl=kill_llimpl,
  1290. export_name="ll_os.ll_os_kill")
  1291. @registering_if(os, 'killpg')
  1292. def register_os_killpg(self):
  1293. os_killpg = self.llexternal('killpg', [rffi.INT, rffi.INT],
  1294. rffi.INT)
  1295. def killpg_llimpl(pid, sig):
  1296. res = rffi.cast(lltype.Signed, os_killpg(rffi.cast(rffi.INT, pid),
  1297. rffi.cast(rffi.INT, sig)))
  1298. if res < 0:
  1299. raise OSError(rposix.get_errno(), "os_killpg failed")
  1300. return extdef([int, int], s_None, llimpl=killpg_llimpl,
  1301. export_name="ll_os.ll_os_killpg")
  1302. @registering_if(os, 'link')
  1303. def register_os_link(self):
  1304. os_link = self.llexternal('link', [rffi.CCHARP, rffi.CCHARP],
  1305. rffi.INT)
  1306. def link_llimpl(oldpath, newpath):
  1307. res = rffi.cast(lltype.Signed, os_link(oldpath, newpath))
  1308. if res < 0:
  1309. raise OSError(rposix.get_errno(), "os_link failed")
  1310. return extdef([str0, str0], s_None, llimpl=link_llimpl,
  1311. export_name="ll_os.ll_os_link")
  1312. @registering_if(os, 'symlink')
  1313. def register_os_symlink(self):
  1314. os_symlink = self.llexternal('symlink', [rffi.CCHARP, rffi.CCHARP],
  1315. rffi.INT)
  1316. def symlink_llimpl(oldpath, newpath):
  1317. res = rffi.cast(lltype.Signed, os_symlink(oldpath, newpath))
  1318. if res < 0:
  1319. raise OSError(rposix.get_errno(), "os_symlink failed")
  1320. return extdef([str0, str0], s_None, llimpl=symlink_llimpl,
  1321. export_name="ll_os.ll_os_symlink")
  1322. @registering_if(os, 'fork')
  1323. def register_os_fork(self):
  1324. from pypy.module.thread import ll_thread
  1325. eci = self.gcc_profiling_bug_workaround('pid_t _noprof_fork(void)',
  1326. 'return fork();')
  1327. os_fork = self.llexternal('_noprof_fork', [], rffi.PID_T,
  1328. compilation_info = eci,
  1329. _nowrapper = True)
  1330. def fork_llimpl():
  1331. opaqueaddr = ll_thread.gc_thread_before_fork()
  1332. childpid = rffi.cast(lltype.Signed, os_fork())
  1333. ll_thread.gc_thread_after_fork(childpid, opaqueaddr)
  1334. if childpid == -1:
  1335. raise OSError(rposix.get_errno(), "os_fork failed")
  1336. return rffi.cast(lltype.Signed, childpid)
  1337. return extdef([], int, llimpl=fork_llimpl,
  1338. export_name="ll_os.ll_os_fork")
  1339. @registering_if(os, 'openpty')
  1340. def register_os_openpty(self):
  1341. os_openpty = self.llexternal(
  1342. 'openpty',
  1343. [rffi.INTP, rffi.INTP, rffi.VOIDP, rffi.VOIDP, rffi.VOIDP],
  1344. rffi.INT,
  1345. compilation_info=ExternalCompilationInfo(libraries=['util']))
  1346. def openpty_llimpl():
  1347. master_p = lltype.malloc(rffi.INTP.TO, 1, flavor='raw')
  1348. slave_p = lltype.malloc(rffi.INTP.T