Debian Codegraph @

rpython/rlib/rfile.py

raw symbols SCIP
1 """ This file makes open() and friends RPython. Note that RFile should not
2 be used directly and instead it's magically appearing each time you call
3 python builtin open()
4 """
5
6 import os, stat, errno, sys
7 from rpython.rlib import rposix, rgc
8 from rpython.rlib.objectmodel import enforceargs
9 from rpython.rlib.rarithmetic import intmask
10 from rpython.rlib.rstring import StringBuilder
11 from rpython.rtyper.lltypesystem import rffi, lltype
12 from rpython.rtyper.tool import rffi_platform as platform
13 from rpython.translator.tool.cbuild import ExternalCompilationInfo
14
15 includes = ['stdio.h', 'sys/types.h']
16 if os.name == "posix":
17 includes += ['unistd.h']
18 ftruncate = 'ftruncate'
19 fileno = 'fileno'
20 else:
21 ftruncate = '_chsize'
22 fileno = '_fileno'
23 eci = ExternalCompilationInfo(includes=includes)
24
25
26 class CConfig(object):
27 _compilation_info_ = eci
28
29 off_t = platform.SimpleType('off_t')
30
31 _IONBF = platform.DefinedConstantInteger('_IONBF')
32 _IOLBF = platform.DefinedConstantInteger('_IOLBF')
33 _IOFBF = platform.DefinedConstantInteger('_IOFBF')
34 BUFSIZ = platform.DefinedConstantInteger('BUFSIZ')
35 EOF = platform.DefinedConstantInteger('EOF')
36
37 config = platform.configure(CConfig)
38
39 FILEP = rffi.COpaquePtr("FILE")
40 OFF_T = config['off_t']
41
42 _IONBF = config['_IONBF']
43 _IOLBF = config['_IOLBF']
44 _IOFBF = config['_IOFBF']
45 BUFSIZ = config['BUFSIZ']
46 EOF = config['EOF']
47
48 BASE_BUF_SIZE = 4096
49 BASE_LINE_SIZE = 100
50
51 NEWLINE_UNKNOWN = 0
52 NEWLINE_CR = 1
53 NEWLINE_LF = 2
54 NEWLINE_CRLF = 4
55
56
57 def llexternal(*args, **kwargs):
58 return rffi.llexternal(*args, compilation_info=eci, **kwargs)
59
60 c_fopen = llexternal('fopen', [rffi.CCHARP, rffi.CCHARP], FILEP,
61 save_err=rffi.RFFI_SAVE_ERRNO)
62 c_popen = llexternal('popen', [rffi.CCHARP, rffi.CCHARP], FILEP,
63 save_err=rffi.RFFI_SAVE_ERRNO)
64 c_fdopen = llexternal(('_' if os.name == 'nt' else '') + 'fdopen',
65 [rffi.INT, rffi.CCHARP], FILEP,
66 save_err=rffi.RFFI_SAVE_ERRNO)
67 c_tmpfile = llexternal('tmpfile', [], FILEP,
68 save_err=rffi.RFFI_SAVE_ERRNO)
69
70 c_setvbuf = llexternal('setvbuf', [FILEP, rffi.CCHARP, rffi.INT, rffi.SIZE_T],
71 rffi.INT)
72
73 c_fclose = llexternal('fclose', [FILEP], rffi.INT,
74 save_err=rffi.RFFI_SAVE_ERRNO)
75 c_pclose = llexternal('pclose', [FILEP], rffi.INT,
76 save_err=rffi.RFFI_SAVE_ERRNO)
77
78 def wrap_fclose(filep):
79 with rposix.SuppressIPH():
80 return c_fclose(filep)
81
82 def wrap_pclose(filep):
83 with rposix.SuppressIPH():
84 return c_fclose(filep)
85
86 # Note: the following two functions are called from __del__ methods,
87 # so must be 'releasegil=False'. Otherwise, a program using both
88 # threads and the RFile class cannot translate. See c684bf704d1f
89 c_fclose_in_del = llexternal('fclose', [FILEP], rffi.INT, releasegil=False)
90 c_pclose_in_del = llexternal('pclose', [FILEP], rffi.INT, releasegil=False)
91
92 def wrap_fclose_in_del(filep):
93 with rposix.SuppressIPH_del():
94 return c_fclose_in_del(filep)
95
96 def wrap_pclose_in_del(filep):
97 with rposix.SuppressIPH_del():
98 return c_pclose_in_del(filep)
99
100 _fclose2 = (wrap_fclose, wrap_fclose_in_del)
101 _pclose2 = (wrap_pclose, wrap_pclose_in_del)
102
103 c_getc = llexternal('getc', [FILEP], rffi.INT, macro=True)
104 c_ungetc = llexternal('ungetc', [rffi.INT, FILEP], rffi.INT)
105 c_fgets = llexternal('fgets', [rffi.CCHARP, rffi.INT, FILEP], rffi.CCHARP)
106 c_fread = llexternal('fread', [rffi.CCHARP, rffi.SIZE_T, rffi.SIZE_T, FILEP],
107 rffi.SIZE_T)
108
109 c_fwrite = llexternal('fwrite', [rffi.CCHARP, rffi.SIZE_T, rffi.SIZE_T, FILEP],
110 rffi.SIZE_T, save_err=rffi.RFFI_SAVE_ERRNO)
111 c_fflush = llexternal('fflush', [FILEP], rffi.INT,
112 save_err=rffi.RFFI_SAVE_ERRNO)
113 c_ftruncate = llexternal(ftruncate, [rffi.INT, OFF_T], rffi.INT, macro=True,
114 save_err=rffi.RFFI_SAVE_ERRNO)
115
116 c_fseek = llexternal('fseek', [FILEP, rffi.LONG, rffi.INT], rffi.INT,
117 save_err=rffi.RFFI_SAVE_ERRNO)
118 c_ftell = llexternal('ftell', [FILEP], rffi.LONG,
119 save_err=rffi.RFFI_SAVE_ERRNO)
120 c_fileno = llexternal(fileno, [FILEP], rffi.INT)
121
122 c_feof = llexternal('feof', [FILEP], rffi.INT)
123 c_ferror = llexternal('ferror', [FILEP], rffi.INT)
124 c_clearerr = llexternal('clearerr', [FILEP], lltype.Void)
125
126 c_stdin = rffi.CExternVariable(FILEP, 'stdin', eci, c_type='FILE*',
127 getter_only=True, declare_as_extern=False)
128 c_stdout = rffi.CExternVariable(FILEP, 'stdout', eci, c_type='FILE*',
129 getter_only=True, declare_as_extern=False)
130 c_stderr = rffi.CExternVariable(FILEP, 'stderr', eci, c_type='FILE*',
131 getter_only=True, declare_as_extern=False)
132
133
134 def _error(ll_file):
135 err = c_ferror(ll_file)
136 c_clearerr(ll_file)
137 raise IOError(err, os.strerror(err))
138
139
140 def _dircheck(ll_file):
141 try:
142 st = os.fstat(c_fileno(ll_file))
143 except OSError:
144 pass
145 else:
146 if stat.S_ISDIR(st[0]):
147 err = errno.EISDIR
148 raise IOError(err, os.strerror(err))
149
150
151 def _sanitize_mode(mode):
152 if len(mode) == 0:
153 raise ValueError("empty mode string")
154 upos = mode.find('U')
155 if upos >= 0:
156 mode = mode[:upos] + mode[upos+1:]
157 first = mode[0:1]
158 if first == 'w' or first == 'a':
159 raise ValueError("universal newline mode can only be used with "
160 "modes starting with 'r'")
161 if first != 'r':
162 mode = 'r' + mode
163 if 'b' not in mode:
164 mode = mode[0] + 'b' + mode[1:]
165 elif mode[0] != 'r' and mode[0] != 'w' and mode[0] != 'a':
166 raise ValueError("mode string must begin with one of 'r', 'w', 'a' "
167 "or 'U', not '%s'" % mode)
168 return mode
169
170
171 def create_file(filename, mode="r", buffering=-1):
172 newmode = _sanitize_mode(mode)
173 ll_name = rffi.str2charp(filename)
174 try:
175 ll_mode = rffi.str2charp(newmode)
176 try:
177 ll_file = c_fopen(ll_name, ll_mode)
178 if not ll_file:
179 errno = rposix.get_saved_errno()
180 raise IOError(errno, os.strerror(errno))
181 finally:
182 lltype.free(ll_mode, flavor='raw')
183 finally:
184 lltype.free(ll_name, flavor='raw')
185 _dircheck(ll_file)
186 f = RFile(ll_file, mode)
187 f._setbufsize(buffering)
188 return f
189
190
191 def create_fdopen_rfile(fd, mode="r", buffering=-1):
192 newmode = _sanitize_mode(mode)
193 ll_mode = rffi.str2charp(newmode)
194 try:
195 with rposix.SuppressIPH():
196 ll_file = c_fdopen(fd, ll_mode)
197 if not ll_file:
198 errno = rposix.get_saved_errno()
199 raise OSError(errno, os.strerror(errno))
200 finally:
201 lltype.free(ll_mode, flavor='raw')
202 _dircheck(ll_file)
203 f = RFile(ll_file, mode)
204 f._setbufsize(buffering)
205 return f
206
207
208 def create_temp_rfile():
209 res = c_tmpfile()
210 if not res:
211 errno = rposix.get_saved_errno()
212 raise OSError(errno, os.strerror(errno))
213 return RFile(res)
214
215
216 def create_popen_file(command, type):
217 ll_command = rffi.str2charp(command)
218 try:
219 ll_type = rffi.str2charp(type)
220 try:
221 ll_file = c_popen(ll_command, ll_type)
222 if not ll_file:
223 errno = rposix.get_saved_errno()
224 raise OSError(errno, os.strerror(errno))
225 finally:
226 lltype.free(ll_type, flavor='raw')
227 finally:
228 lltype.free(ll_command, flavor='raw')
229 return RFile(ll_file, close2=_pclose2)
230
231
232 def create_stdio():
233 close2 = (None, None)
234 stdin = RFile(c_stdin(), close2=close2)
235 stdout = RFile(c_stdout(), close2=close2)
236 stderr = RFile(c_stderr(), close2=close2)
237 return stdin, stdout, stderr
238
239
240 def write_int(f, l):
241 if sys.maxint == 2147483647:
242 f.write(chr(l & 0xff) +
243 chr((l >> 8) & 0xff) +
244 chr((l >> 16) & 0xff) +
245 chr((l >> 24) & 0xff))
246 else:
247 f.write(chr(l & 0xff) +
248 chr((l >> 8) & 0xff) +
249 chr((l >> 16) & 0xff) +
250 chr((l >> 24) & 0xff) +
251 chr((l >> 32) & 0xff) +
252 chr((l >> 40) & 0xff) +
253 chr((l >> 48) & 0xff) +
254 chr((l >> 56) & 0xff))
255
256 class RFile(object):
257 _setbuf = lltype.nullptr(rffi.CCHARP.TO)
258 _univ_newline = False
259 _newlinetypes = NEWLINE_UNKNOWN
260 _skipnextlf = False
261
262 def __init__(self, ll_file, mode=None, close2=_fclose2):
263 self._ll_file = ll_file
264 if mode is not None:
265 self._univ_newline = 'U' in mode
266 self._close2 = close2
267
268 def _setbufsize(self, bufsize):
269 if bufsize >= 0:
270 if bufsize == 0:
271 mode = _IONBF
272 elif bufsize == 1:
273 mode = _IOLBF
274 bufsize = BUFSIZ
275 else:
276 mode = _IOFBF
277 if self._setbuf:
278 lltype.free(self._setbuf, flavor='raw')
279 if mode == _IONBF:
280 self._setbuf = lltype.nullptr(rffi.CCHARP.TO)
281 else:
282 self._setbuf = lltype.malloc(rffi.CCHARP.TO, bufsize, flavor='raw')
283 c_setvbuf(self._ll_file, self._setbuf, mode, bufsize)
284
285 def __del__(self):
286 """Closes the described file when the object's last reference
287 goes away. Unlike an explicit call to close(), this is meant
288 as a last-resort solution and cannot release the GIL or return
289 an error code."""
290 ll_file = self._ll_file
291 if ll_file:
292 do_close = self._close2[1]
293 if do_close:
294 do_close(ll_file) # return value ignored
295 if self._setbuf:
296 lltype.free(self._setbuf, flavor='raw')
297
298 def _cleanup_(self):
299 self._ll_file = lltype.nullptr(FILEP.TO)
300
301 def close(self):
302 """Closes the described file.
303
304 Attention! Unlike Python semantics, `close' does not return `None' upon
305 success but `0', to be able to return an exit code for popen'ed files.
306
307 The actual return value may be determined with os.WEXITSTATUS.
308 """
309 res = 0
310 ll_file = self._ll_file
311 if ll_file:
312 # double close is allowed
313 self._ll_file = lltype.nullptr(FILEP.TO)
314 rgc.may_ignore_finalizer(self)
315 do_close = self._close2[0]
316 try:
317 if do_close:
318 res = do_close(ll_file)
319 if res == -1:
320 errno = rposix.get_saved_errno()
321 raise IOError(errno, os.strerror(errno))
322 finally:
323 if self._setbuf:
324 lltype.free(self._setbuf, flavor='raw')
325 self._setbuf = lltype.nullptr(rffi.CCHARP.TO)
326 return res
327
328 def _check_closed(self):
329 if not self._ll_file:
330 raise ValueError("I/O operation on closed file")
331
332 @property
333 def closed(self):
334 return not self._ll_file
335
336 def _fread(self, buf, n, stream):
337 if not self._univ_newline:
338 return c_fread(buf, 1, n, stream)
339
340 i = 0
341 dst = buf
342 newlinetypes = self._newlinetypes
343 skipnextlf = self._skipnextlf
344 while n:
345 nread = c_fread(dst, 1, n, stream)
346 if nread == 0:
347 break
348
349 src = dst
350 n -= nread
351 shortread = n != 0
352 while nread:
353 nread -= 1
354 c = src[0]
355 src = rffi.ptradd(src, 1)
356 if c == '\r':
357 dst[0] = '\n'
358 dst = rffi.ptradd(dst, 1)
359 i += 1
360 skipnextlf = True
361 elif skipnextlf and c == '\n':
362 skipnextlf = False
363 newlinetypes |= NEWLINE_CRLF
364 n += 1
365 else:
366 if c == '\n':
367 newlinetypes |= NEWLINE_LF
368 elif skipnextlf:
369 newlinetypes |= NEWLINE_CR
370 dst[0] = c
371 dst = rffi.ptradd(dst, 1)
372 i += 1
373 skipnextlf = False
374 if shortread:
375 if skipnextlf and c_feof(stream):
376 newlinetypes |= NEWLINE_CR
377 break
378 self._newlinetypes = newlinetypes
379 self._skipnextlf = skipnextlf
380 return i
381
382 def read(self, size=-1):
383 # XXX CPython uses a more delicate logic here
384 self._check_closed()
385 ll_file = self._ll_file
386 if size == 0:
387 return ""
388 elif size < 0:
389 # read the entire contents
390 buf = lltype.malloc(rffi.CCHARP.TO, BASE_BUF_SIZE, flavor='raw')
391 try:
392 s = StringBuilder()
393 while True:
394 returned_size = self._fread(buf, BASE_BUF_SIZE, ll_file)
395 returned_size = intmask(returned_size) # is between 0 and BASE_BUF_SIZE
396 if returned_size == 0:
397 if c_feof(ll_file):
398 # ok, finished
399 return s.build()
400 raise _error(ll_file)
401 s.append_charpsize(buf, returned_size)
402 finally:
403 lltype.free(buf, flavor='raw')
404 else: # size > 0
405 with rffi.scoped_alloc_buffer(size) as buf:
406 returned_size = self._fread(buf.raw, size, ll_file)
407 returned_size = intmask(returned_size) # is between 0 and size
408 if returned_size == 0:
409 if not c_feof(ll_file):
410 raise _error(ll_file)
411 s = buf.str(returned_size)
412 assert s is not None
413 return s
414
415 def _readline1(self, raw_buf):
416 ll_file = self._ll_file
417 for i in range(BASE_LINE_SIZE):
418 raw_buf[i] = '\n'
419
420 result = c_fgets(raw_buf, BASE_LINE_SIZE, ll_file)
421 if not result:
422 if c_feof(ll_file): # ok
423 return 0
424 raise _error(ll_file)
425
426 # Assume that fgets() works as documented, and additionally
427 # never writes beyond the final \0, which the CPython
428 # fileobject.c says appears to be the case everywhere.
429 # The only case where the buffer was not big enough is the
430 # case where the buffer is full, ends with \0, and doesn't
431 # end with \n\0.
432
433 p = 0
434 while raw_buf[p] != '\n':
435 p += 1
436 if p == BASE_LINE_SIZE:
437 # fgets read whole buffer without finding newline
438 return -1
439 # p points to first \n
440
441 if p + 1 < BASE_LINE_SIZE and raw_buf[p + 1] == '\0':
442 # \n followed by \0, fgets read and found newline
443 return p + 1
444 else:
445 # \n not followed by \0, fgets read but didnt find newline
446 assert p > 0 and raw_buf[p - 1] == '\0'
447 return p - 1
448
449 def readline(self, size=-1):
450 self._check_closed()
451 if size == 0:
452 return ""
453 elif size < 0 and not self._univ_newline:
454 with rffi.scoped_alloc_buffer(BASE_LINE_SIZE) as buf:
455 c = self._readline1(buf.raw)
456 if c >= 0:
457 return buf.str(c)
458
459 # this is the rare case: the line is longer than BASE_LINE_SIZE
460 s = StringBuilder()
461 while True:
462 s.append_charpsize(buf.raw, BASE_LINE_SIZE - 1)
463 c = self._readline1(buf.raw)
464 if c >= 0:
465 break
466 s.append_charpsize(buf.raw, c)
467 return s.build()
468 else: # size > 0 or self._univ_newline
469 ll_file = self._ll_file
470 c = 0
471 s = StringBuilder()
472 if self._univ_newline:
473 newlinetypes = self._newlinetypes
474 skipnextlf = self._skipnextlf
475 while size < 0 or s.getlength() < size:
476 c = c_getc(ll_file)
477 if c == EOF:
478 break
479 if skipnextlf:
480 skipnextlf = False
481 if c == ord('\n'):
482 newlinetypes |= NEWLINE_CRLF
483 c = c_getc(ll_file)
484 if c == EOF:
485 break
486 else:
487 newlinetypes |= NEWLINE_CR
488 if c == ord('\r'):
489 skipnextlf = True
490 c = ord('\n')
491 elif c == ord('\n'):
492 newlinetypes |= NEWLINE_LF
493 s.append(chr(c))
494 if c == ord('\n'):
495 break
496 if c == EOF:
497 if skipnextlf:
498 newlinetypes |= NEWLINE_CR
499 self._newlinetypes = newlinetypes
500 self._skipnextlf = skipnextlf
501 else:
502 while s.getlength() < size:
503 c = c_getc(ll_file)
504 if c == EOF:
505 break
506 s.append(chr(c))
507 if c == ord('\n'):
508 break
509 if c == EOF:
510 if c_ferror(ll_file):
511 raise _error(ll_file)
512 return s.build()
513
514 @enforceargs(None, str)
515 def write(self, value):
516 self._check_closed()
517 with rffi.scoped_nonmovingbuffer(value) as ll_value:
518 # note that since we got a nonmoving buffer, it is either raw
519 # or already cannot move, so the arithmetics below are fine
520 length = len(value)
521 bytes = c_fwrite(ll_value, 1, length, self._ll_file)
522 if bytes != length:
523 errno = rposix.get_saved_errno()
524 c_clearerr(self._ll_file)
525 raise IOError(errno, os.strerror(errno))
526
527 def flush(self):
528 self._check_closed()
529 res = c_fflush(self._ll_file)
530 if res != 0:
531 errno = rposix.get_saved_errno()
532 raise IOError(errno, os.strerror(errno))
533
534 def truncate(self, arg=-1):
535 self._check_closed()
536 if arg == -1:
537 arg = self.tell()
538 self.flush()
539 res = c_ftruncate(self.fileno(), arg)
540 if res == -1:
541 errno = rposix.get_saved_errno()
542 raise IOError(errno, os.strerror(errno))
543
544 def seek(self, pos, whence=0):
545 self._check_closed()
546 res = c_fseek(self._ll_file, pos, whence)
547 if res == -1:
548 errno = rposix.get_saved_errno()
549 raise IOError(errno, os.strerror(errno))
550 self._skipnextlf = False
551
552 def tell(self):
553 self._check_closed()
554 res = intmask(c_ftell(self._ll_file))
555 if res == -1:
556 errno = rposix.get_saved_errno()
557 raise IOError(errno, os.strerror(errno))
558 if self._skipnextlf:
559 c = c_getc(self._ll_file)
560 if c == ord('\n'):
561 self._newlinetypes |= NEWLINE_CRLF
562 res += 1
563 self._skipnextlf = False
564 elif c != EOF:
565 c_ungetc(c, self._ll_file)
566 return res
567
568 def fileno(self):
569 self._check_closed()
570 return intmask(c_fileno(self._ll_file))
571
572 def isatty(self):
573 self._check_closed()
574 return os.isatty(c_fileno(self._ll_file))
575
576 def __enter__(self):
577 return self
578
579 def __exit__(self, *args):
580 self.close()