PageRenderTime 33ms CodeModel.GetById 28ms RepoModel.GetById 0ms app.codeStats 1ms

/pypy/rpython/module/ll_os.py

http://github.com/pypy/pypy
Python | 1809 lines | 1805 code | 2 blank | 2 comment | 3 complexity | de7f63ef290f95f1f3816c7456f20203 MD5 | raw file
  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 in (unicode, unicode0):
  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, unicode0, 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.SIGNED, 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.SIGNED, 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.SIGNED, 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.SIGNED, 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.SIGNED, 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. rposix.validate_fd(fd)
  326. newfd = rffi.cast(lltype.Signed, os_dup(rffi.cast(rffi.INT, fd)))
  327. if newfd == -1:
  328. raise OSError(rposix.get_errno(), "dup failed")
  329. return newfd
  330. return extdef([int], int, llimpl=dup_llimpl,
  331. export_name="ll_os.ll_os_dup", oofakeimpl=os.dup)
  332. @registering(os.dup2)
  333. def register_os_dup2(self):
  334. os_dup2 = self.llexternal(underscore_on_windows+'dup2',
  335. [rffi.INT, rffi.INT], rffi.INT)
  336. def dup2_llimpl(fd, newfd):
  337. rposix.validate_fd(fd)
  338. error = rffi.cast(lltype.Signed, os_dup2(rffi.cast(rffi.INT, fd),
  339. rffi.cast(rffi.INT, newfd)))
  340. if error == -1:
  341. raise OSError(rposix.get_errno(), "dup2 failed")
  342. return extdef([int, int], s_None, llimpl=dup2_llimpl,
  343. export_name="ll_os.ll_os_dup2")
  344. @registering_if(os, "getlogin", condition=not _WIN32)
  345. def register_os_getlogin(self):
  346. os_getlogin = self.llexternal('getlogin', [], rffi.CCHARP)
  347. def getlogin_llimpl():
  348. result = os_getlogin()
  349. if not result:
  350. raise OSError(rposix.get_errno(), "getlogin failed")
  351. return rffi.charp2str(result)
  352. return extdef([], str, llimpl=getlogin_llimpl,
  353. export_name="ll_os.ll_os_getlogin")
  354. @registering_str_unicode(os.utime)
  355. def register_os_utime(self, traits):
  356. UTIMBUFP = lltype.Ptr(self.UTIMBUF)
  357. os_utime = self.llexternal('utime', [rffi.CCHARP, UTIMBUFP], rffi.INT)
  358. if not _WIN32:
  359. includes = ['sys/time.h']
  360. else:
  361. includes = ['time.h']
  362. class CConfig:
  363. _compilation_info_ = ExternalCompilationInfo(
  364. includes=includes
  365. )
  366. HAVE_UTIMES = platform.Has('utimes')
  367. config = platform.configure(CConfig)
  368. # XXX note that on Windows, calls to os.utime() are ignored on
  369. # directories. Remove that hack over there once it's fixed here!
  370. if config['HAVE_UTIMES']:
  371. class CConfig:
  372. if not _WIN32:
  373. _compilation_info_ = ExternalCompilationInfo(
  374. includes = includes
  375. )
  376. else:
  377. _compilation_info_ = ExternalCompilationInfo(
  378. includes = ['time.h']
  379. )
  380. TIMEVAL = platform.Struct('struct timeval', [('tv_sec', rffi.LONG),
  381. ('tv_usec', rffi.LONG)])
  382. config = platform.configure(CConfig)
  383. TIMEVAL = config['TIMEVAL']
  384. TIMEVAL2P = rffi.CArrayPtr(TIMEVAL)
  385. os_utimes = self.llexternal('utimes', [rffi.CCHARP, TIMEVAL2P],
  386. rffi.INT, compilation_info=CConfig._compilation_info_)
  387. def os_utime_platform(path, actime, modtime):
  388. import math
  389. l_times = lltype.malloc(TIMEVAL2P.TO, 2, flavor='raw')
  390. fracpart, intpart = math.modf(actime)
  391. rffi.setintfield(l_times[0], 'c_tv_sec', int(intpart))
  392. rffi.setintfield(l_times[0], 'c_tv_usec', int(fracpart * 1E6))
  393. fracpart, intpart = math.modf(modtime)
  394. rffi.setintfield(l_times[1], 'c_tv_sec', int(intpart))
  395. rffi.setintfield(l_times[1], 'c_tv_usec', int(fracpart * 1E6))
  396. error = os_utimes(path, l_times)
  397. lltype.free(l_times, flavor='raw')
  398. return error
  399. else:
  400. # we only have utime(), which does not allow sub-second resolution
  401. def os_utime_platform(path, actime, modtime):
  402. l_utimbuf = lltype.malloc(UTIMBUFP.TO, flavor='raw')
  403. l_utimbuf.c_actime = rffi.r_time_t(actime)
  404. l_utimbuf.c_modtime = rffi.r_time_t(modtime)
  405. error = os_utime(path, l_utimbuf)
  406. lltype.free(l_utimbuf, flavor='raw')
  407. return error
  408. # NB. this function is specialized; we get one version where
  409. # tp is known to be None, and one version where it is known
  410. # to be a tuple of 2 floats.
  411. if not _WIN32:
  412. assert traits.str is str
  413. @specialize.argtype(1)
  414. def os_utime_llimpl(path, tp):
  415. if tp is None:
  416. error = os_utime(path, lltype.nullptr(UTIMBUFP.TO))
  417. else:
  418. actime, modtime = tp
  419. error = os_utime_platform(path, actime, modtime)
  420. error = rffi.cast(lltype.Signed, error)
  421. if error == -1:
  422. raise OSError(rposix.get_errno(), "os_utime failed")
  423. else:
  424. from pypy.rpython.module.ll_win32file import make_utime_impl
  425. os_utime_llimpl = make_utime_impl(traits)
  426. s_tuple_of_2_floats = SomeTuple([SomeFloat(), SomeFloat()])
  427. def os_utime_normalize_args(s_path, s_times):
  428. # special handling of the arguments: they can be either
  429. # [str, (float, float)] or [str, s_None], and get normalized
  430. # to exactly one of these two.
  431. if not traits.str0.contains(s_path):
  432. raise Exception("os.utime() arg 1 must be a string, got %s" % (
  433. s_path,))
  434. case1 = s_None.contains(s_times)
  435. case2 = s_tuple_of_2_floats.contains(s_times)
  436. if case1 and case2:
  437. return [traits.str0, s_ImpossibleValue] #don't know which case yet
  438. elif case1:
  439. return [traits.str0, s_None]
  440. elif case2:
  441. return [traits.str0, s_tuple_of_2_floats]
  442. else:
  443. raise Exception("os.utime() arg 2 must be None or a tuple of "
  444. "2 floats, got %s" % (s_times,))
  445. os_utime_normalize_args._default_signature_ = [traits.str0, None]
  446. return extdef(os_utime_normalize_args, s_None,
  447. "ll_os.ll_os_utime",
  448. llimpl=os_utime_llimpl)
  449. @registering(os.times)
  450. def register_os_times(self):
  451. if sys.platform.startswith('win'):
  452. from pypy.rlib import rwin32
  453. GetCurrentProcess = self.llexternal('GetCurrentProcess', [],
  454. rwin32.HANDLE)
  455. GetProcessTimes = self.llexternal('GetProcessTimes',
  456. [rwin32.HANDLE,
  457. lltype.Ptr(rwin32.FILETIME),
  458. lltype.Ptr(rwin32.FILETIME),
  459. lltype.Ptr(rwin32.FILETIME),
  460. lltype.Ptr(rwin32.FILETIME)],
  461. rwin32.BOOL)
  462. def times_lltypeimpl():
  463. pcreate = lltype.malloc(rwin32.FILETIME, flavor='raw')
  464. pexit = lltype.malloc(rwin32.FILETIME, flavor='raw')
  465. pkernel = lltype.malloc(rwin32.FILETIME, flavor='raw')
  466. puser = lltype.malloc(rwin32.FILETIME, flavor='raw')
  467. hProc = GetCurrentProcess()
  468. GetProcessTimes(hProc, pcreate, pexit, pkernel, puser)
  469. # The fields of a FILETIME structure are the hi and lo parts
  470. # of a 64-bit value expressed in 100 nanosecond units
  471. # (of course).
  472. result = (rffi.cast(lltype.Signed, pkernel.c_dwHighDateTime) * 429.4967296 +
  473. rffi.cast(lltype.Signed, pkernel.c_dwLowDateTime) * 1E-7,
  474. rffi.cast(lltype.Signed, puser.c_dwHighDateTime) * 429.4967296 +
  475. rffi.cast(lltype.Signed, puser.c_dwLowDateTime) * 1E-7,
  476. 0, 0, 0)
  477. lltype.free(puser, flavor='raw')
  478. lltype.free(pkernel, flavor='raw')
  479. lltype.free(pexit, flavor='raw')
  480. lltype.free(pcreate, flavor='raw')
  481. return result
  482. self.register(os.times, [], (float, float, float, float, float),
  483. "ll_os.ll_times", llimpl=times_lltypeimpl)
  484. return
  485. TMSP = lltype.Ptr(self.TMS)
  486. os_times = self.llexternal('times', [TMSP], self.CLOCK_T)
  487. # Here is a random extra platform parameter which is important.
  488. # Strictly speaking, this should probably be retrieved at runtime, not
  489. # at translation time.
  490. CLOCK_TICKS_PER_SECOND = float(os.sysconf('SC_CLK_TCK'))
  491. def times_lltypeimpl():
  492. l_tmsbuf = lltype.malloc(TMSP.TO, flavor='raw')
  493. try:
  494. result = os_times(l_tmsbuf)
  495. result = rffi.cast(lltype.Signed, result)
  496. if result == -1:
  497. raise OSError(rposix.get_errno(), "times failed")
  498. return (
  499. rffi.cast(lltype.Signed, l_tmsbuf.c_tms_utime)
  500. / CLOCK_TICKS_PER_SECOND,
  501. rffi.cast(lltype.Signed, l_tmsbuf.c_tms_stime)
  502. / CLOCK_TICKS_PER_SECOND,
  503. rffi.cast(lltype.Signed, l_tmsbuf.c_tms_cutime)
  504. / CLOCK_TICKS_PER_SECOND,
  505. rffi.cast(lltype.Signed, l_tmsbuf.c_tms_cstime)
  506. / CLOCK_TICKS_PER_SECOND,
  507. result / CLOCK_TICKS_PER_SECOND)
  508. finally:
  509. lltype.free(l_tmsbuf, flavor='raw')
  510. self.register(os.times, [], (float, float, float, float, float),
  511. "ll_os.ll_times", llimpl=times_lltypeimpl)
  512. @registering_if(os, 'setsid')
  513. def register_os_setsid(self):
  514. os_setsid = self.llexternal('setsid', [], rffi.PID_T)
  515. def setsid_llimpl():
  516. result = rffi.cast(lltype.Signed, os_setsid())
  517. if result == -1:
  518. raise OSError(rposix.get_errno(), "os_setsid failed")
  519. return result
  520. return extdef([], int, export_name="ll_os.ll_os_setsid",
  521. llimpl=setsid_llimpl)
  522. @registering_if(os, 'chroot')
  523. def register_os_chroot(self):
  524. os_chroot = self.llexternal('chroot', [rffi.CCHARP], rffi.INT)
  525. def chroot_llimpl(arg):
  526. result = os_chroot(arg)
  527. if result == -1:
  528. raise OSError(rposix.get_errno(), "os_chroot failed")
  529. return extdef([str0], None, export_name="ll_os.ll_os_chroot",
  530. llimpl=chroot_llimpl)
  531. @registering_if(os, 'uname')
  532. def register_os_uname(self):
  533. CHARARRAY = lltype.FixedSizeArray(lltype.Char, 1)
  534. class CConfig:
  535. _compilation_info_ = ExternalCompilationInfo(
  536. includes = ['sys/utsname.h']
  537. )
  538. UTSNAME = platform.Struct('struct utsname', [
  539. ('sysname', CHARARRAY),
  540. ('nodename', CHARARRAY),
  541. ('release', CHARARRAY),
  542. ('version', CHARARRAY),
  543. ('machine', CHARARRAY)])
  544. config = platform.configure(CConfig)
  545. UTSNAMEP = lltype.Ptr(config['UTSNAME'])
  546. os_uname = self.llexternal('uname', [UTSNAMEP], rffi.INT,
  547. compilation_info=CConfig._compilation_info_)
  548. def uname_llimpl():
  549. l_utsbuf = lltype.malloc(UTSNAMEP.TO, flavor='raw')
  550. result = os_uname(l_utsbuf)
  551. if result == -1:
  552. raise OSError(rposix.get_errno(), "os_uname failed")
  553. retval = (
  554. rffi.charp2str(rffi.cast(rffi.CCHARP, l_utsbuf.c_sysname)),
  555. rffi.charp2str(rffi.cast(rffi.CCHARP, l_utsbuf.c_nodename)),
  556. rffi.charp2str(rffi.cast(rffi.CCHARP, l_utsbuf.c_release)),
  557. rffi.charp2str(rffi.cast(rffi.CCHARP, l_utsbuf.c_version)),
  558. rffi.charp2str(rffi.cast(rffi.CCHARP, l_utsbuf.c_machine)),
  559. )
  560. lltype.free(l_utsbuf, flavor='raw')
  561. return retval
  562. return extdef([], (str, str, str, str, str),
  563. "ll_os.ll_uname", llimpl=uname_llimpl)
  564. @registering_if(os, 'sysconf')
  565. def register_os_sysconf(self):
  566. c_sysconf = self.llexternal('sysconf', [rffi.INT], rffi.LONG)
  567. def sysconf_llimpl(i):
  568. rposix.set_errno(0)
  569. res = c_sysconf(i)
  570. if res == -1:
  571. errno = rposix.get_errno()
  572. if errno != 0:
  573. raise OSError(errno, "sysconf failed")
  574. return res
  575. return extdef([int], int, "ll_os.ll_sysconf", llimpl=sysconf_llimpl)
  576. @registering_if(os, 'fpathconf')
  577. def register_os_fpathconf(self):
  578. c_fpathconf = self.llexternal('fpathconf',
  579. [rffi.INT, rffi.INT], rffi.LONG)
  580. def fpathconf_llimpl(fd, i):
  581. rposix.set_errno(0)
  582. res = c_fpathconf(fd, i)
  583. if res == -1:
  584. errno = rposix.get_errno()
  585. if errno != 0:
  586. raise OSError(errno, "fpathconf failed")
  587. return res
  588. return extdef([int, int], int, "ll_os.ll_fpathconf",
  589. llimpl=fpathconf_llimpl)
  590. @registering_if(os, 'getuid')
  591. def register_os_getuid(self):
  592. return self.extdef_for_os_function_returning_int('getuid')
  593. @registering_if(os, 'geteuid')
  594. def register_os_geteuid(self):
  595. return self.extdef_for_os_function_returning_int('geteuid')
  596. @registering_if(os, 'setuid')
  597. def register_os_setuid(self):
  598. return self.extdef_for_os_function_accepting_int('setuid')
  599. @registering_if(os, 'seteuid')
  600. def register_os_seteuid(self):
  601. return self.extdef_for_os_function_accepting_int('seteuid')
  602. @registering_if(os, 'setgid')
  603. def register_os_setgid(self):
  604. return self.extdef_for_os_function_accepting_int('setgid')
  605. @registering_if(os, 'setegid')
  606. def register_os_setegid(self):
  607. return self.extdef_for_os_function_accepting_int('setegid')
  608. @registering_if(os, 'getpid')
  609. def register_os_getpid(self):
  610. return self.extdef_for_os_function_returning_int('getpid')
  611. @registering_if(os, 'getgid')
  612. def register_os_getgid(self):
  613. return self.extdef_for_os_function_returning_int('getgid')
  614. @registering_if(os, 'getegid')
  615. def register_os_getegid(self):
  616. return self.extdef_for_os_function_returning_int('getegid')
  617. @registering_if(os, 'getgroups')
  618. def register_os_getgroups(self):
  619. GP = rffi.CArrayPtr(self.GID_T)
  620. c_getgroups = self.llexternal('getgroups', [rffi.INT, GP], rffi.INT)
  621. def getgroups_llimpl():
  622. n = c_getgroups(0, lltype.nullptr(GP.TO))
  623. if n >= 0:
  624. groups = lltype.malloc(GP.TO, n, flavor='raw')
  625. try:
  626. n = c_getgroups(n, groups)
  627. result = [groups[i] for i in range(n)]
  628. finally:
  629. lltype.free(groups, flavor='raw')
  630. if n >= 0:
  631. return result
  632. raise OSError(rposix.get_errno(), "os_getgroups failed")
  633. return extdef([], [self.GID_T], llimpl=getgroups_llimpl,
  634. export_name="ll_os.ll_getgroups")
  635. @registering_if(os, 'getpgrp')
  636. def register_os_getpgrp(self):
  637. name = 'getpgrp'
  638. if self.GETPGRP_HAVE_ARG:
  639. c_func = self.llexternal(name, [rffi.INT], rffi.INT)
  640. def c_func_llimpl():
  641. res = rffi.cast(rffi.SIGNED, c_func(0))
  642. if res == -1:
  643. raise OSError(rposix.get_errno(), "%s failed" % name)
  644. return res
  645. c_func_llimpl.func_name = name + '_llimpl'
  646. return extdef([], int, llimpl=c_func_llimpl,
  647. export_name='ll_os.ll_os_' + name)
  648. else:
  649. return self.extdef_for_os_function_returning_int('getpgrp')
  650. @registering_if(os, 'setpgrp')
  651. def register_os_setpgrp(self):
  652. name = 'setpgrp'
  653. if self.SETPGRP_HAVE_ARG:
  654. c_func = self.llexternal(name, [rffi.INT, rffi.INT], rffi.INT)
  655. def c_func_llimpl():
  656. res = rffi.cast(rffi.SIGNED, c_func(0, 0))
  657. if res == -1:
  658. raise OSError(rposix.get_errno(), "%s failed" % name)
  659. c_func_llimpl.func_name = name + '_llimpl'
  660. return extdef([], None, llimpl=c_func_llimpl,
  661. export_name='ll_os.ll_os_' + name)
  662. else:
  663. return self.extdef_for_os_function_accepting_0int(name)
  664. @registering_if(os, 'getppid')
  665. def register_os_getppid(self):
  666. return self.extdef_for_os_function_returning_int('getppid')
  667. @registering_if(os, 'getpgid')
  668. def register_os_getpgid(self):
  669. return self.extdef_for_os_function_int_to_int('getpgid')
  670. @registering_if(os, 'setpgid')
  671. def register_os_setpgid(self):
  672. return self.extdef_for_os_function_accepting_2int('setpgid')
  673. @registering_if(os, 'setreuid')
  674. def register_os_setreuid(self):
  675. return self.extdef_for_os_function_accepting_2int('setreuid')
  676. @registering_if(os, 'setregid')
  677. def register_os_setregid(self):
  678. return self.extdef_for_os_function_accepting_2int('setregid')
  679. @registering_if(os, 'getsid')
  680. def register_os_getsid(self):
  681. return self.extdef_for_os_function_int_to_int('getsid')
  682. @registering_if(os, 'setsid')
  683. def register_os_setsid(self):
  684. return self.extdef_for_os_function_returning_int('setsid')
  685. @registering_str_unicode(os.open)
  686. def register_os_open(self, traits):
  687. os_open = self.llexternal(traits.posix_function_name('open'),
  688. [traits.CCHARP, rffi.INT, rffi.MODE_T],
  689. rffi.INT)
  690. def os_open_llimpl(path, flags, mode):
  691. result = rffi.cast(lltype.Signed, os_open(path, flags, mode))
  692. if result == -1:
  693. raise OSError(rposix.get_errno(), "os_open failed")
  694. return result
  695. def os_open_oofakeimpl(path, flags, mode):
  696. return os.open(OOSupport.from_rstr(path), flags, mode)
  697. return extdef([traits.str0, int, int], int, traits.ll_os_name('open'),
  698. llimpl=os_open_llimpl, oofakeimpl=os_open_oofakeimpl)
  699. @registering_if(os, 'getloadavg')
  700. def register_os_getloadavg(self):
  701. AP = rffi.CArrayPtr(lltype.Float)
  702. c_getloadavg = self.llexternal('getloadavg', [AP, rffi.INT], rffi.INT)
  703. def getloadavg_llimpl():
  704. load = lltype.malloc(AP.TO, 3, flavor='raw')
  705. r = c_getloadavg(load, 3)
  706. result_tuple = load[0], load[1], load[2]
  707. lltype.free(load, flavor='raw')
  708. if r != 3:
  709. raise OSError
  710. return result_tuple
  711. return extdef([], (float, float, float),
  712. "ll_os.ll_getloadavg", llimpl=getloadavg_llimpl)
  713. @registering_if(os, 'makedev')
  714. def register_os_makedev(self):
  715. c_makedev = self.llexternal('makedev', [rffi.INT, rffi.INT], rffi.INT)
  716. def makedev_llimpl(maj, min):
  717. return c_makedev(maj, min)
  718. return extdef([int, int], int,
  719. "ll_os.ll_makedev", llimpl=makedev_llimpl)
  720. @registering_if(os, 'major')
  721. def register_os_major(self):
  722. c_major = self.llexternal('major', [rffi.INT], rffi.INT)
  723. def major_llimpl(dev):
  724. return c_major(dev)
  725. return extdef([int], int,
  726. "ll_os.ll_major", llimpl=major_llimpl)
  727. @registering_if(os, 'minor')
  728. def register_os_minor(self):
  729. c_minor = self.llexternal('minor', [rffi.INT], rffi.INT)
  730. def minor_llimpl(dev):
  731. return c_minor(dev)
  732. return extdef([int], int,
  733. "ll_os.ll_minor", llimpl=minor_llimpl)
  734. # ------------------------------- os.read -------------------------------
  735. @registering(os.read)
  736. def register_os_read(self):
  737. os_read = self.llexternal(underscore_on_windows+'read',
  738. [rffi.INT, rffi.VOIDP, rffi.SIZE_T],
  739. rffi.SIZE_T)
  740. offset = offsetof(STR, 'chars') + itemoffsetof(STR.chars, 0)
  741. def os_read_llimpl(fd, count):
  742. if count < 0:
  743. raise OSError(errno.EINVAL, None)
  744. rposix.validate_fd(fd)
  745. raw_buf, gc_buf = rffi.alloc_buffer(count)
  746. try:
  747. void_buf = rffi.cast(rffi.VOIDP, raw_buf)
  748. got = rffi.cast(lltype.Signed, os_read(fd, void_buf, count))
  749. if got < 0:
  750. raise OSError(rposix.get_errno(), "os_read failed")
  751. return rffi.str_from_buffer(raw_buf, gc_buf, count, got)
  752. finally:
  753. rffi.keep_buffer_alive_until_here(raw_buf, gc_buf)
  754. def os_read_oofakeimpl(fd, count):
  755. return OOSupport.to_rstr(os.read(fd, count))
  756. return extdef([int, int], SomeString(can_be_None=True),
  757. "ll_os.ll_os_read",
  758. llimpl=os_read_llimpl, oofakeimpl=os_read_oofakeimpl)
  759. @registering(os.write)
  760. def register_os_write(self):
  761. os_write = self.llexternal(underscore_on_windows+'write',
  762. [rffi.INT, rffi.VOIDP, rffi.SIZE_T],
  763. rffi.SIZE_T)
  764. def os_write_llimpl(fd, data):
  765. count = len(data)
  766. rposix.validate_fd(fd)
  767. buf = rffi.get_nonmovingbuffer(data)
  768. try:
  769. written = rffi.cast(lltype.Signed, os_write(
  770. rffi.cast(rffi.INT, fd),
  771. buf, rffi.cast(rffi.SIZE_T, count)))
  772. if written < 0:
  773. raise OSError(rposix.get_errno(), "os_write failed")
  774. finally:
  775. rffi.free_nonmovingbuffer(data, buf)
  776. return written
  777. def os_write_oofakeimpl(fd, data):
  778. return os.write(fd, OOSupport.from_rstr(data))
  779. return extdef([int, str], SomeInteger(nonneg=True),
  780. "ll_os.ll_os_write", llimpl=os_write_llimpl,
  781. oofakeimpl=os_write_oofakeimpl)
  782. @registering(os.close)
  783. def register_os_close(self):
  784. os_close = self.llexternal(underscore_on_windows+'close', [rffi.INT],
  785. rffi.INT, threadsafe=False)
  786. def close_llimpl(fd):
  787. rposix.validate_fd(fd)
  788. error = rffi.cast(lltype.Signed, os_close(rffi.cast(rffi.INT, fd)))
  789. if error == -1:
  790. raise OSError(rposix.get_errno(), "close failed")
  791. return extdef([int], s_None, llimpl=close_llimpl,
  792. export_name="ll_os.ll_os_close", oofakeimpl=os.close)
  793. @registering(os.lseek)
  794. def register_os_lseek(self):
  795. if sys.platform.startswith('win'):
  796. funcname = '_lseeki64'
  797. else:
  798. funcname = 'lseek'
  799. if self.SEEK_SET is not None:
  800. SEEK_SET = self.SEEK_SET
  801. SEEK_CUR = self.SEEK_CUR
  802. SEEK_END = self.SEEK_END
  803. else:
  804. SEEK_SET, SEEK_CUR, SEEK_END = 0, 1, 2
  805. if (SEEK_SET, SEEK_CUR, SEEK_END) != (0, 1, 2):
  806. # Turn 0, 1, 2 into SEEK_{SET,CUR,END}
  807. def fix_seek_arg(n):
  808. if n == 0: return SEEK_SET
  809. if n == 1: return SEEK_CUR
  810. if n == 2: return SEEK_END
  811. return n
  812. else:
  813. def fix_seek_arg(n):
  814. return n
  815. os_lseek = self.llexternal(funcname,
  816. [rffi.INT, rffi.LONGLONG, rffi.INT],
  817. rffi.LONGLONG, macro=True)
  818. def lseek_llimpl(fd, pos, how):
  819. rposix.validate_fd(fd)
  820. how = fix_seek_arg(how)
  821. res = os_lseek(rffi.cast(rffi.INT, fd),
  822. rffi.cast(rffi.LONGLONG, pos),
  823. rffi.cast(rffi.INT, how))
  824. res = rffi.cast(lltype.SignedLongLong, res)
  825. if res < 0:
  826. raise OSError(rposix.get_errno(), "os_lseek failed")
  827. return res
  828. def os_lseek_oofakeimpl(fd, pos, how):
  829. res = os.lseek(fd, pos, how)
  830. return r_longlong(res)
  831. return extdef([int, r_longlong, int],
  832. r_longlong,
  833. llimpl = lseek_llimpl,
  834. export_name = "ll_os.ll_os_lseek",
  835. oofakeimpl = os_lseek_oofakeimpl)
  836. @registering_if(os, 'ftruncate')
  837. def register_os_ftruncate(self):
  838. os_ftruncate = self.llexternal('ftruncate',
  839. [rffi.INT, rffi.LONGLONG], rffi.INT)
  840. def ftruncate_llimpl(fd, length):
  841. rposix.validate_fd(fd)
  842. res = rffi.cast(rffi.LONG,
  843. os_ftruncate(rffi.cast(rffi.INT, fd),
  844. rffi.cast(rffi.LONGLONG, length)))
  845. if res < 0:
  846. raise OSError(rposix.get_errno(), "os_ftruncate failed")
  847. return extdef([int, r_longlong], s_None,
  848. llimpl = ftruncate_llimpl,
  849. export_name = "ll_os.ll_os_ftruncate")
  850. @registering_if(os, 'fsync')
  851. def register_os_fsync(self):
  852. if not _WIN32:
  853. os_fsync = self.llexternal('fsync', [rffi.INT], rffi.INT)
  854. else:
  855. os_fsync = self.llexternal('_commit', [rffi.INT], rffi.INT)
  856. def fsync_llimpl(fd):
  857. rposix.validate_fd(fd)
  858. res = rffi.cast(rffi.SIGNED, os_fsync(rffi.cast(rffi.INT, fd)))
  859. if res < 0:
  860. raise OSError(rposix.get_errno(), "fsync failed")
  861. return extdef([int], s_None,
  862. llimpl=fsync_llimpl,
  863. export_name="ll_os.ll_os_fsync")
  864. @registering_if(os, 'fdatasync')
  865. def register_os_fdatasync(self):
  866. os_fdatasync = self.llexternal('fdatasync', [rffi.INT], rffi.INT)
  867. def fdatasync_llimpl(fd):
  868. rposix.validate_fd(fd)
  869. res = rffi.cast(rffi.SIGNED, os_fdatasync(rffi.cast(rffi.INT, fd)))
  870. if res < 0:
  871. raise OSError(rposix.get_errno(), "fdatasync failed")
  872. return extdef([int], s_None,
  873. llimpl=fdatasync_llimpl,
  874. export_name="ll_os.ll_os_fdatasync")
  875. @registering_if(os, 'fchdir')
  876. def register_os_fchdir(self):
  877. os_fchdir = self.llexternal('fchdir', [rffi.INT], rffi.INT)
  878. def fchdir_llimpl(fd):
  879. rposix.validate_fd(fd)
  880. res = rffi.cast(rffi.SIGNED, os_fchdir(rffi.cast(rffi.INT, fd)))
  881. if res < 0:
  882. raise OSError(rposix.get_errno(), "fchdir failed")
  883. return extdef([int], s_None,
  884. llimpl=fchdir_llimpl,
  885. export_name="ll_os.ll_os_fchdir")
  886. @registering_str_unicode(os.access)
  887. def register_os_access(self, traits):
  888. os_access = self.llexternal(traits.posix_function_name('access'),
  889. [traits.CCHARP, rffi.INT],
  890. rffi.INT)
  891. if sys.platform.startswith('win'):
  892. # All files are executable on Windows
  893. def access_llimpl(path, mode):
  894. mode = mode & ~os.X_OK
  895. error = rffi.cast(lltype.Signed, os_access(path, mode))
  896. return error == 0
  897. else:
  898. def access_llimpl(path, mode):
  899. error = rffi.cast(lltype.Signed, os_access(path, mode))
  900. return error == 0
  901. def os_access_oofakeimpl(path, mode):
  902. return os.access(OOSupport.from_rstr(path), mode)
  903. return extdef([traits.str0, int], s_Bool, llimpl=access_llimpl,
  904. export_name=traits.ll_os_name("access"),
  905. oofakeimpl=os_access_oofakeimpl)
  906. @registering_str_unicode(getattr(posix, '_getfullpathname', None),
  907. condition=sys.platform=='win32')
  908. def register_posix__getfullpathname(self, traits):
  909. # this nt function is not exposed via os, but needed
  910. # to get a correct implementation of os.abspath
  911. from pypy.rpython.module.ll_win32file import make_getfullpathname_impl
  912. getfullpathname_llimpl = make_getfullpathname_impl(traits)
  913. return extdef([traits.str0], # a single argument which is a str
  914. traits.str0, # returns a string
  915. traits.ll_os_name('_getfullpathname'),
  916. llimpl=getfullpathname_llimpl)
  917. @registering(os.getcwd)
  918. def register_os_getcwd(self):
  919. os_getcwd = self.llexternal(underscore_on_windows + 'getcwd',
  920. [rffi.CCHARP, rffi.SIZE_T],
  921. rffi.CCHARP)
  922. def os_getcwd_llimpl():
  923. bufsize = 256
  924. while True:
  925. buf = lltype.malloc(rffi.CCHARP.TO, bufsize, flavor='raw')
  926. res = os_getcwd(buf, rffi.cast(rffi.SIZE_T, bufsize))
  927. if res:
  928. break # ok
  929. error = rposix.get_errno()
  930. lltype.free(buf, flavor='raw')
  931. if error != errno.ERANGE:
  932. raise OSError(error, "getcwd failed")
  933. # else try again with a larger buffer, up to some sane limit
  934. bufsize *= 4
  935. if bufsize > 1024*1024: # xxx hard-coded upper limit
  936. raise OSError(error, "getcwd result too large")
  937. result = rffi.charp2str(res)
  938. lltype.free(buf, flavor='raw')
  939. return result
  940. def os_getcwd_oofakeimpl():
  941. return OOSupport.to_rstr(os.getcwd())
  942. return extdef([], str,
  943. "ll_os.ll_os_getcwd", llimpl=os_getcwd_llimpl,
  944. oofakeimpl=os_getcwd_oofakeimpl)
  945. @registering(os.getcwdu, condition=sys.platform=='win32')
  946. def register_os_getcwdu(self):
  947. os_wgetcwd = self.llexternal(underscore_on_windows + 'wgetcwd',
  948. [rffi.CWCHARP, rffi.SIZE_T],
  949. rffi.CWCHARP)
  950. def os_getcwd_llimpl():
  951. bufsize = 256
  952. while True:
  953. buf = lltype.malloc(rffi.CWCHARP.TO, bufsize, flavor='raw')
  954. res = os_wgetcwd(buf, rffi.cast(rffi.SIZE_T, bufsize))
  955. if res:
  956. break # ok
  957. error = rposix.get_errno()
  958. lltype.free(buf, flavor='raw')
  959. if error != errno.ERANGE:
  960. raise OSError(error, "getcwd failed")
  961. # else try again with a larger buffer, up to some sane limit
  962. bufsize *= 4
  963. if bufsize > 1024*1024: # xxx hard-coded upper limit
  964. raise OSError(error, "getcwd result too large")
  965. result = rffi.wcharp2unicode(res)
  966. lltype.free(buf, flavor='raw')
  967. return result
  968. return extdef([], unicode,
  969. "ll_os.ll_os_wgetcwd", llimpl=os_getcwd_llimpl)
  970. @registering_str_unicode(os.listdir)
  971. def register_os_listdir(self, traits):
  972. # we need a different approach on Windows and on Posix
  973. if sys.platform.startswith('win'):
  974. from pypy.rpython.module.ll_win32file import make_listdir_impl
  975. os_listdir_llimpl = make_listdir_impl(traits)
  976. else:
  977. assert traits.str is str
  978. compilation_info = ExternalCompilationInfo(
  979. includes = ['sys/types.h', 'dirent.h']
  980. )
  981. class CConfig:
  982. _compilation_info_ = compilation_info
  983. DIRENT = platform.Struct('struct dirent',
  984. [('d_name', lltype.FixedSizeArray(rffi.CHAR, 1))])
  985. DIRP = rffi.COpaquePtr('DIR')
  986. config = platform.configure(CConfig)
  987. DIRENT = config['DIRENT']
  988. DIRENTP = lltype.Ptr(DIRENT)
  989. os_opendir = self.llexternal('opendir', [rffi.CCHARP], DIRP,
  990. compilation_info=compilation_info)
  991. # XXX macro=True is hack to make sure we get the correct kind of
  992. # dirent struct (which depends on defines)
  993. os_readdir = self.llexternal('readdir', [DIRP], DIRENTP,
  994. compilation_info=compilation_info,
  995. macro=True)
  996. os_closedir = self.llexternal('closedir', [DIRP], rffi.INT,
  997. compilation_info=compilation_info)
  998. def os_listdir_llimpl(path):
  999. dirp = os_opendir(path)
  1000. if not dirp:
  1001. raise OSError(rposix.get_errno(), "os_opendir failed")
  1002. rposix.set_errno(0)
  1003. result = []
  1004. while True:
  1005. direntp = os_readdir(dirp)
  1006. if not direntp:
  1007. error = rposix.get_errno()
  1008. break
  1009. namep = rffi.cast(rffi.CCHARP, direntp.c_d_name)
  1010. name = rffi.charp2str(namep)
  1011. if name != '.' and name != '..':
  1012. result.append(name)
  1013. os_closedir(dirp)
  1014. if error:
  1015. raise OSError(error, "os_readdir failed")
  1016. return result
  1017. return extdef([traits.str0], # a single argument which is a str
  1018. [traits.str0], # returns a list of strings
  1019. traits.ll_os_name('listdir'),
  1020. llimpl=os_listdir_llimpl)
  1021. @registering(os.pipe)
  1022. def register_os_pipe(self):
  1023. # we need a different approach on Windows and on Posix
  1024. if sys.platform.startswith('win'):
  1025. from pypy.rlib import rwin32
  1026. CreatePipe = self.llexternal('CreatePipe', [rwin32.LPHANDLE,
  1027. rwin32.LPHANDLE,
  1028. rffi.VOIDP,
  1029. rwin32.DWORD],
  1030. rwin32.BOOL)
  1031. _open_osfhandle = self.llexternal('_open_osfhandle', [rffi.INTPTR_T,
  1032. rffi.INT],
  1033. rffi.INT)
  1034. null = lltype.nullptr(rffi.VOIDP.TO)
  1035. def os_pipe_llimpl():
  1036. pread = lltype.malloc(rwin32.LPHANDLE.TO, 1, flavor='raw')
  1037. pwrite = lltype.malloc(rwin32.LPHANDLE.TO, 1, flavor='raw')
  1038. ok = CreatePipe(pread, pwrite, null, 0)
  1039. if ok:
  1040. error = 0
  1041. else:
  1042. error = rwin32.GetLastError()
  1043. hread = rffi.cast(rffi.INTPTR_T, pread[0])
  1044. hwrite = rffi.cast(rffi.INTPTR_T, pwrite[0])
  1045. lltype.free(pwrite, flavor='raw')
  1046. lltype.free(pread, flavor='raw')
  1047. if error:
  1048. raise WindowsError(error, "os_pipe failed")
  1049. fdread = _open_osfhandle(hread, 0)
  1050. fdwrite = _open_osfhandle(hwrite, 1)
  1051. return (fdread, fdwrite)
  1052. else:
  1053. INT_ARRAY_P = rffi.CArrayPtr(rffi.INT)
  1054. os_pipe = self.llexternal('pipe', [INT_ARRAY_P], rffi.INT)
  1055. def os_pipe_llimpl():
  1056. filedes = lltype.malloc(INT_ARRAY_P.TO, 2, flavor='raw')
  1057. error = rffi.cast(lltype.Signed, os_pipe(filedes))
  1058. read_fd = filedes[0]
  1059. write_fd = filedes[1]
  1060. lltype.free(filedes, flavor='raw')
  1061. if error != 0:
  1062. raise OSError(rposix.get_errno(), "os_pipe failed")
  1063. return (rffi.cast(lltype.Signed, read_fd),
  1064. rffi.cast(lltype.Signed, write_fd))
  1065. return extdef([], (int, int),
  1066. "ll_os.ll_os_pipe",
  1067. llimpl=os_pipe_llimpl)
  1068. @registering_if(os, 'chown')
  1069. def register_os_chown(self):
  1070. os_chown = self.llexternal('chown', [rffi.CCHARP, rffi.INT, rffi.INT],
  1071. rffi.INT)
  1072. def os_chown_llimpl(path, uid, gid):
  1073. res = os_chown(path, uid, gid)
  1074. if res == -1:
  1075. raise OSError(rposix.get_errno(), "os_chown failed")
  1076. return extdef([str0, int, int], None, "ll_os.ll_os_chown",
  1077. llimpl=os_chown_llimpl)
  1078. @registering_if(os, 'lchown')
  1079. def register_os_lchown(self):
  1080. os_lchown = self.llexternal('lchown',[rffi.CCHARP, rffi.INT, rffi.INT],
  1081. rffi.INT)
  1082. def os_lchown_llimpl(path, uid, gid):
  1083. res = os_lchown(path, uid, gid)
  1084. if res == -1:
  1085. raise OSError(rposix.get_errno(), "os_lchown failed")
  1086. return extdef([str0, int, int], None, "ll_os.ll_os_lchown",
  1087. llimpl=os_lchown_llimpl)
  1088. @registering_if(os, 'readlink')
  1089. def register_os_readlink(self):
  1090. os_readlink = self.llexternal('readlink',
  1091. [rffi.CCHARP, rffi.CCHARP, rffi.SIZE_T],
  1092. rffi.INT)
  1093. # XXX SSIZE_T in POSIX.1-2001
  1094. def os_readlink_llimpl(path):
  1095. bufsize = 1023
  1096. while True:
  1097. l_path = rffi.str2charp(path)
  1098. buf = lltype.malloc(rffi.CCHARP.TO, bufsize,
  1099. flavor='raw')
  1100. res = rffi.cast(lltype.Signed, os_readlink(l_path, buf, bufsize))
  1101. lltype.free(l_path, flavor='raw')
  1102. if res < 0:
  1103. error = rposix.get_errno() # failed
  1104. lltype.free(buf, flavor='raw')
  1105. raise OSError(error, "readlink failed")
  1106. elif res < bufsize:
  1107. break # ok
  1108. else:
  1109. # buf too small, try again with a larger buffer
  1110. lltype.free(buf, flavor='raw')
  1111. bufsize *= 4
  1112. # convert the result to a string
  1113. result = rffi.charp2strn(buf, res)
  1114. lltype.free(buf, flavor='raw')
  1115. return result
  1116. return extdef([str0], str0,
  1117. "ll_os.ll_os_readlink",
  1118. llimpl=os_readlink_llimpl)
  1119. @registering(os.waitpid)
  1120. def register_os_waitpid(self):
  1121. if sys.platform.startswith('win'):
  1122. # emulate waitpid() with the _cwait() of Microsoft's compiler
  1123. os__cwait = self.llexternal('_cwait',
  1124. [rffi.INTP, rffi.PID_T, rffi.INT],
  1125. rffi.PID_T)
  1126. def os_waitpid(pid, status_p, options):
  1127. result = os__cwait(status_p, pid, options)
  1128. # shift the status left a byte so this is more
  1129. # like the POSIX waitpid
  1130. tmp = rffi.cast(rffi.SIGNED, status_p[0])
  1131. tmp <<= 8
  1132. status_p[0] = rffi.cast(rffi.INT, tmp)
  1133. return result
  1134. else:
  1135. # Posix
  1136. os_waitpid = self.llexternal('waitpid',
  1137. [rffi.PID_T, rffi.INTP, rffi.INT],
  1138. rffi.PID_T)
  1139. def os_waitpid_llimpl(pid, options):
  1140. status_p = lltype.malloc(rffi.INTP.TO, 1, flavor='raw')
  1141. status_p[0] = rffi.cast(rffi.INT, 0)
  1142. result = os_waitpid(rffi.cast(rffi.PID_T, pid),
  1143. status_p,
  1144. rffi.cast(rffi.INT, options))
  1145. result = rffi.cast(lltype.Signed, result)
  1146. status = status_p[0]
  1147. lltype.free(status_p, flavor='raw')
  1148. if result == -1:
  1149. raise OSError(rposix.get_errno(), "os_waitpid failed")
  1150. return (rffi.cast(lltype.Signed, result),
  1151. rffi.cast(lltype.Signed, status))
  1152. return extdef([int, int], (int, int),
  1153. "ll_os.ll_os_waitpid",
  1154. llimpl=os_waitpid_llimpl)
  1155. @registering(os.isatty)
  1156. def register_os_isatty(self):
  1157. os_isatty = self.llexternal(underscore_on_windows+'isatty', [rffi.INT], rffi.INT)
  1158. def isatty_llimpl(fd):
  1159. rposix.validate_fd(fd)
  1160. res = rffi.cast(lltype.Signed, os_isatty(rffi.cast(rffi.INT, fd)))
  1161. return res != 0
  1162. return extdef([int], bool, llimpl=isatty_llimpl,
  1163. export_name="ll_os.ll_os_isatty")
  1164. @registering(os.strerror)
  1165. def register_os_strerror(self):
  1166. os_strerror = self.llexternal('strerror', [rffi.INT], rffi.CCHARP)
  1167. def strerror_llimpl(errnum):
  1168. res = os_strerror(rffi.cast(rffi.INT, errnum))
  1169. if not res:
  1170. raise ValueError("os_strerror failed")
  1171. return rffi.charp2str(res)
  1172. return extdef([int], str, llimpl=strerror_llimpl,
  1173. export_name="ll_os.ll_os_strerror")
  1174. @registering(os.system)
  1175. def register_os_system(self):
  1176. os_system = self.llexternal('system', [rffi.CCHARP], rffi.INT)
  1177. def system_llimpl(command):
  1178. res = os_system(command)
  1179. return rffi.cast(lltype.Signed, res)
  1180. return extdef([str0], int, llimpl=system_llimpl,
  1181. export_name="ll_os.ll_os_system")
  1182. @registering_str_unicode(os.unlink)
  1183. def register_os_unlink(self, traits):
  1184. os_unlink = self.llexternal(traits.posix_function_name('unlink'),
  1185. [traits.CCHARP], rffi.INT)
  1186. def unlink_llimpl(pathname):
  1187. res = rffi.cast(lltype.Signed, os_unlink(pathname))
  1188. if res < 0:
  1189. raise OSError(rposix.get_errno(), "os_unlink failed")
  1190. if sys.platform == 'win32':
  1191. from pypy.rpython.module.ll_win32file import make_win32_traits
  1192. win32traits = make_win32_traits(traits)
  1193. @func_renamer('unlink_llimpl_%s' % traits.str.__name__)
  1194. def unlink_llimpl(path):
  1195. if not win32traits.DeleteFile(path):
  1196. raise rwin32.lastWindowsError()
  1197. return extdef([traits.str0], s_None, llimpl=unlink_llimpl,
  1198. export_name=traits.ll_os_name('unlink'))
  1199. @registering_str_unicode(os.chdir)
  1200. def register_os_chdir(self, traits):
  1201. os_chdir = self.llexternal(traits.posix_function_name('chdir'),
  1202. [traits.CCHARP], rffi.INT)
  1203. def os_chdir_llimpl(path):
  1204. res = rffi.cast(lltype.Signed, os_chdir(path))
  1205. if res < 0:
  1206. raise OSError(rposix.get_errno(), "os_chdir failed")
  1207. # On Windows, use an implementation that will produce Win32 errors
  1208. if sys.platform == 'win32':
  1209. from pypy.rpython.module.ll_win32file import make_chdir_impl
  1210. os_chdir_llimpl = make_chdir_impl(traits)
  1211. return extdef([traits.str0], s_None, llimpl=os_chdir_llimpl,
  1212. export_name=traits.ll_os_name('chdir'))
  1213. @registering_str_unicode(os.mkdir)
  1214. def register_os_mkdir(self, traits):
  1215. os_mkdir = self.llexternal(traits.posix_function_name('mkdir'),
  1216. [traits.CCHARP, rffi.MODE_T], rffi.INT)
  1217. if sys.platform == 'win32':
  1218. from pypy.rpython.module.ll_win32file import make_win32_traits
  1219. win32traits = make_win32_traits(traits)
  1220. @func_renamer('mkdir_llimpl_%s' % traits.str.__name__)
  1221. def os_mkdir_llimpl(path, mode):
  1222. if not win32traits.CreateDirectory(path, None):
  1223. raise rwin32.lastWindowsError()
  1224. else:
  1225. def os_mkdir_llimpl(pathname, mode):
  1226. res = os_mkdir(pathname, mode)
  1227. res = rffi.cast(lltype.Signed, res)
  1228. if res < 0:
  1229. raise OSError(rposix.get_errno(), "os_mkdir failed")
  1230. return extdef([traits.str0, int], s_None, llimpl=os_mkdir_llimpl,
  1231. export_name=traits.ll_os_name('mkdir'))
  1232. @registering_str_unicode(os.rmdir)
  1233. def register_os_rmdir(self, traits):
  1234. os_rmdir = self.llexternal(traits.posix_function_name('rmdir'),
  1235. [traits.CCHARP], rffi.INT)
  1236. def rmdir_llimpl(pathname):
  1237. res = rffi.cast(lltype.Signed, os_rmdir(pathname))
  1238. if res < 0:
  1239. raise OSError(rposix.get_errno(), "os_rmdir failed")
  1240. return extdef([traits.str0], s_None, llimpl=rmdir_llimpl,
  1241. export_name=traits.ll_os_name('rmdir'))
  1242. @registering_str_unicode(os.chmod)
  1243. def register_os_chmod(self, traits):
  1244. os_chmod = self.llexternal(traits.posix_function_name('chmod'),
  1245. [traits.CCHARP, rffi.MODE_T], rffi.INT)
  1246. def chmod_llimpl(path, mode):
  1247. res = rffi.cast(lltype.Signed, os_chmod(path, rffi.cast(rffi.MODE_T, mode)))
  1248. if res < 0:
  1249. raise OSError(rposix.get_errno(), "os_chmod failed")
  1250. if sys.platform == 'win32':
  1251. from pypy.rpython.module.ll_win32file import make_chmod_impl
  1252. chmod_llimpl = make_chmod_impl(traits)
  1253. return extdef([traits.str0, int], s_None, llimpl=chmod_llimpl,
  1254. export_name=traits.ll_os_name('chmod'))
  1255. @registering_str_unicode(os.rename)
  1256. def register_os_rename(self, traits):
  1257. os_rename = self.llexternal(traits.posix_function_name('rename'),
  1258. [traits.CCHARP, traits.CCHARP], rffi.INT)
  1259. def rename_llimpl(oldpath, newpath):
  1260. res = rffi.cast(lltype.Signed, os_rename(oldpath, newpath))
  1261. if res < 0:
  1262. raise OSError(rposix.get_errno(), "os_rename failed")
  1263. if sys.platform == 'win32':
  1264. from pypy.rpython.module.ll_win32file import make_win32_traits
  1265. win32traits = make_win32_traits(traits)
  1266. @func_renamer('rename_llimpl_%s' % traits.str.__name__)
  1267. def rename_llimpl(oldpath, newpath):
  1268. if not win32traits.MoveFile(oldpath, newpath):
  1269. raise rwin32.lastWindowsError()
  1270. return extdef([traits.str0, traits.str0], s_None, llimpl=rename_llimpl,
  1271. export_name=traits.ll_os_name('rename'))
  1272. @registering_str_unicode(getattr(os, 'mkfifo', None))
  1273. def register_os_mkfifo(self, traits):
  1274. os_mkfifo = self.llexternal(traits.posix_function_name('mkfifo'),
  1275. [traits.CCHARP, rffi.MODE_T], rffi.INT)
  1276. def mkfifo_llimpl(path, mode):
  1277. res = rffi.cast(lltype.Signed, os_mkfifo(path, mode))
  1278. if res < 0:
  1279. raise OSError(rposix.get_errno(), "os_mkfifo failed")
  1280. return extdef([traits.str0, int], s_None, llimpl=mkfifo_llimpl,
  1281. export_name=traits.ll_os_name('mkfifo'))
  1282. @registering_str_unicode(getattr(os, 'mknod', None))
  1283. def register_os_mknod(self, traits):
  1284. os_mknod = self.llexternal(traits.posix_function_name('mknod'),
  1285. [traits.CCHARP, rffi.MODE_T, rffi.INT],
  1286. rffi.INT) # xxx: actually ^^^ dev_t
  1287. def mknod_llimpl(path, mode, dev):
  1288. res = rffi.cast(lltype.Signed, os_mknod(path, mode, dev))
  1289. if res < 0:
  1290. raise OSError(rposix.get_errno(), "os_mknod failed")
  1291. return extdef([traits.str0, int, int], s_None, llimpl=mknod_llimpl,
  1292. export_name=traits.ll_os_name('mknod'))
  1293. @registering(os.umask)
  1294. def register_os_umask(self):
  1295. os_umask = self.llexternal(underscore_on_windows+'umask', [rffi.MODE_T], rffi.MODE_T)
  1296. def umask_llimpl(newmask):
  1297. res = os_umask(rffi.cast(rffi.MODE_T, newmask))
  1298. return rffi.cast(lltype.Signed, res)
  1299. return extdef([int], int, llimpl=umask_llimpl,
  1300. export_name="ll_os.ll_os_umask")
  1301. @registering_if(os, 'kill', sys.platform != 'win32')
  1302. def register_os_kill(self):
  1303. os_kill = self.llexternal('kill', [rffi.PID_T, rffi.INT],
  1304. rffi.INT)
  1305. def kill_llimpl(pid, sig):
  1306. res = rffi.cast(lltype.Signed, os_kill(rffi.cast(rffi.PID_T, pid),
  1307. rffi.cast(rffi.INT, sig)))
  1308. if res < 0:
  1309. raise OSError(rposix.get_errno(), "os_kill failed")
  1310. return extdef([int, int], s_None, llimpl=kill_llimpl,
  1311. export_name="ll_os.ll_os_kill")
  1312. @registering_if(os, 'killpg')
  1313. def register_os_killpg(self):
  1314. os_killpg = self.llexternal('killpg', [rffi.INT, rffi.INT],
  1315. rffi.INT)
  1316. def killpg_llimpl(pid, sig):
  1317. res = rffi.cast(lltype.Signed, os_killpg(rffi.cast(rffi.INT, pid),
  1318. rffi.cast(rffi.INT, sig)))
  1319. if res < 0:
  1320. raise OSError(rposix.get_errno(), "os_killpg failed")
  1321. return extdef([int, int], s_None, llimpl=killpg_llimpl,
  1322. export_name="ll_os.ll_os_killpg")
  1323. @registering_if(os, 'link')
  1324. def register_os_link(self):
  1325. os_link = self.llexternal('link', [rffi.CCHARP, rffi.CCHARP],
  1326. rffi.INT)
  1327. def link_llimpl(oldpath, newpath):
  1328. res = rffi.cast(lltype.Signed, os_link(oldpath, newpath))
  1329. if res < 0:
  1330. raise OSError(rposix.get_errno(), "os_link failed")
  1331. return extdef([str0, str0], s_None, llimpl=link_llimpl,
  1332. export_name="ll_os.ll_os_link")
  1333. @registering_if(os, 'symlink')
  1334. def register_os_symlink(self):
  1335. os_symlink = self.llexternal('symlink', [rffi.CCHARP, rffi.CCHARP],
  1336. rffi.INT)
  1337. def symlink_llimpl(oldpath, newpath):
  1338. res = rffi.cast(lltype.Signed, os_symlink(oldpath, newpath))
  1339. if res < 0:
  1340. raise OSError(rposix.get_errno(), "os_symlink failed")
  1341. return extdef([str0, str0], s_None, llimpl=symlink_llimpl,
  1342. export_name="ll_os.ll_os_symlink")
  1343. @registering_if(os, 'fork')
  1344. def register_os_fork(self):
  1345. from pypy.module.thread import ll_thread
  1346. eci = self.gcc_profiling_bug_workaround('pid_t _noprof_fork(void)',
  1347. 'return fork();')
  1348. os_fork = self.llexternal('_noprof_fork', [], rffi.PID_T,
  1349. compilation_info = eci,
  1350. _nowrapper = True)
  1351. def fork_llimpl():
  1352. opaqueaddr = ll_thread.gc_thread_before_fork()
  1353. childpid = rffi.cast(lltype.Signed, os_fork())
  1354. ll_thread.gc_thread_after_fork(childpid, opaqueaddr)
  1355. if childpid == -1:
  1356. raise OSError(rposix.get_errno(), "os_fork failed")
  1357. return rffi.cast(lltype.Signed, childpid)
  1358. return extdef([], int, llimpl=fork_llimpl,
  1359. export_name="ll_os.ll_os_fork")
  1360. @registering_if(os, 'openpty')
  1361. def register_os_openpty(self):
  1362. os_openpty = self.llexternal(
  1363. 'openpty',
  1364. [rffi.INTP, rffi.INTP, rffi.VOIDP, rffi.VOIDP, rffi.VOIDP],
  1365. rffi.INT,
  1366. compilation_info=ExternalCompilationInfo(libraries=['util']))
  1367. def openpty_llimpl():
  1368. master_p = lltype.malloc(rffi.INTP.TO, 1, flavor='raw')
  1369. slave_p = lltype.malloc(rffi.INTP.TO, 1, flavor='raw')
  1370. result = os_openpty(master_p, slave_p, None, None, None)
  1371. master_fd = master_p[0]
  1372. slave_fd = slave_p[0]
  1373. lltype.free(master_p, flavor='raw')
  1374. lltype.free(slave_p, flavor='raw')
  1375. if result == -1:
  1376. raise OSError(rposix.get_errno(), "os_openpty failed")
  1377. return (rffi.cast(lltype.Signed, master_fd),
  1378. rffi.cast(lltype.Signed, slave_fd))
  1379. return extdef([], (int, int), "ll_os.ll_os_openpty",
  1380. llimpl=openpty_llimpl)
  1381. @registering_if(os, 'forkpty')
  1382. def register_os_forkpty(self):
  1383. os_forkpty = self.llexternal(
  1384. 'forkpty',
  1385. [rffi.INTP, rffi.VOIDP, rffi.VOIDP, rffi.VOIDP],
  1386. rffi.PID_T,
  1387. compilation_info=ExternalCompilationInfo(libraries=['util']))
  1388. def forkpty_llimpl():
  1389. master_p = lltype.malloc(rffi.INTP.TO, 1, flavor='raw')
  1390. childpid = os_forkpty(master_p, None, None, None)
  1391. master_fd = master_p[0]
  1392. lltype.free(master_p, flavor='raw')
  1393. if childpid == -1:
  1394. raise OSError(rposix.get_errno(), "os_forkpty failed")
  1395. return (rffi.cast(lltype.Signed, childpid),
  1396. rffi.cast(lltype.Signed, master_fd))
  1397. return extdef([], (int, int), "ll_os.ll_os_forkpty",
  1398. llimpl=forkpty_llimpl)
  1399. @registering(os._exit)
  1400. def register_os__exit(self):
  1401. os__exit = self.llexternal('_exit', [rffi.INT], lltype.Void)
  1402. def _exit_llimpl(status):
  1403. os__exit(rffi.cast(rffi.INT, status))
  1404. return extdef([int], s_None, llimpl=_exit_llimpl,
  1405. export_name="ll_os.ll_os__exit")
  1406. @registering_if(os, 'nice')
  1407. def register_os_nice(self):
  1408. os_nice = self.llexternal('nice', [rffi.INT], rffi.INT)
  1409. def nice_llimpl(inc):
  1410. # Assume that the system provides a standard-compliant version
  1411. # of nice() that returns the new priority. Nowadays, FreeBSD
  1412. # might be the last major non-compliant system (xxx check me).
  1413. rposix.set_errno(0)
  1414. res = rffi.cast(lltype.Signed, os_nice(inc))
  1415. if res == -1:
  1416. err = rposix.get_errno()
  1417. if err != 0:
  1418. raise OSError(err, "os_nice failed")
  1419. return res
  1420. return extdef([int], int, llimpl=nice_llimpl,
  1421. export_name="ll_os.ll_os_nice")
  1422. # --------------------------- os.stat & variants ---------------------------
  1423. @registering(os.fstat)
  1424. def register_os_fstat(self):
  1425. from pypy.rpython.module import ll_os_stat
  1426. return ll_os_stat.register_stat_variant('fstat', StringTraits())
  1427. @registering_str_unicode(os.stat)
  1428. def register_os_stat(self, traits):
  1429. from pypy.rpython.module import ll_os_stat
  1430. return ll_os_stat.register_stat_variant('stat', traits)
  1431. @registering_str_unicode(os.lstat)
  1432. def register_os_lstat(self, traits):
  1433. from pypy.rpython.module import ll_os_stat
  1434. return ll_os_stat.register_stat_variant('lstat', traits)
  1435. # ------------------------------- os.W* ---------------------------------
  1436. w_star = ['WCOREDUMP', 'WIFCONTINUED', 'WIFSTOPPED',
  1437. 'WIFSIGNALED', 'WIFEXITED', 'WEXITSTATUS',
  1438. 'WSTOPSIG', 'WTERMSIG']
  1439. # last 3 are returning int
  1440. w_star_returning_int = dict.fromkeys(w_star[-3:])
  1441. def declare_new_w_star(self, name):
  1442. """ stupid workaround for the python late-binding
  1443. 'feature'
  1444. """
  1445. def fake(status):
  1446. return int(getattr(os, name)(status))
  1447. fake.func_name = 'fake_' + name
  1448. os_c_func = self.llexternal("pypy_macro_wrapper_" + name,
  1449. [lltype.Signed], lltype.Signed,
  1450. _callable=fake)
  1451. if name in self.w_star_returning_int:
  1452. def llimpl(status):
  1453. return os_c_func(status)
  1454. resulttype = int
  1455. else:
  1456. def llimpl(status):
  1457. return bool(os_c_func(status))
  1458. resulttype = bool
  1459. llimpl.func_name = name + '_llimpl'
  1460. return extdef([int], resulttype, "ll_os." + name,
  1461. llimpl=llimpl)
  1462. for name in w_star:
  1463. locals()['register_w_' + name] = registering_if(os, name)(
  1464. lambda self, xname=name : self.declare_new_w_star(xname))
  1465. @registering_if(os, 'ttyname')
  1466. def register_os_ttyname(self):
  1467. os_ttyname = self.llexternal('ttyname', [lltype.Signed], rffi.CCHARP)
  1468. def ttyname_llimpl(fd):
  1469. l_name = os_ttyname(fd)
  1470. if not l_name:
  1471. raise OSError(rposix.get_errno(), "ttyname raised")
  1472. return rffi.charp2str(l_name)
  1473. return extdef([int], str, "ll_os.ttyname",
  1474. llimpl=ttyname_llimpl)
  1475. # ____________________________________________________________
  1476. # XXX horrible workaround for a bug of profiling in gcc on
  1477. # OS X with functions containing a direct call to some system calls
  1478. # like fork(), execv(), execve()
  1479. def gcc_profiling_bug_workaround(self, decl, body):
  1480. body = ('/*--no-profiling-for-this-file!--*/\n'
  1481. '%s {\n'
  1482. '\t%s\n'
  1483. '}\n' % (decl, body,))
  1484. return ExternalCompilationInfo(
  1485. post_include_bits = [decl + ';'],
  1486. separate_module_sources = [body])
  1487. # ____________________________________________________________
  1488. # Support for os.environ
  1489. # XXX only for systems where os.environ is an instance of _Environ,
  1490. # which should cover Unix and Windows at least
  1491. assert type(os.environ) is not dict
  1492. from pypy.rpython.controllerentry import ControllerEntryForPrebuilt
  1493. class EnvironExtRegistry(ControllerEntryForPrebuilt):
  1494. _about_ = os.environ
  1495. def getcontroller(self):
  1496. from pypy.rpython.module.ll_os_environ import OsEnvironController
  1497. return OsEnvironController()
  1498. # ____________________________________________________________
  1499. # Support for the WindowsError exception
  1500. if sys.platform == 'win32':
  1501. from pypy.rlib import rwin32
  1502. class RegisterFormatError(BaseLazyRegistering):
  1503. def __init__(self):
  1504. pass
  1505. @registering(rwin32.FormatError)
  1506. def register_rwin32_FormatError(self):
  1507. return extdef([lltype.Signed], str,
  1508. "rwin32_FormatError",
  1509. llimpl=rwin32.llimpl_FormatError,
  1510. ooimpl=rwin32.fake_FormatError)