blob: 145d93adeb156bb51be5e4d5e19e5ebb5f6760a3 [file] [log] [blame]
Guido van Rossuma9e20242007-03-08 00:43:48 +00001/* Author: Daniel Stutzbach */
2
3#define PY_SSIZE_T_CLEAN
4#include "Python.h"
Antoine Pitroue033e062010-10-29 10:38:18 +00005#include "structmember.h"
Benjamin Peterson2614cda2010-03-21 22:36:19 +00006#ifdef HAVE_SYS_TYPES_H
Guido van Rossuma9e20242007-03-08 00:43:48 +00007#include <sys/types.h>
Benjamin Peterson2614cda2010-03-21 22:36:19 +00008#endif
9#ifdef HAVE_SYS_STAT_H
Guido van Rossuma9e20242007-03-08 00:43:48 +000010#include <sys/stat.h>
Benjamin Peterson2614cda2010-03-21 22:36:19 +000011#endif
12#ifdef HAVE_FCNTL_H
Guido van Rossuma9e20242007-03-08 00:43:48 +000013#include <fcntl.h>
Benjamin Peterson2614cda2010-03-21 22:36:19 +000014#endif
Guido van Rossuma9e20242007-03-08 00:43:48 +000015#include <stddef.h> /* For offsetof */
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +000016#include "_iomodule.h"
Guido van Rossuma9e20242007-03-08 00:43:48 +000017
18/*
19 * Known likely problems:
20 *
21 * - Files larger then 2**32-1
22 * - Files with unicode filenames
23 * - Passing numbers greater than 2**32-1 when an integer is expected
24 * - Making it work on Windows and other oddball platforms
25 *
26 * To Do:
27 *
28 * - autoconfify header file inclusion
Guido van Rossuma9e20242007-03-08 00:43:48 +000029 */
30
31#ifdef MS_WINDOWS
32/* can simulate truncate with Win32 API functions; see file_truncate */
Thomas Hellerfdeee3a2007-07-12 11:21:36 +000033#define HAVE_FTRUNCATE
Guido van Rossuma9e20242007-03-08 00:43:48 +000034#define WIN32_LEAN_AND_MEAN
35#include <windows.h>
36#endif
37
Christian Heimesa872de52008-12-05 08:26:55 +000038#if BUFSIZ < (8*1024)
39#define SMALLCHUNK (8*1024)
40#elif (BUFSIZ >= (2 << 25))
41#error "unreasonable BUFSIZ > 64MB defined"
42#else
43#define SMALLCHUNK BUFSIZ
44#endif
45
Serhiy Storchakaf24131f2015-04-16 11:19:43 +030046/*[clinic input]
47module _io
48class _io.FileIO "fileio *" "&PyFileIO_Type"
49[clinic start generated code]*/
50/*[clinic end generated code: output=da39a3ee5e6b4b0d input=1c77708b41fda70c]*/
51
52/*[python input]
53class io_ssize_t_converter(CConverter):
54 type = 'Py_ssize_t'
55 converter = '_PyIO_ConvertSsize_t'
56[python start generated code]*/
57/*[python end generated code: output=da39a3ee5e6b4b0d input=d0a811d3cbfd1b33]*/
58
Guido van Rossuma9e20242007-03-08 00:43:48 +000059typedef struct {
Antoine Pitrouae4b4722010-05-05 16:31:07 +000060 PyObject_HEAD
61 int fd;
Charles-François Natalidc3044c2012-01-09 22:40:02 +010062 unsigned int created : 1;
Antoine Pitrouae4b4722010-05-05 16:31:07 +000063 unsigned int readable : 1;
64 unsigned int writable : 1;
Antoine Pitroue93b63b2013-09-04 20:46:33 +020065 unsigned int appending : 1;
Antoine Pitrouae4b4722010-05-05 16:31:07 +000066 signed int seekable : 2; /* -1 means unknown */
67 unsigned int closefd : 1;
Antoine Pitrou796564c2013-07-30 19:59:21 +020068 char finalizing;
Antoine Pitroude687222014-06-29 20:07:28 -040069 unsigned int blksize;
Antoine Pitrouae4b4722010-05-05 16:31:07 +000070 PyObject *weakreflist;
71 PyObject *dict;
Benjamin Peterson680bf1a2009-06-12 02:07:12 +000072} fileio;
Guido van Rossuma9e20242007-03-08 00:43:48 +000073
Collin Winteraf334382007-03-08 21:46:15 +000074PyTypeObject PyFileIO_Type;
75
Victor Stinnerd9d04192013-11-06 23:50:10 +010076_Py_IDENTIFIER(name);
77
Guido van Rossuma9e20242007-03-08 00:43:48 +000078#define PyFileIO_Check(op) (PyObject_TypeCheck((op), &PyFileIO_Type))
79
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +000080int
81_PyFileIO_closed(PyObject *self)
82{
Antoine Pitrouae4b4722010-05-05 16:31:07 +000083 return ((fileio *)self)->fd < 0;
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +000084}
Antoine Pitrou08838b62009-01-21 00:55:13 +000085
Antoine Pitroue033e062010-10-29 10:38:18 +000086/* Because this can call arbitrary code, it shouldn't be called when
87 the refcount is 0 (that is, not directly from tp_dealloc unless
88 the refcount has been temporarily re-incremented). */
89static PyObject *
90fileio_dealloc_warn(fileio *self, PyObject *source)
91{
92 if (self->fd >= 0 && self->closefd) {
93 PyObject *exc, *val, *tb;
94 PyErr_Fetch(&exc, &val, &tb);
95 if (PyErr_WarnFormat(PyExc_ResourceWarning, 1,
96 "unclosed file %R", source)) {
97 /* Spurious errors can appear at shutdown */
98 if (PyErr_ExceptionMatches(PyExc_Warning))
99 PyErr_WriteUnraisable((PyObject *) self);
100 }
101 PyErr_Restore(exc, val, tb);
102 }
103 Py_RETURN_NONE;
104}
105
Antoine Pitrou7fb111b2009-03-04 11:14:01 +0000106static PyObject *
107portable_lseek(int fd, PyObject *posobj, int whence);
108
Antoine Pitroua28fcfd2009-03-13 23:42:55 +0000109static PyObject *portable_lseek(int fd, PyObject *posobj, int whence);
110
Kristján Valur Jónsson19288c22008-12-18 17:15:54 +0000111/* Returns 0 on success, -1 with exception set on failure. */
Neal Norwitz88b44da2007-08-12 17:23:54 +0000112static int
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000113internal_close(fileio *self)
Guido van Rossuma9e20242007-03-08 00:43:48 +0000114{
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000115 int err = 0;
116 int save_errno = 0;
117 if (self->fd >= 0) {
118 int fd = self->fd;
119 self->fd = -1;
120 /* fd is accessible and someone else may have closed it */
121 if (_PyVerify_fd(fd)) {
122 Py_BEGIN_ALLOW_THREADS
Steve Dower8fc89802015-04-12 00:26:27 -0400123 _Py_BEGIN_SUPPRESS_IPH
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000124 err = close(fd);
125 if (err < 0)
126 save_errno = errno;
Steve Dower8fc89802015-04-12 00:26:27 -0400127 _Py_END_SUPPRESS_IPH
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000128 Py_END_ALLOW_THREADS
129 } else {
130 save_errno = errno;
131 err = -1;
132 }
133 }
134 if (err < 0) {
135 errno = save_errno;
136 PyErr_SetFromErrno(PyExc_IOError);
137 return -1;
138 }
139 return 0;
Neal Norwitz88b44da2007-08-12 17:23:54 +0000140}
141
Serhiy Storchakaf24131f2015-04-16 11:19:43 +0300142/*[clinic input]
143_io.FileIO.close
144
145Close the file.
146
147A closed file cannot be used for further I/O operations. close() may be
148called more than once without error.
149[clinic start generated code]*/
150
Neal Norwitz88b44da2007-08-12 17:23:54 +0000151static PyObject *
Serhiy Storchakaf24131f2015-04-16 11:19:43 +0300152_io_FileIO_close_impl(fileio *self)
153/*[clinic end generated code: output=7737a319ef3bad0b input=f35231760d54a522]*/
Neal Norwitz88b44da2007-08-12 17:23:54 +0000154{
Serhiy Storchakaa3712a92015-02-21 00:35:09 +0200155 PyObject *res;
156 PyObject *exc, *val, *tb;
157 int rc;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +0200158 _Py_IDENTIFIER(close);
Serhiy Storchakaa3712a92015-02-21 00:35:09 +0200159 res = _PyObject_CallMethodId((PyObject*)&PyRawIOBase_Type,
160 &PyId_close, "O", self);
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000161 if (!self->closefd) {
162 self->fd = -1;
Serhiy Storchakaa3712a92015-02-21 00:35:09 +0200163 return res;
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000164 }
Serhiy Storchakaa3712a92015-02-21 00:35:09 +0200165 if (res == NULL)
166 PyErr_Fetch(&exc, &val, &tb);
Antoine Pitrou796564c2013-07-30 19:59:21 +0200167 if (self->finalizing) {
Antoine Pitroue033e062010-10-29 10:38:18 +0000168 PyObject *r = fileio_dealloc_warn(self, (PyObject *) self);
169 if (r)
170 Py_DECREF(r);
171 else
172 PyErr_Clear();
173 }
Serhiy Storchakaa3712a92015-02-21 00:35:09 +0200174 rc = internal_close(self);
175 if (res == NULL)
176 _PyErr_ChainExceptions(exc, val, tb);
177 if (rc < 0)
178 Py_CLEAR(res);
179 return res;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000180}
181
182static PyObject *
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000183fileio_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
Guido van Rossuma9e20242007-03-08 00:43:48 +0000184{
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000185 fileio *self;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000186
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000187 assert(type != NULL && type->tp_alloc != NULL);
Guido van Rossuma9e20242007-03-08 00:43:48 +0000188
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000189 self = (fileio *) type->tp_alloc(type, 0);
190 if (self != NULL) {
191 self->fd = -1;
Charles-François Natalidc3044c2012-01-09 22:40:02 +0100192 self->created = 0;
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000193 self->readable = 0;
194 self->writable = 0;
Antoine Pitroue93b63b2013-09-04 20:46:33 +0200195 self->appending = 0;
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000196 self->seekable = -1;
Antoine Pitroude687222014-06-29 20:07:28 -0400197 self->blksize = 0;
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000198 self->closefd = 1;
199 self->weakreflist = NULL;
200 }
Guido van Rossuma9e20242007-03-08 00:43:48 +0000201
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000202 return (PyObject *) self;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000203}
204
Victor Stinnerdaf45552013-08-28 00:53:59 +0200205#ifdef O_CLOEXEC
206extern int _Py_open_cloexec_works;
207#endif
Guido van Rossuma9e20242007-03-08 00:43:48 +0000208
Serhiy Storchakaf24131f2015-04-16 11:19:43 +0300209/*[clinic input]
210_io.FileIO.__init__
211 file as nameobj: object
212 mode: str = "r"
213 closefd: int(c_default="1") = True
214 opener: object = None
215
216Open a file.
217
218The mode can be 'r' (default), 'w', 'x' or 'a' for reading,
219writing, exclusive creation or appending. The file will be created if it
220doesn't exist when opened for writing or appending; it will be truncated
221when opened for writing. A FileExistsError will be raised if it already
222exists when opened for creating. Opening a file for creating implies
223writing so this mode behaves in a similar way to 'w'.Add a '+' to the mode
224to allow simultaneous reading and writing. A custom opener can be used by
225passing a callable as *opener*. The underlying file descriptor for the file
226object is then obtained by calling opener with (*name*, *flags*).
227*opener* must return an open file descriptor (passing os.open as *opener*
228results in functionality similar to passing None).
229[clinic start generated code]*/
230
Guido van Rossuma9e20242007-03-08 00:43:48 +0000231static int
Serhiy Storchakaf24131f2015-04-16 11:19:43 +0300232_io_FileIO___init___impl(fileio *self, PyObject *nameobj, const char *mode,
233 int closefd, PyObject *opener)
234/*[clinic end generated code: output=23413f68e6484bbd input=193164e293d6c097]*/
Guido van Rossuma9e20242007-03-08 00:43:48 +0000235{
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000236 const char *name = NULL;
Serhiy Storchakaf24131f2015-04-16 11:19:43 +0300237 PyObject *stringobj = NULL;
238 const char *s;
Thomas Helleraf2be262007-07-12 11:03:13 +0000239#ifdef MS_WINDOWS
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000240 Py_UNICODE *widename = NULL;
Thomas Helleraf2be262007-07-12 11:03:13 +0000241#endif
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000242 int ret = 0;
Antoine Pitroue93b63b2013-09-04 20:46:33 +0200243 int rwa = 0, plus = 0;
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000244 int flags = 0;
245 int fd = -1;
Hynek Schlawack9ed8b4e2012-06-21 20:20:25 +0200246 int fd_is_own = 0;
Victor Stinnerdaf45552013-08-28 00:53:59 +0200247#ifdef O_CLOEXEC
248 int *atomic_flag_works = &_Py_open_cloexec_works;
249#elif !defined(MS_WINDOWS)
250 int *atomic_flag_works = NULL;
251#endif
Steve Dowerf2f373f2015-02-21 08:44:05 -0800252 struct _Py_stat_struct fdfstat;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +0000253 int async_err = 0;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000254
Christian Heimes82adeff2015-04-16 17:21:54 +0200255 assert(PyFileIO_Check(self));
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000256 if (self->fd >= 0) {
Hynek Schlawack2cc71562012-05-25 10:05:53 +0200257 if (self->closefd) {
258 /* Have to close the existing file first. */
259 if (internal_close(self) < 0)
260 return -1;
261 }
262 else
263 self->fd = -1;
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000264 }
Guido van Rossuma9e20242007-03-08 00:43:48 +0000265
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000266 if (PyFloat_Check(nameobj)) {
267 PyErr_SetString(PyExc_TypeError,
268 "integer argument expected, got float");
269 return -1;
270 }
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000271
Serhiy Storchaka78980432013-01-15 01:12:17 +0200272 fd = _PyLong_AsInt(nameobj);
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000273 if (fd < 0) {
274 if (!PyErr_Occurred()) {
275 PyErr_SetString(PyExc_ValueError,
Serhiy Storchaka3d2279f2015-04-10 16:08:43 +0300276 "negative file descriptor");
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000277 return -1;
278 }
279 PyErr_Clear();
280 }
Guido van Rossumb0428152007-04-08 17:44:42 +0000281
Hirokazu Yamamoto8223c242009-05-17 04:21:53 +0000282#ifdef MS_WINDOWS
Victor Stinnerfe9a8612011-09-29 23:19:04 +0200283 if (PyUnicode_Check(nameobj)) {
Antoine Pitrou13348842012-01-29 18:36:34 +0100284 int rv = _PyUnicode_HasNULChars(nameobj);
285 if (rv) {
286 if (rv != -1)
Serhiy Storchakad8a14472014-09-06 20:07:17 +0300287 PyErr_SetString(PyExc_ValueError, "embedded null character");
Antoine Pitrou13348842012-01-29 18:36:34 +0100288 return -1;
289 }
Victor Stinnerfe9a8612011-09-29 23:19:04 +0200290 widename = PyUnicode_AsUnicode(nameobj);
291 if (widename == NULL)
292 return -1;
293 } else
Guido van Rossuma9e20242007-03-08 00:43:48 +0000294#endif
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000295 if (fd < 0)
296 {
Antoine Pitrou13348842012-01-29 18:36:34 +0100297 if (!PyUnicode_FSConverter(nameobj, &stringobj)) {
298 return -1;
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000299 }
Antoine Pitrou13348842012-01-29 18:36:34 +0100300 name = PyBytes_AS_STRING(stringobj);
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000301 }
Guido van Rossuma9e20242007-03-08 00:43:48 +0000302
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000303 s = mode;
304 while (*s) {
305 switch (*s++) {
Charles-François Natalidc3044c2012-01-09 22:40:02 +0100306 case 'x':
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000307 if (rwa) {
308 bad_mode:
309 PyErr_SetString(PyExc_ValueError,
Charles-François Natalidc3044c2012-01-09 22:40:02 +0100310 "Must have exactly one of create/read/write/append "
Georg Brandl28928ae2010-10-21 13:45:52 +0000311 "mode and at most one plus");
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000312 goto error;
313 }
314 rwa = 1;
Charles-François Natalidc3044c2012-01-09 22:40:02 +0100315 self->created = 1;
316 self->writable = 1;
317 flags |= O_EXCL | O_CREAT;
318 break;
319 case 'r':
320 if (rwa)
321 goto bad_mode;
322 rwa = 1;
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000323 self->readable = 1;
324 break;
325 case 'w':
326 if (rwa)
327 goto bad_mode;
328 rwa = 1;
329 self->writable = 1;
330 flags |= O_CREAT | O_TRUNC;
331 break;
332 case 'a':
333 if (rwa)
334 goto bad_mode;
335 rwa = 1;
336 self->writable = 1;
Antoine Pitroue93b63b2013-09-04 20:46:33 +0200337 self->appending = 1;
338 flags |= O_APPEND | O_CREAT;
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000339 break;
340 case 'b':
341 break;
342 case '+':
343 if (plus)
344 goto bad_mode;
345 self->readable = self->writable = 1;
346 plus = 1;
347 break;
348 default:
349 PyErr_Format(PyExc_ValueError,
350 "invalid mode: %.200s", mode);
351 goto error;
352 }
353 }
Guido van Rossuma9e20242007-03-08 00:43:48 +0000354
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000355 if (!rwa)
356 goto bad_mode;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000357
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000358 if (self->readable && self->writable)
359 flags |= O_RDWR;
360 else if (self->readable)
361 flags |= O_RDONLY;
362 else
363 flags |= O_WRONLY;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000364
365#ifdef O_BINARY
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000366 flags |= O_BINARY;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000367#endif
368
Victor Stinnerdaf45552013-08-28 00:53:59 +0200369#ifdef MS_WINDOWS
370 flags |= O_NOINHERIT;
371#elif defined(O_CLOEXEC)
372 flags |= O_CLOEXEC;
373#endif
Walter Dörwald0e411482007-06-06 16:55:38 +0000374
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000375 if (fd >= 0) {
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000376 self->fd = fd;
377 self->closefd = closefd;
378 }
379 else {
380 self->closefd = 1;
381 if (!closefd) {
382 PyErr_SetString(PyExc_ValueError,
383 "Cannot use closefd=False with file name");
384 goto error;
385 }
Guido van Rossum2dced8b2007-10-30 17:27:30 +0000386
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000387 errno = 0;
Ross Lagerwall59142db2011-10-31 20:34:46 +0200388 if (opener == Py_None) {
Charles-François Natali6e6c59b2015-02-07 13:27:50 +0000389 do {
390 Py_BEGIN_ALLOW_THREADS
Thomas Helleraf2be262007-07-12 11:03:13 +0000391#ifdef MS_WINDOWS
Charles-François Natali6e6c59b2015-02-07 13:27:50 +0000392 if (widename != NULL)
393 self->fd = _wopen(widename, flags, 0666);
394 else
Thomas Helleraf2be262007-07-12 11:03:13 +0000395#endif
Charles-François Natali6e6c59b2015-02-07 13:27:50 +0000396 self->fd = open(name, flags, 0666);
Charles-François Natali6e6c59b2015-02-07 13:27:50 +0000397 Py_END_ALLOW_THREADS
398 } while (self->fd < 0 && errno == EINTR &&
399 !(async_err = PyErr_CheckSignals()));
Victor Stinner9672da72015-03-04 18:40:10 +0100400
401 if (async_err)
402 goto error;
Victor Stinnerdaf45552013-08-28 00:53:59 +0200403 }
404 else {
405 PyObject *fdobj;
406
407#ifndef MS_WINDOWS
408 /* the opener may clear the atomic flag */
409 atomic_flag_works = NULL;
410#endif
411
412 fdobj = PyObject_CallFunction(opener, "Oi", nameobj, flags);
Ross Lagerwall59142db2011-10-31 20:34:46 +0200413 if (fdobj == NULL)
414 goto error;
415 if (!PyLong_Check(fdobj)) {
416 Py_DECREF(fdobj);
417 PyErr_SetString(PyExc_TypeError,
418 "expected integer from opener");
419 goto error;
420 }
421
Serhiy Storchaka78980432013-01-15 01:12:17 +0200422 self->fd = _PyLong_AsInt(fdobj);
Ross Lagerwall59142db2011-10-31 20:34:46 +0200423 Py_DECREF(fdobj);
424 if (self->fd == -1) {
425 goto error;
426 }
427 }
428
Hynek Schlawack7f59fd72012-06-22 09:32:22 +0200429 fd_is_own = 1;
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000430 if (self->fd < 0) {
Victor Stinner9672da72015-03-04 18:40:10 +0100431 PyErr_SetFromErrnoWithFilenameObject(PyExc_OSError, nameobj);
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000432 goto error;
433 }
Victor Stinnerdaf45552013-08-28 00:53:59 +0200434
435#ifndef MS_WINDOWS
436 if (_Py_set_inheritable(self->fd, 0, atomic_flag_works) < 0)
437 goto error;
438#endif
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000439 }
Antoine Pitroude687222014-06-29 20:07:28 -0400440
441 self->blksize = DEFAULT_BUFFER_SIZE;
Victor Stinnere134a7f2015-03-30 10:09:31 +0200442 if (_Py_fstat(self->fd, &fdfstat) < 0)
Antoine Pitrou9235b252012-07-06 18:48:24 +0200443 goto error;
Antoine Pitroude687222014-06-29 20:07:28 -0400444#if defined(S_ISDIR) && defined(EISDIR)
445 /* On Unix, open will succeed for directories.
446 In Python, there should be no file objects referring to
447 directories, so we need a check. */
448 if (S_ISDIR(fdfstat.st_mode)) {
449 errno = EISDIR;
450 PyErr_SetFromErrnoWithFilenameObject(PyExc_IOError, nameobj);
451 goto error;
452 }
453#endif /* defined(S_ISDIR) */
454#ifdef HAVE_STRUCT_STAT_ST_BLKSIZE
455 if (fdfstat.st_blksize > 1)
456 self->blksize = fdfstat.st_blksize;
457#endif /* HAVE_STRUCT_STAT_ST_BLKSIZE */
Guido van Rossuma9e20242007-03-08 00:43:48 +0000458
Victor Stinner89e34362011-01-07 18:47:22 +0000459#if defined(MS_WINDOWS) || defined(__CYGWIN__)
460 /* don't translate newlines (\r\n <=> \n) */
461 _setmode(self->fd, O_BINARY);
462#endif
463
Victor Stinnerd9d04192013-11-06 23:50:10 +0100464 if (_PyObject_SetAttrId((PyObject *)self, &PyId_name, nameobj) < 0)
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000465 goto error;
Antoine Pitrou08838b62009-01-21 00:55:13 +0000466
Antoine Pitroue93b63b2013-09-04 20:46:33 +0200467 if (self->appending) {
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000468 /* For consistent behaviour, we explicitly seek to the
469 end of file (otherwise, it might be done only on the
470 first write()). */
471 PyObject *pos = portable_lseek(self->fd, NULL, 2);
Hynek Schlawack9ed8b4e2012-06-21 20:20:25 +0200472 if (pos == NULL)
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000473 goto error;
474 Py_DECREF(pos);
475 }
Antoine Pitrou7fb111b2009-03-04 11:14:01 +0000476
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000477 goto done;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000478
479 error:
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000480 ret = -1;
Hynek Schlawack9ed8b4e2012-06-21 20:20:25 +0200481 if (!fd_is_own)
482 self->fd = -1;
Benjamin Petersonbbb04122010-10-30 23:16:28 +0000483 if (self->fd >= 0)
484 internal_close(self);
Guido van Rossum53807da2007-04-10 19:01:47 +0000485
Guido van Rossuma9e20242007-03-08 00:43:48 +0000486 done:
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000487 Py_CLEAR(stringobj);
488 return ret;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000489}
490
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000491static int
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000492fileio_traverse(fileio *self, visitproc visit, void *arg)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000493{
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000494 Py_VISIT(self->dict);
495 return 0;
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000496}
497
498static int
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000499fileio_clear(fileio *self)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000500{
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000501 Py_CLEAR(self->dict);
502 return 0;
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000503}
504
Guido van Rossuma9e20242007-03-08 00:43:48 +0000505static void
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000506fileio_dealloc(fileio *self)
Guido van Rossuma9e20242007-03-08 00:43:48 +0000507{
Antoine Pitrou796564c2013-07-30 19:59:21 +0200508 self->finalizing = 1;
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000509 if (_PyIOBase_finalize((PyObject *) self) < 0)
510 return;
511 _PyObject_GC_UNTRACK(self);
512 if (self->weakreflist != NULL)
513 PyObject_ClearWeakRefs((PyObject *) self);
514 Py_CLEAR(self->dict);
515 Py_TYPE(self)->tp_free((PyObject *)self);
Guido van Rossuma9e20242007-03-08 00:43:48 +0000516}
517
518static PyObject *
519err_closed(void)
520{
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000521 PyErr_SetString(PyExc_ValueError, "I/O operation on closed file");
522 return NULL;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000523}
524
525static PyObject *
Guido van Rossum53807da2007-04-10 19:01:47 +0000526err_mode(char *action)
527{
Antoine Pitrou712cb732013-12-21 15:51:54 +0100528 _PyIO_State *state = IO_STATE();
529 if (state != NULL)
530 PyErr_Format(state->unsupported_operation,
531 "File not open for %s", action);
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000532 return NULL;
Guido van Rossum53807da2007-04-10 19:01:47 +0000533}
534
Serhiy Storchakaf24131f2015-04-16 11:19:43 +0300535/*[clinic input]
536_io.FileIO.fileno
537
538Return the underlying file descriptor (an integer).
539[clinic start generated code]*/
540
Guido van Rossum53807da2007-04-10 19:01:47 +0000541static PyObject *
Serhiy Storchakaf24131f2015-04-16 11:19:43 +0300542_io_FileIO_fileno_impl(fileio *self)
543/*[clinic end generated code: output=a9626ce5398ece90 input=0b9b2de67335ada3]*/
Guido van Rossuma9e20242007-03-08 00:43:48 +0000544{
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000545 if (self->fd < 0)
546 return err_closed();
547 return PyLong_FromLong((long) self->fd);
Guido van Rossuma9e20242007-03-08 00:43:48 +0000548}
549
Serhiy Storchakaf24131f2015-04-16 11:19:43 +0300550/*[clinic input]
551_io.FileIO.readable
552
553True if file was opened in a read mode.
554[clinic start generated code]*/
555
Guido van Rossuma9e20242007-03-08 00:43:48 +0000556static PyObject *
Serhiy Storchakaf24131f2015-04-16 11:19:43 +0300557_io_FileIO_readable_impl(fileio *self)
558/*[clinic end generated code: output=640744a6150fe9ba input=a3fdfed6eea721c5]*/
Guido van Rossuma9e20242007-03-08 00:43:48 +0000559{
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000560 if (self->fd < 0)
561 return err_closed();
562 return PyBool_FromLong((long) self->readable);
Guido van Rossuma9e20242007-03-08 00:43:48 +0000563}
564
Serhiy Storchakaf24131f2015-04-16 11:19:43 +0300565/*[clinic input]
566_io.FileIO.writable
567
568True if file was opened in a write mode.
569[clinic start generated code]*/
570
Guido van Rossuma9e20242007-03-08 00:43:48 +0000571static PyObject *
Serhiy Storchakaf24131f2015-04-16 11:19:43 +0300572_io_FileIO_writable_impl(fileio *self)
573/*[clinic end generated code: output=96cefc5446e89977 input=c204a808ca2e1748]*/
Guido van Rossuma9e20242007-03-08 00:43:48 +0000574{
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000575 if (self->fd < 0)
576 return err_closed();
577 return PyBool_FromLong((long) self->writable);
Guido van Rossuma9e20242007-03-08 00:43:48 +0000578}
579
Serhiy Storchakaf24131f2015-04-16 11:19:43 +0300580/*[clinic input]
581_io.FileIO.seekable
582
583True if file supports random-access.
584[clinic start generated code]*/
585
Guido van Rossuma9e20242007-03-08 00:43:48 +0000586static PyObject *
Serhiy Storchakaf24131f2015-04-16 11:19:43 +0300587_io_FileIO_seekable_impl(fileio *self)
588/*[clinic end generated code: output=47909ca0a42e9287 input=c8e5554d2fd63c7f]*/
Guido van Rossuma9e20242007-03-08 00:43:48 +0000589{
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000590 if (self->fd < 0)
591 return err_closed();
592 if (self->seekable < 0) {
593 PyObject *pos = portable_lseek(self->fd, NULL, SEEK_CUR);
594 if (pos == NULL) {
595 PyErr_Clear();
596 self->seekable = 0;
597 } else {
598 Py_DECREF(pos);
599 self->seekable = 1;
600 }
601 }
602 return PyBool_FromLong((long) self->seekable);
Guido van Rossuma9e20242007-03-08 00:43:48 +0000603}
604
Serhiy Storchakaf24131f2015-04-16 11:19:43 +0300605/*[clinic input]
606_io.FileIO.readinto
607 buffer: Py_buffer(types={'rwbuffer'})
608 /
609
610Same as RawIOBase.readinto().
611[clinic start generated code]*/
612
Guido van Rossuma9e20242007-03-08 00:43:48 +0000613static PyObject *
Serhiy Storchakaf24131f2015-04-16 11:19:43 +0300614_io_FileIO_readinto_impl(fileio *self, Py_buffer *buffer)
615/*[clinic end generated code: output=b01a5a22c8415cb4 input=5edd8327498d468c]*/
Guido van Rossuma9e20242007-03-08 00:43:48 +0000616{
Victor Stinner66aab0c2015-03-19 22:53:20 +0100617 Py_ssize_t n;
618 int err;
Guido van Rossum53807da2007-04-10 19:01:47 +0000619
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000620 if (self->fd < 0)
621 return err_closed();
622 if (!self->readable)
623 return err_mode("reading");
Guido van Rossum53807da2007-04-10 19:01:47 +0000624
Serhiy Storchakaf24131f2015-04-16 11:19:43 +0300625 n = _Py_read(self->fd, buffer->buf, buffer->len);
Victor Stinner66aab0c2015-03-19 22:53:20 +0100626 /* copy errno because PyBuffer_Release() can indirectly modify it */
Antoine Pitrouc345ce12011-12-16 12:28:32 +0100627 err = errno;
Victor Stinner66aab0c2015-03-19 22:53:20 +0100628
629 if (n == -1) {
630 if (err == EAGAIN) {
631 PyErr_Clear();
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000632 Py_RETURN_NONE;
Victor Stinner66aab0c2015-03-19 22:53:20 +0100633 }
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000634 return NULL;
635 }
Guido van Rossuma9e20242007-03-08 00:43:48 +0000636
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000637 return PyLong_FromSsize_t(n);
Guido van Rossuma9e20242007-03-08 00:43:48 +0000638}
639
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000640static size_t
Richard Oudkerkaf7260e2013-05-17 23:34:42 +0100641new_buffersize(fileio *self, size_t currentsize)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000642{
Antoine Pitroua3f44572012-04-17 13:50:58 +0200643 size_t addend;
Richard Oudkerkaf7260e2013-05-17 23:34:42 +0100644
Nadeem Vawdad41a98b2011-10-13 13:34:16 +0200645 /* Expand the buffer by an amount proportional to the current size,
Antoine Pitroua3f44572012-04-17 13:50:58 +0200646 giving us amortized linear-time behavior. For bigger sizes, use a
647 less-than-double growth factor to avoid excessive allocation. */
Richard Oudkerkaf7260e2013-05-17 23:34:42 +0100648 assert(currentsize <= PY_SSIZE_T_MAX);
Antoine Pitroua3f44572012-04-17 13:50:58 +0200649 if (currentsize > 65536)
650 addend = currentsize >> 3;
651 else
652 addend = 256 + currentsize;
653 if (addend < SMALLCHUNK)
654 /* Avoid tiny read() calls. */
655 addend = SMALLCHUNK;
656 return addend + currentsize;
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000657}
658
Serhiy Storchakaf24131f2015-04-16 11:19:43 +0300659/*[clinic input]
660_io.FileIO.readall
661
662Read all data from the file, returned as bytes.
663
664In non-blocking mode, returns as much as is immediately available,
665or None if no data is available. Return an empty bytes object at EOF.
666[clinic start generated code]*/
667
Guido van Rossum7165cb12007-07-10 06:54:34 +0000668static PyObject *
Serhiy Storchakaf24131f2015-04-16 11:19:43 +0300669_io_FileIO_readall_impl(fileio *self)
670/*[clinic end generated code: output=faa0292b213b4022 input=dbdc137f55602834]*/
Guido van Rossum7165cb12007-07-10 06:54:34 +0000671{
Victor Stinnere134a7f2015-03-30 10:09:31 +0200672 struct _Py_stat_struct status;
Victor Stinnera2a64772011-10-11 22:45:02 +0200673 Py_off_t pos, end;
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000674 PyObject *result;
Richard Oudkerkaf7260e2013-05-17 23:34:42 +0100675 Py_ssize_t bytes_read = 0;
Victor Stinner66aab0c2015-03-19 22:53:20 +0100676 Py_ssize_t n;
Richard Oudkerkaf7260e2013-05-17 23:34:42 +0100677 size_t bufsize;
Guido van Rossum7165cb12007-07-10 06:54:34 +0000678
Victor Stinnerb79f28c2011-05-25 22:09:03 +0200679 if (self->fd < 0)
680 return err_closed();
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000681 if (!_PyVerify_fd(self->fd))
682 return PyErr_SetFromErrno(PyExc_IOError);
Kristján Valur Jónssona8abe862009-03-24 15:27:42 +0000683
Steve Dower8fc89802015-04-12 00:26:27 -0400684 _Py_BEGIN_SUPPRESS_IPH
Victor Stinner14b9b112013-06-25 00:37:25 +0200685#ifdef MS_WINDOWS
Victor Stinnere9d44ccb2011-05-26 00:16:44 +0200686 pos = _lseeki64(self->fd, 0L, SEEK_CUR);
687#else
688 pos = lseek(self->fd, 0L, SEEK_CUR);
689#endif
Steve Dower8fc89802015-04-12 00:26:27 -0400690 _Py_END_SUPPRESS_IPH
691
Victor Stinnere134a7f2015-03-30 10:09:31 +0200692 if (_Py_fstat_noraise(self->fd, &status) == 0)
693 end = status.st_size;
Victor Stinnere9d44ccb2011-05-26 00:16:44 +0200694 else
Victor Stinnera2a64772011-10-11 22:45:02 +0200695 end = (Py_off_t)-1;
Christian Heimesa872de52008-12-05 08:26:55 +0000696
Richard Oudkerkaf7260e2013-05-17 23:34:42 +0100697 if (end > 0 && end >= pos && pos >= 0 && end - pos < PY_SSIZE_T_MAX) {
698 /* This is probably a real file, so we try to allocate a
699 buffer one byte larger than the rest of the file. If the
700 calculation is right then we should get EOF without having
701 to enlarge the buffer. */
702 bufsize = (size_t)(end - pos + 1);
703 } else {
704 bufsize = SMALLCHUNK;
705 }
706
707 result = PyBytes_FromStringAndSize(NULL, bufsize);
708 if (result == NULL)
709 return NULL;
710
711 while (1) {
712 if (bytes_read >= (Py_ssize_t)bufsize) {
713 bufsize = new_buffersize(self, bytes_read);
714 if (bufsize > PY_SSIZE_T_MAX || bufsize <= 0) {
715 PyErr_SetString(PyExc_OverflowError,
716 "unbounded read returned more bytes "
Serhiy Storchakab817b772015-04-10 02:18:44 +0300717 "than a Python bytes object can hold");
Richard Oudkerkaf7260e2013-05-17 23:34:42 +0100718 Py_DECREF(result);
719 return NULL;
720 }
721
722 if (PyBytes_GET_SIZE(result) < (Py_ssize_t)bufsize) {
723 if (_PyBytes_Resize(&result, bufsize) < 0)
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000724 return NULL;
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000725 }
726 }
Victor Stinner9672da72015-03-04 18:40:10 +0100727
Victor Stinner66aab0c2015-03-19 22:53:20 +0100728 n = _Py_read(self->fd,
729 PyBytes_AS_STRING(result) + bytes_read,
730 bufsize - bytes_read);
Victor Stinner9672da72015-03-04 18:40:10 +0100731
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000732 if (n == 0)
733 break;
Victor Stinner66aab0c2015-03-19 22:53:20 +0100734 if (n == -1) {
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000735 if (errno == EAGAIN) {
Victor Stinner66aab0c2015-03-19 22:53:20 +0100736 PyErr_Clear();
Victor Stinnere10920f2014-07-02 22:59:31 +0200737 if (bytes_read > 0)
738 break;
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000739 Py_DECREF(result);
740 Py_RETURN_NONE;
741 }
742 Py_DECREF(result);
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000743 return NULL;
744 }
Richard Oudkerkaf7260e2013-05-17 23:34:42 +0100745 bytes_read += n;
Victor Stinnere9d44ccb2011-05-26 00:16:44 +0200746 pos += n;
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000747 }
Guido van Rossum7165cb12007-07-10 06:54:34 +0000748
Richard Oudkerkaf7260e2013-05-17 23:34:42 +0100749 if (PyBytes_GET_SIZE(result) > bytes_read) {
750 if (_PyBytes_Resize(&result, bytes_read) < 0)
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000751 return NULL;
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000752 }
753 return result;
Guido van Rossum7165cb12007-07-10 06:54:34 +0000754}
755
Serhiy Storchakaf24131f2015-04-16 11:19:43 +0300756/*[clinic input]
757_io.FileIO.read
758 size: io_ssize_t = -1
759 /
760
761Read at most size bytes, returned as bytes.
762
763Only makes one system call, so less data may be returned than requested.
764In non-blocking mode, returns None if no data is available.
765Return an empty bytes object at EOF.
766[clinic start generated code]*/
767
Guido van Rossuma9e20242007-03-08 00:43:48 +0000768static PyObject *
Serhiy Storchakaf24131f2015-04-16 11:19:43 +0300769_io_FileIO_read_impl(fileio *self, Py_ssize_t size)
770/*[clinic end generated code: output=42528d39dd0ca641 input=5c6caa5490c13a9b]*/
Guido van Rossuma9e20242007-03-08 00:43:48 +0000771{
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000772 char *ptr;
773 Py_ssize_t n;
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000774 PyObject *bytes;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000775
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000776 if (self->fd < 0)
777 return err_closed();
778 if (!self->readable)
779 return err_mode("reading");
Guido van Rossuma9e20242007-03-08 00:43:48 +0000780
Victor Stinner66aab0c2015-03-19 22:53:20 +0100781 if (size < 0)
Serhiy Storchakaf24131f2015-04-16 11:19:43 +0300782 return _io_FileIO_readall_impl(self);
Guido van Rossumc2f93dc2007-05-24 00:50:02 +0000783
Victor Stinner14b9b112013-06-25 00:37:25 +0200784#ifdef MS_WINDOWS
Victor Stinner66aab0c2015-03-19 22:53:20 +0100785 /* On Windows, the count parameter of read() is an int */
Victor Stinnerc655a722011-07-05 11:31:49 +0200786 if (size > INT_MAX)
787 size = INT_MAX;
788#endif
Victor Stinner66aab0c2015-03-19 22:53:20 +0100789
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000790 bytes = PyBytes_FromStringAndSize(NULL, size);
791 if (bytes == NULL)
792 return NULL;
793 ptr = PyBytes_AS_STRING(bytes);
Guido van Rossuma9e20242007-03-08 00:43:48 +0000794
Victor Stinner66aab0c2015-03-19 22:53:20 +0100795 n = _Py_read(self->fd, ptr, size);
796 if (n == -1) {
797 /* copy errno because Py_DECREF() can indirectly modify it */
Antoine Pitrouc345ce12011-12-16 12:28:32 +0100798 int err = errno;
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000799 Py_DECREF(bytes);
Victor Stinner66aab0c2015-03-19 22:53:20 +0100800 if (err == EAGAIN) {
801 PyErr_Clear();
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000802 Py_RETURN_NONE;
Victor Stinner66aab0c2015-03-19 22:53:20 +0100803 }
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000804 return NULL;
805 }
Guido van Rossuma9e20242007-03-08 00:43:48 +0000806
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000807 if (n != size) {
808 if (_PyBytes_Resize(&bytes, n) < 0) {
Victor Stinner85c761d2013-07-16 21:36:02 +0200809 Py_CLEAR(bytes);
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000810 return NULL;
811 }
812 }
Guido van Rossuma9e20242007-03-08 00:43:48 +0000813
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000814 return (PyObject *) bytes;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000815}
816
Serhiy Storchakaf24131f2015-04-16 11:19:43 +0300817/*[clinic input]
818_io.FileIO.write
819 b: Py_buffer
820 /
821
822Write bytes b to file, return number written.
823
824Only makes one system call, so not all of the data may be written.
825The number of bytes actually written is returned. In non-blocking mode,
826returns None if the write would block.
827[clinic start generated code]*/
828
Guido van Rossuma9e20242007-03-08 00:43:48 +0000829static PyObject *
Serhiy Storchakaf24131f2015-04-16 11:19:43 +0300830_io_FileIO_write_impl(fileio *self, Py_buffer *b)
831/*[clinic end generated code: output=b4059db3d363a2f7 input=ffbd8834f447ac31]*/
Guido van Rossuma9e20242007-03-08 00:43:48 +0000832{
Victor Stinner66aab0c2015-03-19 22:53:20 +0100833 Py_ssize_t n;
834 int err;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000835
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000836 if (self->fd < 0)
837 return err_closed();
838 if (!self->writable)
839 return err_mode("writing");
Guido van Rossum53807da2007-04-10 19:01:47 +0000840
Serhiy Storchakaf24131f2015-04-16 11:19:43 +0300841 n = _Py_write(self->fd, b->buf, b->len);
Victor Stinner66aab0c2015-03-19 22:53:20 +0100842 /* copy errno because PyBuffer_Release() can indirectly modify it */
Antoine Pitrouc345ce12011-12-16 12:28:32 +0100843 err = errno;
Martin v. Löwis423be952008-08-13 15:53:07 +0000844
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000845 if (n < 0) {
Victor Stinner66aab0c2015-03-19 22:53:20 +0100846 if (err == EAGAIN) {
847 PyErr_Clear();
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000848 Py_RETURN_NONE;
Victor Stinner66aab0c2015-03-19 22:53:20 +0100849 }
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000850 return NULL;
851 }
Guido van Rossuma9e20242007-03-08 00:43:48 +0000852
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000853 return PyLong_FromSsize_t(n);
Guido van Rossuma9e20242007-03-08 00:43:48 +0000854}
855
Guido van Rossum53807da2007-04-10 19:01:47 +0000856/* XXX Windows support below is likely incomplete */
857
Guido van Rossum53807da2007-04-10 19:01:47 +0000858/* Cribbed from posix_lseek() */
859static PyObject *
860portable_lseek(int fd, PyObject *posobj, int whence)
861{
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000862 Py_off_t pos, res;
Guido van Rossum53807da2007-04-10 19:01:47 +0000863
864#ifdef SEEK_SET
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000865 /* Turn 0, 1, 2 into SEEK_{SET,CUR,END} */
866 switch (whence) {
Guido van Rossum53807da2007-04-10 19:01:47 +0000867#if SEEK_SET != 0
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000868 case 0: whence = SEEK_SET; break;
Guido van Rossum53807da2007-04-10 19:01:47 +0000869#endif
870#if SEEK_CUR != 1
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000871 case 1: whence = SEEK_CUR; break;
Guido van Rossum53807da2007-04-10 19:01:47 +0000872#endif
Antoine Pitrou4f7945f2009-01-20 11:42:11 +0000873#if SEEK_END != 2
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000874 case 2: whence = SEEK_END; break;
Guido van Rossum53807da2007-04-10 19:01:47 +0000875#endif
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000876 }
Guido van Rossum53807da2007-04-10 19:01:47 +0000877#endif /* SEEK_SET */
878
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000879 if (posobj == NULL)
880 pos = 0;
881 else {
882 if(PyFloat_Check(posobj)) {
883 PyErr_SetString(PyExc_TypeError, "an integer is required");
884 return NULL;
885 }
Alexandre Vassalotti77250f42008-05-06 19:48:38 +0000886#if defined(HAVE_LARGEFILE_SUPPORT)
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000887 pos = PyLong_AsLongLong(posobj);
Guido van Rossum53807da2007-04-10 19:01:47 +0000888#else
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000889 pos = PyLong_AsLong(posobj);
Guido van Rossum53807da2007-04-10 19:01:47 +0000890#endif
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000891 if (PyErr_Occurred())
892 return NULL;
893 }
Guido van Rossum53807da2007-04-10 19:01:47 +0000894
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000895 if (_PyVerify_fd(fd)) {
896 Py_BEGIN_ALLOW_THREADS
Steve Dower8fc89802015-04-12 00:26:27 -0400897 _Py_BEGIN_SUPPRESS_IPH
Victor Stinner14b9b112013-06-25 00:37:25 +0200898#ifdef MS_WINDOWS
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000899 res = _lseeki64(fd, pos, whence);
Guido van Rossum53807da2007-04-10 19:01:47 +0000900#else
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000901 res = lseek(fd, pos, whence);
Guido van Rossum53807da2007-04-10 19:01:47 +0000902#endif
Steve Dower8fc89802015-04-12 00:26:27 -0400903 _Py_END_SUPPRESS_IPH
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000904 Py_END_ALLOW_THREADS
905 } else
906 res = -1;
907 if (res < 0)
908 return PyErr_SetFromErrno(PyExc_IOError);
Guido van Rossum53807da2007-04-10 19:01:47 +0000909
Alexandre Vassalotti77250f42008-05-06 19:48:38 +0000910#if defined(HAVE_LARGEFILE_SUPPORT)
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000911 return PyLong_FromLongLong(res);
Alexandre Vassalotti77250f42008-05-06 19:48:38 +0000912#else
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000913 return PyLong_FromLong(res);
Guido van Rossum53807da2007-04-10 19:01:47 +0000914#endif
915}
916
Serhiy Storchakaf24131f2015-04-16 11:19:43 +0300917/*[clinic input]
918_io.FileIO.seek
919 pos: object
920 whence: int = 0
921 /
Guido van Rossuma9e20242007-03-08 00:43:48 +0000922
Serhiy Storchakaf24131f2015-04-16 11:19:43 +0300923Move to new file position and return the file position.
924
925Argument offset is a byte count. Optional argument whence defaults to
926SEEK_SET or 0 (offset from start of file, offset should be >= 0); other values
927are SEEK_CUR or 1 (move relative to current position, positive or negative),
928and SEEK_END or 2 (move relative to end of file, usually negative, although
929many platforms allow seeking beyond the end of a file).
930
931Note that not all file objects are seekable.
932[clinic start generated code]*/
933
934static PyObject *
935_io_FileIO_seek_impl(fileio *self, PyObject *pos, int whence)
936/*[clinic end generated code: output=c976acdf054e6655 input=0439194b0774d454]*/
937{
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000938 if (self->fd < 0)
939 return err_closed();
Guido van Rossuma9e20242007-03-08 00:43:48 +0000940
Serhiy Storchakaf24131f2015-04-16 11:19:43 +0300941 return portable_lseek(self->fd, pos, whence);
Guido van Rossuma9e20242007-03-08 00:43:48 +0000942}
943
Serhiy Storchakaf24131f2015-04-16 11:19:43 +0300944/*[clinic input]
945_io.FileIO.tell
946
947Current file position.
948
949Can raise OSError for non seekable files.
950[clinic start generated code]*/
951
Guido van Rossuma9e20242007-03-08 00:43:48 +0000952static PyObject *
Serhiy Storchakaf24131f2015-04-16 11:19:43 +0300953_io_FileIO_tell_impl(fileio *self)
954/*[clinic end generated code: output=ffe2147058809d0b input=807e24ead4cec2f9]*/
Guido van Rossuma9e20242007-03-08 00:43:48 +0000955{
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000956 if (self->fd < 0)
957 return err_closed();
Guido van Rossuma9e20242007-03-08 00:43:48 +0000958
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000959 return portable_lseek(self->fd, NULL, 1);
Guido van Rossuma9e20242007-03-08 00:43:48 +0000960}
961
Thomas Hellerc6a55ee2007-07-11 12:45:46 +0000962#ifdef HAVE_FTRUNCATE
Serhiy Storchakaf24131f2015-04-16 11:19:43 +0300963/*[clinic input]
964_io.FileIO.truncate
965 size as posobj: object = NULL
966 /
967
968Truncate the file to at most size bytes and return the truncated size.
969
970Size defaults to the current file position, as returned by tell().
971The current file position is changed to the value of size.
972[clinic start generated code]*/
973
Guido van Rossuma9e20242007-03-08 00:43:48 +0000974static PyObject *
Serhiy Storchakaf24131f2015-04-16 11:19:43 +0300975_io_FileIO_truncate_impl(fileio *self, PyObject *posobj)
976/*[clinic end generated code: output=e49ca7a916c176fa input=9026af44686b7318]*/
Guido van Rossuma9e20242007-03-08 00:43:48 +0000977{
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000978 Py_off_t pos;
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000979 int ret;
980 int fd;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000981
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000982 fd = self->fd;
983 if (fd < 0)
984 return err_closed();
985 if (!self->writable)
986 return err_mode("writing");
Guido van Rossuma9e20242007-03-08 00:43:48 +0000987
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000988 if (posobj == Py_None || posobj == NULL) {
989 /* Get the current position. */
990 posobj = portable_lseek(fd, NULL, 1);
991 if (posobj == NULL)
992 return NULL;
993 }
994 else {
995 Py_INCREF(posobj);
996 }
Guido van Rossum53807da2007-04-10 19:01:47 +0000997
Antoine Pitrou905a2ff2010-01-31 22:47:27 +0000998#if defined(HAVE_LARGEFILE_SUPPORT)
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000999 pos = PyLong_AsLongLong(posobj);
Antoine Pitrou905a2ff2010-01-31 22:47:27 +00001000#else
Antoine Pitrouae4b4722010-05-05 16:31:07 +00001001 pos = PyLong_AsLong(posobj);
Antoine Pitrou905a2ff2010-01-31 22:47:27 +00001002#endif
Antoine Pitrouae4b4722010-05-05 16:31:07 +00001003 if (PyErr_Occurred()){
1004 Py_DECREF(posobj);
1005 return NULL;
1006 }
Antoine Pitrou905a2ff2010-01-31 22:47:27 +00001007
Antoine Pitrouae4b4722010-05-05 16:31:07 +00001008 Py_BEGIN_ALLOW_THREADS
Steve Dowera1c7e722015-04-12 00:26:43 -04001009 _Py_BEGIN_SUPPRESS_IPH
Antoine Pitrouae4b4722010-05-05 16:31:07 +00001010 errno = 0;
Steve Dowerfe0a41a2015-03-20 19:50:46 -07001011#ifdef MS_WINDOWS
1012 ret = _chsize_s(fd, pos);
1013#else
Antoine Pitrouae4b4722010-05-05 16:31:07 +00001014 ret = ftruncate(fd, pos);
Steve Dowerfe0a41a2015-03-20 19:50:46 -07001015#endif
Steve Dowera1c7e722015-04-12 00:26:43 -04001016 _Py_END_SUPPRESS_IPH
Antoine Pitrouae4b4722010-05-05 16:31:07 +00001017 Py_END_ALLOW_THREADS
Antoine Pitrou905a2ff2010-01-31 22:47:27 +00001018
Antoine Pitrouae4b4722010-05-05 16:31:07 +00001019 if (ret != 0) {
1020 Py_DECREF(posobj);
1021 PyErr_SetFromErrno(PyExc_IOError);
1022 return NULL;
1023 }
Guido van Rossuma9e20242007-03-08 00:43:48 +00001024
Antoine Pitrouae4b4722010-05-05 16:31:07 +00001025 return posobj;
Guido van Rossuma9e20242007-03-08 00:43:48 +00001026}
Antoine Pitrou905a2ff2010-01-31 22:47:27 +00001027#endif /* HAVE_FTRUNCATE */
Guido van Rossum53807da2007-04-10 19:01:47 +00001028
1029static char *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +00001030mode_string(fileio *self)
Guido van Rossum53807da2007-04-10 19:01:47 +00001031{
Charles-François Natalidc3044c2012-01-09 22:40:02 +01001032 if (self->created) {
1033 if (self->readable)
1034 return "xb+";
1035 else
1036 return "xb";
1037 }
Antoine Pitroue93b63b2013-09-04 20:46:33 +02001038 if (self->appending) {
1039 if (self->readable)
1040 return "ab+";
1041 else
1042 return "ab";
1043 }
1044 else if (self->readable) {
Antoine Pitrouae4b4722010-05-05 16:31:07 +00001045 if (self->writable)
1046 return "rb+";
1047 else
1048 return "rb";
1049 }
1050 else
1051 return "wb";
Guido van Rossum53807da2007-04-10 19:01:47 +00001052}
Guido van Rossuma9e20242007-03-08 00:43:48 +00001053
1054static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +00001055fileio_repr(fileio *self)
Guido van Rossuma9e20242007-03-08 00:43:48 +00001056{
Antoine Pitrouae4b4722010-05-05 16:31:07 +00001057 PyObject *nameobj, *res;
Guido van Rossuma9e20242007-03-08 00:43:48 +00001058
Antoine Pitrouae4b4722010-05-05 16:31:07 +00001059 if (self->fd < 0)
1060 return PyUnicode_FromFormat("<_io.FileIO [closed]>");
Antoine Pitrou716c4442009-05-23 19:04:03 +00001061
Martin v. Löwis767046a2011-10-14 15:35:36 +02001062 nameobj = _PyObject_GetAttrId((PyObject *) self, &PyId_name);
Antoine Pitrouae4b4722010-05-05 16:31:07 +00001063 if (nameobj == NULL) {
1064 if (PyErr_ExceptionMatches(PyExc_AttributeError))
1065 PyErr_Clear();
1066 else
1067 return NULL;
Robert Collins933430a2014-10-18 13:32:43 +13001068 res = PyUnicode_FromFormat(
Serhiy Storchaka4954f9f2014-12-02 23:39:56 +02001069 "<_io.FileIO fd=%d mode='%s' closefd=%s>",
1070 self->fd, mode_string(self), self->closefd ? "True" : "False");
Antoine Pitrouae4b4722010-05-05 16:31:07 +00001071 }
1072 else {
Robert Collins933430a2014-10-18 13:32:43 +13001073 res = PyUnicode_FromFormat(
Serhiy Storchaka4954f9f2014-12-02 23:39:56 +02001074 "<_io.FileIO name=%R mode='%s' closefd=%s>",
1075 nameobj, mode_string(self), self->closefd ? "True" : "False");
Antoine Pitrouae4b4722010-05-05 16:31:07 +00001076 Py_DECREF(nameobj);
1077 }
1078 return res;
Guido van Rossuma9e20242007-03-08 00:43:48 +00001079}
1080
Serhiy Storchakaf24131f2015-04-16 11:19:43 +03001081/*[clinic input]
1082_io.FileIO.isatty
1083
1084True if the file is connected to a TTY device.
1085[clinic start generated code]*/
1086
Guido van Rossuma9e20242007-03-08 00:43:48 +00001087static PyObject *
Serhiy Storchakaf24131f2015-04-16 11:19:43 +03001088_io_FileIO_isatty_impl(fileio *self)
1089/*[clinic end generated code: output=932c39924e9a8070 input=cd94ca1f5e95e843]*/
Guido van Rossuma9e20242007-03-08 00:43:48 +00001090{
Antoine Pitrouae4b4722010-05-05 16:31:07 +00001091 long res;
Guido van Rossum53807da2007-04-10 19:01:47 +00001092
Antoine Pitrouae4b4722010-05-05 16:31:07 +00001093 if (self->fd < 0)
1094 return err_closed();
1095 Py_BEGIN_ALLOW_THREADS
Steve Dower8fc89802015-04-12 00:26:27 -04001096 _Py_BEGIN_SUPPRESS_IPH
1097 if (_PyVerify_fd(self->fd))
1098 res = isatty(self->fd);
1099 else
1100 res = 0;
1101 _Py_END_SUPPRESS_IPH
Antoine Pitrouae4b4722010-05-05 16:31:07 +00001102 Py_END_ALLOW_THREADS
1103 return PyBool_FromLong(res);
Guido van Rossuma9e20242007-03-08 00:43:48 +00001104}
1105
Antoine Pitrou243757e2010-11-05 21:15:39 +00001106static PyObject *
1107fileio_getstate(fileio *self)
1108{
1109 PyErr_Format(PyExc_TypeError,
1110 "cannot serialize '%s' object", Py_TYPE(self)->tp_name);
1111 return NULL;
1112}
1113
Serhiy Storchakaf24131f2015-04-16 11:19:43 +03001114#include "clinic/fileio.c.h"
Guido van Rossuma9e20242007-03-08 00:43:48 +00001115
1116static PyMethodDef fileio_methods[] = {
Serhiy Storchakaf24131f2015-04-16 11:19:43 +03001117 _IO_FILEIO_READ_METHODDEF
1118 _IO_FILEIO_READALL_METHODDEF
1119 _IO_FILEIO_READINTO_METHODDEF
1120 _IO_FILEIO_WRITE_METHODDEF
1121 _IO_FILEIO_SEEK_METHODDEF
1122 _IO_FILEIO_TELL_METHODDEF
1123 _IO_FILEIO_TRUNCATE_METHODDEF
1124 _IO_FILEIO_CLOSE_METHODDEF
1125 _IO_FILEIO_SEEKABLE_METHODDEF
1126 _IO_FILEIO_READABLE_METHODDEF
1127 _IO_FILEIO_WRITABLE_METHODDEF
1128 _IO_FILEIO_FILENO_METHODDEF
1129 _IO_FILEIO_ISATTY_METHODDEF
Antoine Pitroue033e062010-10-29 10:38:18 +00001130 {"_dealloc_warn", (PyCFunction)fileio_dealloc_warn, METH_O, NULL},
Antoine Pitrou243757e2010-11-05 21:15:39 +00001131 {"__getstate__", (PyCFunction)fileio_getstate, METH_NOARGS, NULL},
Antoine Pitrouae4b4722010-05-05 16:31:07 +00001132 {NULL, NULL} /* sentinel */
Guido van Rossuma9e20242007-03-08 00:43:48 +00001133};
1134
Guido van Rossum53807da2007-04-10 19:01:47 +00001135/* 'closed' and 'mode' are attributes for backwards compatibility reasons. */
1136
Guido van Rossumb0428152007-04-08 17:44:42 +00001137static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +00001138get_closed(fileio *self, void *closure)
Guido van Rossumb0428152007-04-08 17:44:42 +00001139{
Antoine Pitrouae4b4722010-05-05 16:31:07 +00001140 return PyBool_FromLong((long)(self->fd < 0));
Guido van Rossum53807da2007-04-10 19:01:47 +00001141}
1142
1143static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +00001144get_closefd(fileio *self, void *closure)
Christian Heimesecc42a22008-11-05 19:30:32 +00001145{
Antoine Pitrouae4b4722010-05-05 16:31:07 +00001146 return PyBool_FromLong((long)(self->closefd));
Christian Heimesecc42a22008-11-05 19:30:32 +00001147}
1148
1149static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +00001150get_mode(fileio *self, void *closure)
Guido van Rossum53807da2007-04-10 19:01:47 +00001151{
Antoine Pitrouae4b4722010-05-05 16:31:07 +00001152 return PyUnicode_FromString(mode_string(self));
Guido van Rossumb0428152007-04-08 17:44:42 +00001153}
1154
1155static PyGetSetDef fileio_getsetlist[] = {
Antoine Pitrouae4b4722010-05-05 16:31:07 +00001156 {"closed", (getter)get_closed, NULL, "True if the file is closed"},
1157 {"closefd", (getter)get_closefd, NULL,
Serhiy Storchaka3d2279f2015-04-10 16:08:43 +03001158 "True if the file descriptor will be closed by close()."},
Antoine Pitrouae4b4722010-05-05 16:31:07 +00001159 {"mode", (getter)get_mode, NULL, "String giving the file mode"},
1160 {NULL},
Guido van Rossumb0428152007-04-08 17:44:42 +00001161};
1162
Antoine Pitrou796564c2013-07-30 19:59:21 +02001163static PyMemberDef fileio_members[] = {
Antoine Pitroude687222014-06-29 20:07:28 -04001164 {"_blksize", T_UINT, offsetof(fileio, blksize), 0},
Antoine Pitrou796564c2013-07-30 19:59:21 +02001165 {"_finalizing", T_BOOL, offsetof(fileio, finalizing), 0},
1166 {NULL}
1167};
1168
Guido van Rossuma9e20242007-03-08 00:43:48 +00001169PyTypeObject PyFileIO_Type = {
Antoine Pitrouae4b4722010-05-05 16:31:07 +00001170 PyVarObject_HEAD_INIT(NULL, 0)
1171 "_io.FileIO",
1172 sizeof(fileio),
1173 0,
1174 (destructor)fileio_dealloc, /* tp_dealloc */
1175 0, /* tp_print */
1176 0, /* tp_getattr */
1177 0, /* tp_setattr */
1178 0, /* tp_reserved */
1179 (reprfunc)fileio_repr, /* tp_repr */
1180 0, /* tp_as_number */
1181 0, /* tp_as_sequence */
1182 0, /* tp_as_mapping */
1183 0, /* tp_hash */
1184 0, /* tp_call */
1185 0, /* tp_str */
1186 PyObject_GenericGetAttr, /* tp_getattro */
1187 0, /* tp_setattro */
1188 0, /* tp_as_buffer */
1189 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE
Antoine Pitrou796564c2013-07-30 19:59:21 +02001190 | Py_TPFLAGS_HAVE_GC | Py_TPFLAGS_HAVE_FINALIZE, /* tp_flags */
Serhiy Storchakaf24131f2015-04-16 11:19:43 +03001191 _io_FileIO___init____doc__, /* tp_doc */
Antoine Pitrouae4b4722010-05-05 16:31:07 +00001192 (traverseproc)fileio_traverse, /* tp_traverse */
1193 (inquiry)fileio_clear, /* tp_clear */
1194 0, /* tp_richcompare */
1195 offsetof(fileio, weakreflist), /* tp_weaklistoffset */
1196 0, /* tp_iter */
1197 0, /* tp_iternext */
1198 fileio_methods, /* tp_methods */
Antoine Pitrou796564c2013-07-30 19:59:21 +02001199 fileio_members, /* tp_members */
Antoine Pitrouae4b4722010-05-05 16:31:07 +00001200 fileio_getsetlist, /* tp_getset */
1201 0, /* tp_base */
1202 0, /* tp_dict */
1203 0, /* tp_descr_get */
1204 0, /* tp_descr_set */
1205 offsetof(fileio, dict), /* tp_dictoffset */
Serhiy Storchakaf24131f2015-04-16 11:19:43 +03001206 _io_FileIO___init__, /* tp_init */
Antoine Pitrouae4b4722010-05-05 16:31:07 +00001207 PyType_GenericAlloc, /* tp_alloc */
1208 fileio_new, /* tp_new */
1209 PyObject_GC_Del, /* tp_free */
Antoine Pitrou796564c2013-07-30 19:59:21 +02001210 0, /* tp_is_gc */
1211 0, /* tp_bases */
1212 0, /* tp_mro */
1213 0, /* tp_cache */
1214 0, /* tp_subclasses */
1215 0, /* tp_weaklist */
1216 0, /* tp_del */
1217 0, /* tp_version_tag */
1218 0, /* tp_finalize */
Guido van Rossuma9e20242007-03-08 00:43:48 +00001219};