blob: 34a58014a608d93f7bec402d8a388cb2a299744f [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
Guido van Rossuma9e20242007-03-08 00:43:48 +000046typedef struct {
Antoine Pitrouae4b4722010-05-05 16:31:07 +000047 PyObject_HEAD
48 int fd;
Charles-François Natalidc3044c2012-01-09 22:40:02 +010049 unsigned int created : 1;
Antoine Pitrouae4b4722010-05-05 16:31:07 +000050 unsigned int readable : 1;
51 unsigned int writable : 1;
52 signed int seekable : 2; /* -1 means unknown */
53 unsigned int closefd : 1;
Antoine Pitroue033e062010-10-29 10:38:18 +000054 unsigned int deallocating: 1;
Antoine Pitrouae4b4722010-05-05 16:31:07 +000055 PyObject *weakreflist;
56 PyObject *dict;
Benjamin Peterson680bf1a2009-06-12 02:07:12 +000057} fileio;
Guido van Rossuma9e20242007-03-08 00:43:48 +000058
Collin Winteraf334382007-03-08 21:46:15 +000059PyTypeObject PyFileIO_Type;
60
Guido van Rossuma9e20242007-03-08 00:43:48 +000061#define PyFileIO_Check(op) (PyObject_TypeCheck((op), &PyFileIO_Type))
62
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +000063int
64_PyFileIO_closed(PyObject *self)
65{
Antoine Pitrouae4b4722010-05-05 16:31:07 +000066 return ((fileio *)self)->fd < 0;
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +000067}
Antoine Pitrou08838b62009-01-21 00:55:13 +000068
Antoine Pitroue033e062010-10-29 10:38:18 +000069/* Because this can call arbitrary code, it shouldn't be called when
70 the refcount is 0 (that is, not directly from tp_dealloc unless
71 the refcount has been temporarily re-incremented). */
72static PyObject *
73fileio_dealloc_warn(fileio *self, PyObject *source)
74{
75 if (self->fd >= 0 && self->closefd) {
76 PyObject *exc, *val, *tb;
77 PyErr_Fetch(&exc, &val, &tb);
78 if (PyErr_WarnFormat(PyExc_ResourceWarning, 1,
79 "unclosed file %R", source)) {
80 /* Spurious errors can appear at shutdown */
81 if (PyErr_ExceptionMatches(PyExc_Warning))
82 PyErr_WriteUnraisable((PyObject *) self);
83 }
84 PyErr_Restore(exc, val, tb);
85 }
86 Py_RETURN_NONE;
87}
88
Antoine Pitrou7fb111b2009-03-04 11:14:01 +000089static PyObject *
90portable_lseek(int fd, PyObject *posobj, int whence);
91
Antoine Pitroua28fcfd2009-03-13 23:42:55 +000092static PyObject *portable_lseek(int fd, PyObject *posobj, int whence);
93
Kristján Valur Jónsson19288c22008-12-18 17:15:54 +000094/* Returns 0 on success, -1 with exception set on failure. */
Neal Norwitz88b44da2007-08-12 17:23:54 +000095static int
Benjamin Peterson680bf1a2009-06-12 02:07:12 +000096internal_close(fileio *self)
Guido van Rossuma9e20242007-03-08 00:43:48 +000097{
Antoine Pitrouae4b4722010-05-05 16:31:07 +000098 int err = 0;
99 int save_errno = 0;
100 if (self->fd >= 0) {
101 int fd = self->fd;
102 self->fd = -1;
103 /* fd is accessible and someone else may have closed it */
104 if (_PyVerify_fd(fd)) {
105 Py_BEGIN_ALLOW_THREADS
106 err = close(fd);
107 if (err < 0)
108 save_errno = errno;
109 Py_END_ALLOW_THREADS
110 } else {
111 save_errno = errno;
112 err = -1;
113 }
114 }
115 if (err < 0) {
116 errno = save_errno;
117 PyErr_SetFromErrno(PyExc_IOError);
118 return -1;
119 }
120 return 0;
Neal Norwitz88b44da2007-08-12 17:23:54 +0000121}
122
123static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000124fileio_close(fileio *self)
Neal Norwitz88b44da2007-08-12 17:23:54 +0000125{
Martin v. Löwisbd928fe2011-10-14 10:20:37 +0200126 _Py_IDENTIFIER(close);
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000127 if (!self->closefd) {
128 self->fd = -1;
129 Py_RETURN_NONE;
130 }
Antoine Pitroue033e062010-10-29 10:38:18 +0000131 if (self->deallocating) {
132 PyObject *r = fileio_dealloc_warn(self, (PyObject *) self);
133 if (r)
134 Py_DECREF(r);
135 else
136 PyErr_Clear();
137 }
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000138 errno = internal_close(self);
139 if (errno < 0)
140 return NULL;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000141
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200142 return _PyObject_CallMethodId((PyObject*)&PyRawIOBase_Type,
143 &PyId_close, "O", self);
Guido van Rossuma9e20242007-03-08 00:43:48 +0000144}
145
146static PyObject *
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000147fileio_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
Guido van Rossuma9e20242007-03-08 00:43:48 +0000148{
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000149 fileio *self;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000150
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000151 assert(type != NULL && type->tp_alloc != NULL);
Guido van Rossuma9e20242007-03-08 00:43:48 +0000152
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000153 self = (fileio *) type->tp_alloc(type, 0);
154 if (self != NULL) {
155 self->fd = -1;
Charles-François Natalidc3044c2012-01-09 22:40:02 +0100156 self->created = 0;
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000157 self->readable = 0;
158 self->writable = 0;
159 self->seekable = -1;
160 self->closefd = 1;
161 self->weakreflist = NULL;
162 }
Guido van Rossuma9e20242007-03-08 00:43:48 +0000163
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000164 return (PyObject *) self;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000165}
166
167/* On Unix, open will succeed for directories.
168 In Python, there should be no file objects referring to
169 directories, so we need a check. */
170
171static int
Antoine Pitrou9235b252012-07-06 18:48:24 +0200172dircheck(fileio* self, PyObject *nameobj)
Guido van Rossuma9e20242007-03-08 00:43:48 +0000173{
Christian Heimes91e8b812013-06-23 23:51:44 +0200174#if defined(HAVE_FSTAT) && defined(S_ISDIR) && defined(EISDIR)
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000175 struct stat buf;
176 if (self->fd < 0)
177 return 0;
178 if (fstat(self->fd, &buf) == 0 && S_ISDIR(buf.st_mode)) {
Antoine Pitrou9235b252012-07-06 18:48:24 +0200179 errno = EISDIR;
180 PyErr_SetFromErrnoWithFilenameObject(PyExc_IOError, nameobj);
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000181 return -1;
182 }
Guido van Rossuma9e20242007-03-08 00:43:48 +0000183#endif
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000184 return 0;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000185}
186
Benjamin Peterson806d4022009-01-19 15:11:51 +0000187static int
188check_fd(int fd)
189{
190#if defined(HAVE_FSTAT)
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000191 struct stat buf;
192 if (!_PyVerify_fd(fd) || (fstat(fd, &buf) < 0 && errno == EBADF)) {
193 PyObject *exc;
194 char *msg = strerror(EBADF);
195 exc = PyObject_CallFunction(PyExc_OSError, "(is)",
196 EBADF, msg);
197 PyErr_SetObject(PyExc_OSError, exc);
198 Py_XDECREF(exc);
199 return -1;
200 }
Benjamin Peterson806d4022009-01-19 15:11:51 +0000201#endif
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000202 return 0;
Benjamin Peterson806d4022009-01-19 15:11:51 +0000203}
204
Guido van Rossuma9e20242007-03-08 00:43:48 +0000205
206static int
207fileio_init(PyObject *oself, PyObject *args, PyObject *kwds)
208{
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000209 fileio *self = (fileio *) oself;
Ross Lagerwall59142db2011-10-31 20:34:46 +0200210 static char *kwlist[] = {"file", "mode", "closefd", "opener", NULL};
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000211 const char *name = NULL;
Ross Lagerwall59142db2011-10-31 20:34:46 +0200212 PyObject *nameobj, *stringobj = NULL, *opener = Py_None;
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000213 char *mode = "r";
214 char *s;
Thomas Helleraf2be262007-07-12 11:03:13 +0000215#ifdef MS_WINDOWS
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000216 Py_UNICODE *widename = NULL;
Thomas Helleraf2be262007-07-12 11:03:13 +0000217#endif
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000218 int ret = 0;
219 int rwa = 0, plus = 0, append = 0;
220 int flags = 0;
221 int fd = -1;
222 int closefd = 1;
Hynek Schlawack9ed8b4e2012-06-21 20:20:25 +0200223 int fd_is_own = 0;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000224
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000225 assert(PyFileIO_Check(oself));
226 if (self->fd >= 0) {
Hynek Schlawack2cc71562012-05-25 10:05:53 +0200227 if (self->closefd) {
228 /* Have to close the existing file first. */
229 if (internal_close(self) < 0)
230 return -1;
231 }
232 else
233 self->fd = -1;
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000234 }
Guido van Rossuma9e20242007-03-08 00:43:48 +0000235
Ross Lagerwall59142db2011-10-31 20:34:46 +0200236 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|siO:fileio",
237 kwlist, &nameobj, &mode, &closefd,
238 &opener))
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000239 return -1;
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000240
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000241 if (PyFloat_Check(nameobj)) {
242 PyErr_SetString(PyExc_TypeError,
243 "integer argument expected, got float");
244 return -1;
245 }
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000246
Serhiy Storchaka78980432013-01-15 01:12:17 +0200247 fd = _PyLong_AsInt(nameobj);
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000248 if (fd < 0) {
249 if (!PyErr_Occurred()) {
250 PyErr_SetString(PyExc_ValueError,
251 "Negative filedescriptor");
252 return -1;
253 }
254 PyErr_Clear();
255 }
Guido van Rossumb0428152007-04-08 17:44:42 +0000256
Hirokazu Yamamoto8223c242009-05-17 04:21:53 +0000257#ifdef MS_WINDOWS
Victor Stinnerfe9a8612011-09-29 23:19:04 +0200258 if (PyUnicode_Check(nameobj)) {
Antoine Pitrou13348842012-01-29 18:36:34 +0100259 int rv = _PyUnicode_HasNULChars(nameobj);
260 if (rv) {
261 if (rv != -1)
262 PyErr_SetString(PyExc_TypeError, "embedded NUL character");
263 return -1;
264 }
Victor Stinnerfe9a8612011-09-29 23:19:04 +0200265 widename = PyUnicode_AsUnicode(nameobj);
266 if (widename == NULL)
267 return -1;
268 } else
Guido van Rossuma9e20242007-03-08 00:43:48 +0000269#endif
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000270 if (fd < 0)
271 {
Antoine Pitrou13348842012-01-29 18:36:34 +0100272 if (!PyUnicode_FSConverter(nameobj, &stringobj)) {
273 return -1;
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000274 }
Antoine Pitrou13348842012-01-29 18:36:34 +0100275 name = PyBytes_AS_STRING(stringobj);
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000276 }
Guido van Rossuma9e20242007-03-08 00:43:48 +0000277
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000278 s = mode;
279 while (*s) {
280 switch (*s++) {
Charles-François Natalidc3044c2012-01-09 22:40:02 +0100281 case 'x':
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000282 if (rwa) {
283 bad_mode:
284 PyErr_SetString(PyExc_ValueError,
Charles-François Natalidc3044c2012-01-09 22:40:02 +0100285 "Must have exactly one of create/read/write/append "
Georg Brandl28928ae2010-10-21 13:45:52 +0000286 "mode and at most one plus");
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000287 goto error;
288 }
289 rwa = 1;
Charles-François Natalidc3044c2012-01-09 22:40:02 +0100290 self->created = 1;
291 self->writable = 1;
292 flags |= O_EXCL | O_CREAT;
293 break;
294 case 'r':
295 if (rwa)
296 goto bad_mode;
297 rwa = 1;
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000298 self->readable = 1;
299 break;
300 case 'w':
301 if (rwa)
302 goto bad_mode;
303 rwa = 1;
304 self->writable = 1;
305 flags |= O_CREAT | O_TRUNC;
306 break;
307 case 'a':
308 if (rwa)
309 goto bad_mode;
310 rwa = 1;
311 self->writable = 1;
312 flags |= O_CREAT;
313 append = 1;
314 break;
315 case 'b':
316 break;
317 case '+':
318 if (plus)
319 goto bad_mode;
320 self->readable = self->writable = 1;
321 plus = 1;
322 break;
323 default:
324 PyErr_Format(PyExc_ValueError,
325 "invalid mode: %.200s", mode);
326 goto error;
327 }
328 }
Guido van Rossuma9e20242007-03-08 00:43:48 +0000329
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000330 if (!rwa)
331 goto bad_mode;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000332
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000333 if (self->readable && self->writable)
334 flags |= O_RDWR;
335 else if (self->readable)
336 flags |= O_RDONLY;
337 else
338 flags |= O_WRONLY;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000339
340#ifdef O_BINARY
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000341 flags |= O_BINARY;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000342#endif
343
Walter Dörwald0e411482007-06-06 16:55:38 +0000344#ifdef O_APPEND
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000345 if (append)
346 flags |= O_APPEND;
Walter Dörwald0e411482007-06-06 16:55:38 +0000347#endif
348
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000349 if (fd >= 0) {
350 if (check_fd(fd))
351 goto error;
352 self->fd = fd;
353 self->closefd = closefd;
354 }
355 else {
356 self->closefd = 1;
357 if (!closefd) {
358 PyErr_SetString(PyExc_ValueError,
359 "Cannot use closefd=False with file name");
360 goto error;
361 }
Guido van Rossum2dced8b2007-10-30 17:27:30 +0000362
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000363 errno = 0;
Ross Lagerwall59142db2011-10-31 20:34:46 +0200364 if (opener == Py_None) {
365 Py_BEGIN_ALLOW_THREADS
Thomas Helleraf2be262007-07-12 11:03:13 +0000366#ifdef MS_WINDOWS
Ross Lagerwall59142db2011-10-31 20:34:46 +0200367 if (widename != NULL)
368 self->fd = _wopen(widename, flags, 0666);
369 else
Thomas Helleraf2be262007-07-12 11:03:13 +0000370#endif
Ross Lagerwall59142db2011-10-31 20:34:46 +0200371 self->fd = open(name, flags, 0666);
372 Py_END_ALLOW_THREADS
373 } else {
374 PyObject *fdobj = PyObject_CallFunction(
375 opener, "Oi", nameobj, flags);
376 if (fdobj == NULL)
377 goto error;
378 if (!PyLong_Check(fdobj)) {
379 Py_DECREF(fdobj);
380 PyErr_SetString(PyExc_TypeError,
381 "expected integer from opener");
382 goto error;
383 }
384
Serhiy Storchaka78980432013-01-15 01:12:17 +0200385 self->fd = _PyLong_AsInt(fdobj);
Ross Lagerwall59142db2011-10-31 20:34:46 +0200386 Py_DECREF(fdobj);
387 if (self->fd == -1) {
388 goto error;
389 }
390 }
391
Hynek Schlawack7f59fd72012-06-22 09:32:22 +0200392 fd_is_own = 1;
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000393 if (self->fd < 0) {
Victor Stinner292c8352012-10-30 02:17:38 +0100394 PyErr_SetFromErrnoWithFilenameObject(PyExc_OSError, nameobj);
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000395 goto error;
396 }
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000397 }
Antoine Pitrou9235b252012-07-06 18:48:24 +0200398 if (dircheck(self, nameobj) < 0)
399 goto error;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000400
Victor Stinner89e34362011-01-07 18:47:22 +0000401#if defined(MS_WINDOWS) || defined(__CYGWIN__)
402 /* don't translate newlines (\r\n <=> \n) */
403 _setmode(self->fd, O_BINARY);
404#endif
405
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000406 if (PyObject_SetAttrString((PyObject *)self, "name", nameobj) < 0)
407 goto error;
Antoine Pitrou08838b62009-01-21 00:55:13 +0000408
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000409 if (append) {
410 /* For consistent behaviour, we explicitly seek to the
411 end of file (otherwise, it might be done only on the
412 first write()). */
413 PyObject *pos = portable_lseek(self->fd, NULL, 2);
Hynek Schlawack9ed8b4e2012-06-21 20:20:25 +0200414 if (pos == NULL)
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000415 goto error;
416 Py_DECREF(pos);
417 }
Antoine Pitrou7fb111b2009-03-04 11:14:01 +0000418
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000419 goto done;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000420
421 error:
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000422 ret = -1;
Hynek Schlawack9ed8b4e2012-06-21 20:20:25 +0200423 if (!fd_is_own)
424 self->fd = -1;
Benjamin Petersonbbb04122010-10-30 23:16:28 +0000425 if (self->fd >= 0)
426 internal_close(self);
Guido van Rossum53807da2007-04-10 19:01:47 +0000427
Guido van Rossuma9e20242007-03-08 00:43:48 +0000428 done:
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000429 Py_CLEAR(stringobj);
430 return ret;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000431}
432
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000433static int
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000434fileio_traverse(fileio *self, visitproc visit, void *arg)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000435{
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000436 Py_VISIT(self->dict);
437 return 0;
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000438}
439
440static int
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000441fileio_clear(fileio *self)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000442{
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000443 Py_CLEAR(self->dict);
444 return 0;
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000445}
446
Guido van Rossuma9e20242007-03-08 00:43:48 +0000447static void
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000448fileio_dealloc(fileio *self)
Guido van Rossuma9e20242007-03-08 00:43:48 +0000449{
Antoine Pitroue033e062010-10-29 10:38:18 +0000450 self->deallocating = 1;
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000451 if (_PyIOBase_finalize((PyObject *) self) < 0)
452 return;
453 _PyObject_GC_UNTRACK(self);
454 if (self->weakreflist != NULL)
455 PyObject_ClearWeakRefs((PyObject *) self);
456 Py_CLEAR(self->dict);
457 Py_TYPE(self)->tp_free((PyObject *)self);
Guido van Rossuma9e20242007-03-08 00:43:48 +0000458}
459
460static PyObject *
461err_closed(void)
462{
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000463 PyErr_SetString(PyExc_ValueError, "I/O operation on closed file");
464 return NULL;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000465}
466
467static PyObject *
Guido van Rossum53807da2007-04-10 19:01:47 +0000468err_mode(char *action)
469{
Antoine Pitrou0d739d72010-09-05 23:01:12 +0000470 PyErr_Format(IO_STATE->unsupported_operation,
471 "File not open for %s", action);
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000472 return NULL;
Guido van Rossum53807da2007-04-10 19:01:47 +0000473}
474
475static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000476fileio_fileno(fileio *self)
Guido van Rossuma9e20242007-03-08 00:43:48 +0000477{
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000478 if (self->fd < 0)
479 return err_closed();
480 return PyLong_FromLong((long) self->fd);
Guido van Rossuma9e20242007-03-08 00:43:48 +0000481}
482
483static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000484fileio_readable(fileio *self)
Guido van Rossuma9e20242007-03-08 00:43:48 +0000485{
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000486 if (self->fd < 0)
487 return err_closed();
488 return PyBool_FromLong((long) self->readable);
Guido van Rossuma9e20242007-03-08 00:43:48 +0000489}
490
491static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000492fileio_writable(fileio *self)
Guido van Rossuma9e20242007-03-08 00:43:48 +0000493{
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000494 if (self->fd < 0)
495 return err_closed();
496 return PyBool_FromLong((long) self->writable);
Guido van Rossuma9e20242007-03-08 00:43:48 +0000497}
498
499static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000500fileio_seekable(fileio *self)
Guido van Rossuma9e20242007-03-08 00:43:48 +0000501{
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000502 if (self->fd < 0)
503 return err_closed();
504 if (self->seekable < 0) {
505 PyObject *pos = portable_lseek(self->fd, NULL, SEEK_CUR);
506 if (pos == NULL) {
507 PyErr_Clear();
508 self->seekable = 0;
509 } else {
510 Py_DECREF(pos);
511 self->seekable = 1;
512 }
513 }
514 return PyBool_FromLong((long) self->seekable);
Guido van Rossuma9e20242007-03-08 00:43:48 +0000515}
516
517static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000518fileio_readinto(fileio *self, PyObject *args)
Guido van Rossuma9e20242007-03-08 00:43:48 +0000519{
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000520 Py_buffer pbuf;
Victor Stinnere6edec22011-01-04 00:29:35 +0000521 Py_ssize_t n, len;
Antoine Pitrouc345ce12011-12-16 12:28:32 +0100522 int err;
Guido van Rossum53807da2007-04-10 19:01:47 +0000523
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000524 if (self->fd < 0)
525 return err_closed();
526 if (!self->readable)
527 return err_mode("reading");
Guido van Rossum53807da2007-04-10 19:01:47 +0000528
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000529 if (!PyArg_ParseTuple(args, "w*", &pbuf))
530 return NULL;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000531
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000532 if (_PyVerify_fd(self->fd)) {
Victor Stinnere6edec22011-01-04 00:29:35 +0000533 len = pbuf.len;
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000534 Py_BEGIN_ALLOW_THREADS
535 errno = 0;
Victor Stinnere6edec22011-01-04 00:29:35 +0000536#if defined(MS_WIN64) || defined(MS_WINDOWS)
537 if (len > INT_MAX)
538 len = INT_MAX;
539 n = read(self->fd, pbuf.buf, (int)len);
540#else
Victor Stinner72344792011-01-11 00:04:12 +0000541 n = read(self->fd, pbuf.buf, len);
Victor Stinnere6edec22011-01-04 00:29:35 +0000542#endif
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000543 Py_END_ALLOW_THREADS
544 } else
545 n = -1;
Antoine Pitrouc345ce12011-12-16 12:28:32 +0100546 err = errno;
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000547 PyBuffer_Release(&pbuf);
548 if (n < 0) {
Antoine Pitrouc345ce12011-12-16 12:28:32 +0100549 if (err == EAGAIN)
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000550 Py_RETURN_NONE;
Antoine Pitrouc345ce12011-12-16 12:28:32 +0100551 errno = err;
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000552 PyErr_SetFromErrno(PyExc_IOError);
553 return NULL;
554 }
Guido van Rossuma9e20242007-03-08 00:43:48 +0000555
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000556 return PyLong_FromSsize_t(n);
Guido van Rossuma9e20242007-03-08 00:43:48 +0000557}
558
Richard Oudkerkaf7260e2013-05-17 23:34:42 +0100559#ifndef HAVE_FSTAT
560
561static PyObject *
562fileio_readall(fileio *self)
563{
564 _Py_IDENTIFIER(readall);
565 return _PyObject_CallMethodId((PyObject*)&PyRawIOBase_Type,
566 &PyId_readall, "O", self);
567}
568
569#else
570
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000571static size_t
Richard Oudkerkaf7260e2013-05-17 23:34:42 +0100572new_buffersize(fileio *self, size_t currentsize)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000573{
Antoine Pitroua3f44572012-04-17 13:50:58 +0200574 size_t addend;
Richard Oudkerkaf7260e2013-05-17 23:34:42 +0100575
Nadeem Vawdad41a98b2011-10-13 13:34:16 +0200576 /* Expand the buffer by an amount proportional to the current size,
Antoine Pitroua3f44572012-04-17 13:50:58 +0200577 giving us amortized linear-time behavior. For bigger sizes, use a
578 less-than-double growth factor to avoid excessive allocation. */
Richard Oudkerkaf7260e2013-05-17 23:34:42 +0100579 assert(currentsize <= PY_SSIZE_T_MAX);
Antoine Pitroua3f44572012-04-17 13:50:58 +0200580 if (currentsize > 65536)
581 addend = currentsize >> 3;
582 else
583 addend = 256 + currentsize;
584 if (addend < SMALLCHUNK)
585 /* Avoid tiny read() calls. */
586 addend = SMALLCHUNK;
587 return addend + currentsize;
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000588}
589
Guido van Rossum7165cb12007-07-10 06:54:34 +0000590static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000591fileio_readall(fileio *self)
Guido van Rossum7165cb12007-07-10 06:54:34 +0000592{
Victor Stinnere9d44ccb2011-05-26 00:16:44 +0200593 struct stat st;
Victor Stinnera2a64772011-10-11 22:45:02 +0200594 Py_off_t pos, end;
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000595 PyObject *result;
Richard Oudkerkaf7260e2013-05-17 23:34:42 +0100596 Py_ssize_t bytes_read = 0;
Victor Stinnerc44057d2013-01-03 03:33:21 +0100597 Py_ssize_t n;
Richard Oudkerkaf7260e2013-05-17 23:34:42 +0100598 size_t bufsize;
Guido van Rossum7165cb12007-07-10 06:54:34 +0000599
Victor Stinnerb79f28c2011-05-25 22:09:03 +0200600 if (self->fd < 0)
601 return err_closed();
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000602 if (!_PyVerify_fd(self->fd))
603 return PyErr_SetFromErrno(PyExc_IOError);
Kristján Valur Jónssona8abe862009-03-24 15:27:42 +0000604
Victor Stinnere9d44ccb2011-05-26 00:16:44 +0200605#if defined(MS_WIN64) || defined(MS_WINDOWS)
606 pos = _lseeki64(self->fd, 0L, SEEK_CUR);
607#else
608 pos = lseek(self->fd, 0L, SEEK_CUR);
609#endif
610 if (fstat(self->fd, &st) == 0)
611 end = st.st_size;
612 else
Victor Stinnera2a64772011-10-11 22:45:02 +0200613 end = (Py_off_t)-1;
Christian Heimesa872de52008-12-05 08:26:55 +0000614
Richard Oudkerkaf7260e2013-05-17 23:34:42 +0100615 if (end > 0 && end >= pos && pos >= 0 && end - pos < PY_SSIZE_T_MAX) {
616 /* This is probably a real file, so we try to allocate a
617 buffer one byte larger than the rest of the file. If the
618 calculation is right then we should get EOF without having
619 to enlarge the buffer. */
620 bufsize = (size_t)(end - pos + 1);
621 } else {
622 bufsize = SMALLCHUNK;
623 }
624
625 result = PyBytes_FromStringAndSize(NULL, bufsize);
626 if (result == NULL)
627 return NULL;
628
629 while (1) {
630 if (bytes_read >= (Py_ssize_t)bufsize) {
631 bufsize = new_buffersize(self, bytes_read);
632 if (bufsize > PY_SSIZE_T_MAX || bufsize <= 0) {
633 PyErr_SetString(PyExc_OverflowError,
634 "unbounded read returned more bytes "
Victor Stinner3e269392013-05-18 00:38:43 +0200635 "than a Python string can hold");
Richard Oudkerkaf7260e2013-05-17 23:34:42 +0100636 Py_DECREF(result);
637 return NULL;
638 }
639
640 if (PyBytes_GET_SIZE(result) < (Py_ssize_t)bufsize) {
641 if (_PyBytes_Resize(&result, bufsize) < 0)
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000642 return NULL;
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000643 }
644 }
645 Py_BEGIN_ALLOW_THREADS
646 errno = 0;
Richard Oudkerkaf7260e2013-05-17 23:34:42 +0100647 n = bufsize - bytes_read;
Victor Stinnerc44057d2013-01-03 03:33:21 +0100648#if defined(MS_WIN64) || defined(MS_WINDOWS)
649 if (n > INT_MAX)
650 n = INT_MAX;
Richard Oudkerkaf7260e2013-05-17 23:34:42 +0100651 n = read(self->fd, PyBytes_AS_STRING(result) + bytes_read, (int)n);
Victor Stinnerc44057d2013-01-03 03:33:21 +0100652#else
Richard Oudkerkaf7260e2013-05-17 23:34:42 +0100653 n = read(self->fd, PyBytes_AS_STRING(result) + bytes_read, n);
Victor Stinnerc44057d2013-01-03 03:33:21 +0100654#endif
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000655 Py_END_ALLOW_THREADS
656 if (n == 0)
657 break;
658 if (n < 0) {
Gregory P. Smith51359922012-06-23 23:55:39 -0700659 if (errno == EINTR) {
660 if (PyErr_CheckSignals()) {
661 Py_DECREF(result);
662 return NULL;
663 }
664 continue;
665 }
Richard Oudkerkaf7260e2013-05-17 23:34:42 +0100666 if (bytes_read > 0)
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000667 break;
668 if (errno == EAGAIN) {
669 Py_DECREF(result);
670 Py_RETURN_NONE;
671 }
672 Py_DECREF(result);
673 PyErr_SetFromErrno(PyExc_IOError);
674 return NULL;
675 }
Richard Oudkerkaf7260e2013-05-17 23:34:42 +0100676 bytes_read += n;
Victor Stinnere9d44ccb2011-05-26 00:16:44 +0200677 pos += n;
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000678 }
Guido van Rossum7165cb12007-07-10 06:54:34 +0000679
Richard Oudkerkaf7260e2013-05-17 23:34:42 +0100680 if (PyBytes_GET_SIZE(result) > bytes_read) {
681 if (_PyBytes_Resize(&result, bytes_read) < 0)
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000682 return NULL;
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000683 }
684 return result;
Guido van Rossum7165cb12007-07-10 06:54:34 +0000685}
686
Richard Oudkerkaf7260e2013-05-17 23:34:42 +0100687#endif /* HAVE_FSTAT */
688
Guido van Rossuma9e20242007-03-08 00:43:48 +0000689static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000690fileio_read(fileio *self, PyObject *args)
Guido van Rossuma9e20242007-03-08 00:43:48 +0000691{
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000692 char *ptr;
693 Py_ssize_t n;
694 Py_ssize_t size = -1;
695 PyObject *bytes;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000696
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000697 if (self->fd < 0)
698 return err_closed();
699 if (!self->readable)
700 return err_mode("reading");
Guido van Rossuma9e20242007-03-08 00:43:48 +0000701
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000702 if (!PyArg_ParseTuple(args, "|O&", &_PyIO_ConvertSsize_t, &size))
703 return NULL;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000704
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000705 if (size < 0) {
706 return fileio_readall(self);
707 }
Guido van Rossumc2f93dc2007-05-24 00:50:02 +0000708
Victor Stinnerc655a722011-07-05 11:31:49 +0200709#if defined(MS_WIN64) || defined(MS_WINDOWS)
710 if (size > INT_MAX)
711 size = INT_MAX;
712#endif
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000713 bytes = PyBytes_FromStringAndSize(NULL, size);
714 if (bytes == NULL)
715 return NULL;
716 ptr = PyBytes_AS_STRING(bytes);
Guido van Rossuma9e20242007-03-08 00:43:48 +0000717
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000718 if (_PyVerify_fd(self->fd)) {
719 Py_BEGIN_ALLOW_THREADS
720 errno = 0;
Victor Stinnerc655a722011-07-05 11:31:49 +0200721#if defined(MS_WIN64) || defined(MS_WINDOWS)
722 n = read(self->fd, ptr, (int)size);
723#else
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000724 n = read(self->fd, ptr, size);
Victor Stinnerc655a722011-07-05 11:31:49 +0200725#endif
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000726 Py_END_ALLOW_THREADS
727 } else
728 n = -1;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000729
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000730 if (n < 0) {
Antoine Pitrouc345ce12011-12-16 12:28:32 +0100731 int err = errno;
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000732 Py_DECREF(bytes);
Antoine Pitrouc345ce12011-12-16 12:28:32 +0100733 if (err == EAGAIN)
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000734 Py_RETURN_NONE;
Antoine Pitrouc345ce12011-12-16 12:28:32 +0100735 errno = err;
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000736 PyErr_SetFromErrno(PyExc_IOError);
737 return NULL;
738 }
Guido van Rossuma9e20242007-03-08 00:43:48 +0000739
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000740 if (n != size) {
741 if (_PyBytes_Resize(&bytes, n) < 0) {
742 Py_DECREF(bytes);
743 return NULL;
744 }
745 }
Guido van Rossuma9e20242007-03-08 00:43:48 +0000746
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000747 return (PyObject *) bytes;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000748}
749
750static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000751fileio_write(fileio *self, PyObject *args)
Guido van Rossuma9e20242007-03-08 00:43:48 +0000752{
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000753 Py_buffer pbuf;
Victor Stinnere6edec22011-01-04 00:29:35 +0000754 Py_ssize_t n, len;
Antoine Pitrouc345ce12011-12-16 12:28:32 +0100755 int err;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000756
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000757 if (self->fd < 0)
758 return err_closed();
759 if (!self->writable)
760 return err_mode("writing");
Guido van Rossum53807da2007-04-10 19:01:47 +0000761
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000762 if (!PyArg_ParseTuple(args, "y*", &pbuf))
763 return NULL;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000764
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000765 if (_PyVerify_fd(self->fd)) {
766 Py_BEGIN_ALLOW_THREADS
767 errno = 0;
Victor Stinnere6edec22011-01-04 00:29:35 +0000768 len = pbuf.len;
769#if defined(MS_WIN64) || defined(MS_WINDOWS)
Victor Stinnere0daff12011-03-20 23:36:35 +0100770 if (len > 32767 && isatty(self->fd)) {
771 /* Issue #11395: the Windows console returns an error (12: not
772 enough space error) on writing into stdout if stdout mode is
773 binary and the length is greater than 66,000 bytes (or less,
774 depending on heap usage). */
775 len = 32767;
776 }
777 else if (len > INT_MAX)
Victor Stinnere6edec22011-01-04 00:29:35 +0000778 len = INT_MAX;
779 n = write(self->fd, pbuf.buf, (int)len);
780#else
Victor Stinner72344792011-01-11 00:04:12 +0000781 n = write(self->fd, pbuf.buf, len);
Victor Stinnere6edec22011-01-04 00:29:35 +0000782#endif
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000783 Py_END_ALLOW_THREADS
784 } else
785 n = -1;
Antoine Pitrouc345ce12011-12-16 12:28:32 +0100786 err = errno;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000787
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000788 PyBuffer_Release(&pbuf);
Martin v. Löwis423be952008-08-13 15:53:07 +0000789
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000790 if (n < 0) {
Antoine Pitrouc345ce12011-12-16 12:28:32 +0100791 if (err == EAGAIN)
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000792 Py_RETURN_NONE;
Antoine Pitrouc345ce12011-12-16 12:28:32 +0100793 errno = err;
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000794 PyErr_SetFromErrno(PyExc_IOError);
795 return NULL;
796 }
Guido van Rossuma9e20242007-03-08 00:43:48 +0000797
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000798 return PyLong_FromSsize_t(n);
Guido van Rossuma9e20242007-03-08 00:43:48 +0000799}
800
Guido van Rossum53807da2007-04-10 19:01:47 +0000801/* XXX Windows support below is likely incomplete */
802
Guido van Rossum53807da2007-04-10 19:01:47 +0000803/* Cribbed from posix_lseek() */
804static PyObject *
805portable_lseek(int fd, PyObject *posobj, int whence)
806{
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000807 Py_off_t pos, res;
Guido van Rossum53807da2007-04-10 19:01:47 +0000808
809#ifdef SEEK_SET
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000810 /* Turn 0, 1, 2 into SEEK_{SET,CUR,END} */
811 switch (whence) {
Guido van Rossum53807da2007-04-10 19:01:47 +0000812#if SEEK_SET != 0
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000813 case 0: whence = SEEK_SET; break;
Guido van Rossum53807da2007-04-10 19:01:47 +0000814#endif
815#if SEEK_CUR != 1
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000816 case 1: whence = SEEK_CUR; break;
Guido van Rossum53807da2007-04-10 19:01:47 +0000817#endif
Antoine Pitrou4f7945f2009-01-20 11:42:11 +0000818#if SEEK_END != 2
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000819 case 2: whence = SEEK_END; break;
Guido van Rossum53807da2007-04-10 19:01:47 +0000820#endif
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000821 }
Guido van Rossum53807da2007-04-10 19:01:47 +0000822#endif /* SEEK_SET */
823
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000824 if (posobj == NULL)
825 pos = 0;
826 else {
827 if(PyFloat_Check(posobj)) {
828 PyErr_SetString(PyExc_TypeError, "an integer is required");
829 return NULL;
830 }
Alexandre Vassalotti77250f42008-05-06 19:48:38 +0000831#if defined(HAVE_LARGEFILE_SUPPORT)
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000832 pos = PyLong_AsLongLong(posobj);
Guido van Rossum53807da2007-04-10 19:01:47 +0000833#else
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000834 pos = PyLong_AsLong(posobj);
Guido van Rossum53807da2007-04-10 19:01:47 +0000835#endif
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000836 if (PyErr_Occurred())
837 return NULL;
838 }
Guido van Rossum53807da2007-04-10 19:01:47 +0000839
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000840 if (_PyVerify_fd(fd)) {
841 Py_BEGIN_ALLOW_THREADS
Guido van Rossum53807da2007-04-10 19:01:47 +0000842#if defined(MS_WIN64) || defined(MS_WINDOWS)
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000843 res = _lseeki64(fd, pos, whence);
Guido van Rossum53807da2007-04-10 19:01:47 +0000844#else
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000845 res = lseek(fd, pos, whence);
Guido van Rossum53807da2007-04-10 19:01:47 +0000846#endif
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000847 Py_END_ALLOW_THREADS
848 } else
849 res = -1;
850 if (res < 0)
851 return PyErr_SetFromErrno(PyExc_IOError);
Guido van Rossum53807da2007-04-10 19:01:47 +0000852
Alexandre Vassalotti77250f42008-05-06 19:48:38 +0000853#if defined(HAVE_LARGEFILE_SUPPORT)
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000854 return PyLong_FromLongLong(res);
Alexandre Vassalotti77250f42008-05-06 19:48:38 +0000855#else
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000856 return PyLong_FromLong(res);
Guido van Rossum53807da2007-04-10 19:01:47 +0000857#endif
858}
859
Guido van Rossuma9e20242007-03-08 00:43:48 +0000860static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000861fileio_seek(fileio *self, PyObject *args)
Guido van Rossuma9e20242007-03-08 00:43:48 +0000862{
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000863 PyObject *posobj;
864 int whence = 0;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000865
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000866 if (self->fd < 0)
867 return err_closed();
Guido van Rossuma9e20242007-03-08 00:43:48 +0000868
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000869 if (!PyArg_ParseTuple(args, "O|i", &posobj, &whence))
870 return NULL;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000871
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000872 return portable_lseek(self->fd, posobj, whence);
Guido van Rossuma9e20242007-03-08 00:43:48 +0000873}
874
875static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000876fileio_tell(fileio *self, PyObject *args)
Guido van Rossuma9e20242007-03-08 00:43:48 +0000877{
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000878 if (self->fd < 0)
879 return err_closed();
Guido van Rossuma9e20242007-03-08 00:43:48 +0000880
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000881 return portable_lseek(self->fd, NULL, 1);
Guido van Rossuma9e20242007-03-08 00:43:48 +0000882}
883
Thomas Hellerc6a55ee2007-07-11 12:45:46 +0000884#ifdef HAVE_FTRUNCATE
Guido van Rossuma9e20242007-03-08 00:43:48 +0000885static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000886fileio_truncate(fileio *self, PyObject *args)
Guido van Rossuma9e20242007-03-08 00:43:48 +0000887{
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000888 PyObject *posobj = NULL; /* the new size wanted by the user */
Antoine Pitrou905a2ff2010-01-31 22:47:27 +0000889#ifndef MS_WINDOWS
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000890 Py_off_t pos;
Antoine Pitrou905a2ff2010-01-31 22:47:27 +0000891#endif
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000892 int ret;
893 int fd;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000894
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000895 fd = self->fd;
896 if (fd < 0)
897 return err_closed();
898 if (!self->writable)
899 return err_mode("writing");
Guido van Rossuma9e20242007-03-08 00:43:48 +0000900
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000901 if (!PyArg_ParseTuple(args, "|O", &posobj))
902 return NULL;
Guido van Rossum53807da2007-04-10 19:01:47 +0000903
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000904 if (posobj == Py_None || posobj == NULL) {
905 /* Get the current position. */
906 posobj = portable_lseek(fd, NULL, 1);
907 if (posobj == NULL)
908 return NULL;
909 }
910 else {
911 Py_INCREF(posobj);
912 }
Guido van Rossum53807da2007-04-10 19:01:47 +0000913
Thomas Hellerfdeee3a2007-07-12 11:21:36 +0000914#ifdef MS_WINDOWS
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000915 /* MS _chsize doesn't work if newsize doesn't fit in 32 bits,
916 so don't even try using it. */
917 {
918 PyObject *oldposobj, *tempposobj;
919 HANDLE hFile;
Antoine Pitrou905a2ff2010-01-31 22:47:27 +0000920
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000921 /* we save the file pointer position */
922 oldposobj = portable_lseek(fd, NULL, 1);
923 if (oldposobj == NULL) {
924 Py_DECREF(posobj);
925 return NULL;
926 }
Thomas Hellerfdeee3a2007-07-12 11:21:36 +0000927
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000928 /* we then move to the truncation position */
929 tempposobj = portable_lseek(fd, posobj, 0);
930 if (tempposobj == NULL) {
931 Py_DECREF(oldposobj);
932 Py_DECREF(posobj);
933 return NULL;
934 }
935 Py_DECREF(tempposobj);
Antoine Pitrou905a2ff2010-01-31 22:47:27 +0000936
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000937 /* Truncate. Note that this may grow the file! */
938 Py_BEGIN_ALLOW_THREADS
939 errno = 0;
940 hFile = (HANDLE)_get_osfhandle(fd);
941 ret = hFile == (HANDLE)-1; /* testing for INVALID_HANDLE value */
942 if (ret == 0) {
943 ret = SetEndOfFile(hFile) == 0;
944 if (ret)
945 errno = EACCES;
946 }
947 Py_END_ALLOW_THREADS
948
949 /* we restore the file pointer position in any case */
950 tempposobj = portable_lseek(fd, oldposobj, 0);
951 Py_DECREF(oldposobj);
952 if (tempposobj == NULL) {
953 Py_DECREF(posobj);
954 return NULL;
955 }
956 Py_DECREF(tempposobj);
957 }
Thomas Hellerfdeee3a2007-07-12 11:21:36 +0000958#else
Antoine Pitrou905a2ff2010-01-31 22:47:27 +0000959
960#if defined(HAVE_LARGEFILE_SUPPORT)
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000961 pos = PyLong_AsLongLong(posobj);
Antoine Pitrou905a2ff2010-01-31 22:47:27 +0000962#else
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000963 pos = PyLong_AsLong(posobj);
Antoine Pitrou905a2ff2010-01-31 22:47:27 +0000964#endif
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000965 if (PyErr_Occurred()){
966 Py_DECREF(posobj);
967 return NULL;
968 }
Antoine Pitrou905a2ff2010-01-31 22:47:27 +0000969
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000970 Py_BEGIN_ALLOW_THREADS
971 errno = 0;
972 ret = ftruncate(fd, pos);
973 Py_END_ALLOW_THREADS
Antoine Pitrou905a2ff2010-01-31 22:47:27 +0000974
Thomas Hellerfdeee3a2007-07-12 11:21:36 +0000975#endif /* !MS_WINDOWS */
Guido van Rossuma9e20242007-03-08 00:43:48 +0000976
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000977 if (ret != 0) {
978 Py_DECREF(posobj);
979 PyErr_SetFromErrno(PyExc_IOError);
980 return NULL;
981 }
Guido van Rossuma9e20242007-03-08 00:43:48 +0000982
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000983 return posobj;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000984}
Antoine Pitrou905a2ff2010-01-31 22:47:27 +0000985#endif /* HAVE_FTRUNCATE */
Guido van Rossum53807da2007-04-10 19:01:47 +0000986
987static char *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000988mode_string(fileio *self)
Guido van Rossum53807da2007-04-10 19:01:47 +0000989{
Charles-François Natalidc3044c2012-01-09 22:40:02 +0100990 if (self->created) {
991 if (self->readable)
992 return "xb+";
993 else
994 return "xb";
995 }
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000996 if (self->readable) {
997 if (self->writable)
998 return "rb+";
999 else
1000 return "rb";
1001 }
1002 else
1003 return "wb";
Guido van Rossum53807da2007-04-10 19:01:47 +00001004}
Guido van Rossuma9e20242007-03-08 00:43:48 +00001005
1006static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +00001007fileio_repr(fileio *self)
Guido van Rossuma9e20242007-03-08 00:43:48 +00001008{
Martin v. Löwis767046a2011-10-14 15:35:36 +02001009 _Py_IDENTIFIER(name);
Antoine Pitrouae4b4722010-05-05 16:31:07 +00001010 PyObject *nameobj, *res;
Guido van Rossuma9e20242007-03-08 00:43:48 +00001011
Antoine Pitrouae4b4722010-05-05 16:31:07 +00001012 if (self->fd < 0)
1013 return PyUnicode_FromFormat("<_io.FileIO [closed]>");
Antoine Pitrou716c4442009-05-23 19:04:03 +00001014
Martin v. Löwis767046a2011-10-14 15:35:36 +02001015 nameobj = _PyObject_GetAttrId((PyObject *) self, &PyId_name);
Antoine Pitrouae4b4722010-05-05 16:31:07 +00001016 if (nameobj == NULL) {
1017 if (PyErr_ExceptionMatches(PyExc_AttributeError))
1018 PyErr_Clear();
1019 else
1020 return NULL;
1021 res = PyUnicode_FromFormat("<_io.FileIO fd=%d mode='%s'>",
1022 self->fd, mode_string(self));
1023 }
1024 else {
1025 res = PyUnicode_FromFormat("<_io.FileIO name=%R mode='%s'>",
1026 nameobj, mode_string(self));
1027 Py_DECREF(nameobj);
1028 }
1029 return res;
Guido van Rossuma9e20242007-03-08 00:43:48 +00001030}
1031
1032static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +00001033fileio_isatty(fileio *self)
Guido van Rossuma9e20242007-03-08 00:43:48 +00001034{
Antoine Pitrouae4b4722010-05-05 16:31:07 +00001035 long res;
Guido van Rossum53807da2007-04-10 19:01:47 +00001036
Antoine Pitrouae4b4722010-05-05 16:31:07 +00001037 if (self->fd < 0)
1038 return err_closed();
1039 Py_BEGIN_ALLOW_THREADS
1040 res = isatty(self->fd);
1041 Py_END_ALLOW_THREADS
1042 return PyBool_FromLong(res);
Guido van Rossuma9e20242007-03-08 00:43:48 +00001043}
1044
Antoine Pitrou243757e2010-11-05 21:15:39 +00001045static PyObject *
1046fileio_getstate(fileio *self)
1047{
1048 PyErr_Format(PyExc_TypeError,
1049 "cannot serialize '%s' object", Py_TYPE(self)->tp_name);
1050 return NULL;
1051}
1052
Guido van Rossuma9e20242007-03-08 00:43:48 +00001053
1054PyDoc_STRVAR(fileio_doc,
Ross Lagerwall59142db2011-10-31 20:34:46 +02001055"file(name: str[, mode: str][, opener: None]) -> file IO object\n"
Guido van Rossuma9e20242007-03-08 00:43:48 +00001056"\n"
Charles-François Natalidc3044c2012-01-09 22:40:02 +01001057"Open a file. The mode can be 'r', 'w', 'x' or 'a' for reading (default),\n"
Charles-François Natalid612de12012-01-14 11:51:00 +01001058"writing, exclusive creation or appending. The file will be created if it\n"
1059"doesn't exist when opened for writing or appending; it will be truncated\n"
1060"when opened for writing. A `FileExistsError` will be raised if it already\n"
Charles-François Natalidc3044c2012-01-09 22:40:02 +01001061"exists when opened for creating. Opening a file for creating implies\n"
1062"writing so this mode behaves in a similar way to 'w'.Add a '+' to the mode\n"
1063"to allow simultaneous reading and writing. A custom opener can be used by\n"
1064"passing a callable as *opener*. The underlying file descriptor for the file\n"
Ross Lagerwall59142db2011-10-31 20:34:46 +02001065"object is then obtained by calling opener with (*name*, *flags*).\n"
Charles-François Natalidc3044c2012-01-09 22:40:02 +01001066"*opener* must return an open file descriptor (passing os.open as *opener*\n"
1067"results in functionality similar to passing None).");
Guido van Rossuma9e20242007-03-08 00:43:48 +00001068
1069PyDoc_STRVAR(read_doc,
1070"read(size: int) -> bytes. read at most size bytes, returned as bytes.\n"
1071"\n"
1072"Only makes one system call, so less data may be returned than requested\n"
Guido van Rossum7165cb12007-07-10 06:54:34 +00001073"In non-blocking mode, returns None if no data is available.\n"
1074"On end-of-file, returns ''.");
1075
1076PyDoc_STRVAR(readall_doc,
1077"readall() -> bytes. read all data from the file, returned as bytes.\n"
1078"\n"
1079"In non-blocking mode, returns as much as is immediately available,\n"
1080"or None if no data is available. On end-of-file, returns ''.");
Guido van Rossuma9e20242007-03-08 00:43:48 +00001081
1082PyDoc_STRVAR(write_doc,
1083"write(b: bytes) -> int. Write bytes b to file, return number written.\n"
1084"\n"
1085"Only makes one system call, so not all of the data may be written.\n"
1086"The number of bytes actually written is returned.");
1087
1088PyDoc_STRVAR(fileno_doc,
1089"fileno() -> int. \"file descriptor\".\n"
1090"\n"
1091"This is needed for lower-level file interfaces, such the fcntl module.");
1092
1093PyDoc_STRVAR(seek_doc,
1094"seek(offset: int[, whence: int]) -> None. Move to new file position.\n"
1095"\n"
1096"Argument offset is a byte count. Optional argument whence defaults to\n"
1097"0 (offset from start of file, offset should be >= 0); other values are 1\n"
1098"(move relative to current position, positive or negative), and 2 (move\n"
1099"relative to end of file, usually negative, although many platforms allow\n"
1100"seeking beyond the end of a file)."
1101"\n"
1102"Note that not all file objects are seekable.");
1103
Thomas Hellerc6a55ee2007-07-11 12:45:46 +00001104#ifdef HAVE_FTRUNCATE
Guido van Rossuma9e20242007-03-08 00:43:48 +00001105PyDoc_STRVAR(truncate_doc,
Antoine Pitrouae4b4722010-05-05 16:31:07 +00001106"truncate([size: int]) -> None. Truncate the file to at most size bytes.\n"
Guido van Rossuma9e20242007-03-08 00:43:48 +00001107"\n"
Alexandre Vassalotti77250f42008-05-06 19:48:38 +00001108"Size defaults to the current file position, as returned by tell()."
1109"The current file position is changed to the value of size.");
Thomas Hellerc6a55ee2007-07-11 12:45:46 +00001110#endif
Guido van Rossuma9e20242007-03-08 00:43:48 +00001111
1112PyDoc_STRVAR(tell_doc,
Antoine Pitrouae4b4722010-05-05 16:31:07 +00001113"tell() -> int. Current file position");
Guido van Rossuma9e20242007-03-08 00:43:48 +00001114
1115PyDoc_STRVAR(readinto_doc,
Benjamin Peterson9a8082f2009-03-05 00:55:56 +00001116"readinto() -> Same as RawIOBase.readinto().");
Guido van Rossuma9e20242007-03-08 00:43:48 +00001117
1118PyDoc_STRVAR(close_doc,
1119"close() -> None. Close the file.\n"
1120"\n"
1121"A closed file cannot be used for further I/O operations. close() may be\n"
1122"called more than once without error. Changes the fileno to -1.");
1123
1124PyDoc_STRVAR(isatty_doc,
1125"isatty() -> bool. True if the file is connected to a tty device.");
1126
Guido van Rossuma9e20242007-03-08 00:43:48 +00001127PyDoc_STRVAR(seekable_doc,
1128"seekable() -> bool. True if file supports random-access.");
1129
1130PyDoc_STRVAR(readable_doc,
1131"readable() -> bool. True if file was opened in a read mode.");
1132
1133PyDoc_STRVAR(writable_doc,
1134"writable() -> bool. True if file was opened in a write mode.");
1135
1136static PyMethodDef fileio_methods[] = {
Antoine Pitrouae4b4722010-05-05 16:31:07 +00001137 {"read", (PyCFunction)fileio_read, METH_VARARGS, read_doc},
1138 {"readall", (PyCFunction)fileio_readall, METH_NOARGS, readall_doc},
1139 {"readinto", (PyCFunction)fileio_readinto, METH_VARARGS, readinto_doc},
1140 {"write", (PyCFunction)fileio_write, METH_VARARGS, write_doc},
1141 {"seek", (PyCFunction)fileio_seek, METH_VARARGS, seek_doc},
1142 {"tell", (PyCFunction)fileio_tell, METH_VARARGS, tell_doc},
Thomas Hellerc6a55ee2007-07-11 12:45:46 +00001143#ifdef HAVE_FTRUNCATE
Antoine Pitrouae4b4722010-05-05 16:31:07 +00001144 {"truncate", (PyCFunction)fileio_truncate, METH_VARARGS, truncate_doc},
Thomas Hellerc6a55ee2007-07-11 12:45:46 +00001145#endif
Antoine Pitrouae4b4722010-05-05 16:31:07 +00001146 {"close", (PyCFunction)fileio_close, METH_NOARGS, close_doc},
1147 {"seekable", (PyCFunction)fileio_seekable, METH_NOARGS, seekable_doc},
1148 {"readable", (PyCFunction)fileio_readable, METH_NOARGS, readable_doc},
1149 {"writable", (PyCFunction)fileio_writable, METH_NOARGS, writable_doc},
1150 {"fileno", (PyCFunction)fileio_fileno, METH_NOARGS, fileno_doc},
1151 {"isatty", (PyCFunction)fileio_isatty, METH_NOARGS, isatty_doc},
Antoine Pitroue033e062010-10-29 10:38:18 +00001152 {"_dealloc_warn", (PyCFunction)fileio_dealloc_warn, METH_O, NULL},
Antoine Pitrou243757e2010-11-05 21:15:39 +00001153 {"__getstate__", (PyCFunction)fileio_getstate, METH_NOARGS, NULL},
Antoine Pitrouae4b4722010-05-05 16:31:07 +00001154 {NULL, NULL} /* sentinel */
Guido van Rossuma9e20242007-03-08 00:43:48 +00001155};
1156
Guido van Rossum53807da2007-04-10 19:01:47 +00001157/* 'closed' and 'mode' are attributes for backwards compatibility reasons. */
1158
Guido van Rossumb0428152007-04-08 17:44:42 +00001159static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +00001160get_closed(fileio *self, void *closure)
Guido van Rossumb0428152007-04-08 17:44:42 +00001161{
Antoine Pitrouae4b4722010-05-05 16:31:07 +00001162 return PyBool_FromLong((long)(self->fd < 0));
Guido van Rossum53807da2007-04-10 19:01:47 +00001163}
1164
1165static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +00001166get_closefd(fileio *self, void *closure)
Christian Heimesecc42a22008-11-05 19:30:32 +00001167{
Antoine Pitrouae4b4722010-05-05 16:31:07 +00001168 return PyBool_FromLong((long)(self->closefd));
Christian Heimesecc42a22008-11-05 19:30:32 +00001169}
1170
1171static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +00001172get_mode(fileio *self, void *closure)
Guido van Rossum53807da2007-04-10 19:01:47 +00001173{
Antoine Pitrouae4b4722010-05-05 16:31:07 +00001174 return PyUnicode_FromString(mode_string(self));
Guido van Rossumb0428152007-04-08 17:44:42 +00001175}
1176
1177static PyGetSetDef fileio_getsetlist[] = {
Antoine Pitrouae4b4722010-05-05 16:31:07 +00001178 {"closed", (getter)get_closed, NULL, "True if the file is closed"},
1179 {"closefd", (getter)get_closefd, NULL,
1180 "True if the file descriptor will be closed"},
1181 {"mode", (getter)get_mode, NULL, "String giving the file mode"},
1182 {NULL},
Guido van Rossumb0428152007-04-08 17:44:42 +00001183};
1184
Guido van Rossuma9e20242007-03-08 00:43:48 +00001185PyTypeObject PyFileIO_Type = {
Antoine Pitrouae4b4722010-05-05 16:31:07 +00001186 PyVarObject_HEAD_INIT(NULL, 0)
1187 "_io.FileIO",
1188 sizeof(fileio),
1189 0,
1190 (destructor)fileio_dealloc, /* tp_dealloc */
1191 0, /* tp_print */
1192 0, /* tp_getattr */
1193 0, /* tp_setattr */
1194 0, /* tp_reserved */
1195 (reprfunc)fileio_repr, /* tp_repr */
1196 0, /* tp_as_number */
1197 0, /* tp_as_sequence */
1198 0, /* tp_as_mapping */
1199 0, /* tp_hash */
1200 0, /* tp_call */
1201 0, /* tp_str */
1202 PyObject_GenericGetAttr, /* tp_getattro */
1203 0, /* tp_setattro */
1204 0, /* tp_as_buffer */
1205 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE
1206 | Py_TPFLAGS_HAVE_GC, /* tp_flags */
1207 fileio_doc, /* tp_doc */
1208 (traverseproc)fileio_traverse, /* tp_traverse */
1209 (inquiry)fileio_clear, /* tp_clear */
1210 0, /* tp_richcompare */
1211 offsetof(fileio, weakreflist), /* tp_weaklistoffset */
1212 0, /* tp_iter */
1213 0, /* tp_iternext */
1214 fileio_methods, /* tp_methods */
1215 0, /* tp_members */
1216 fileio_getsetlist, /* tp_getset */
1217 0, /* tp_base */
1218 0, /* tp_dict */
1219 0, /* tp_descr_get */
1220 0, /* tp_descr_set */
1221 offsetof(fileio, dict), /* tp_dictoffset */
1222 fileio_init, /* tp_init */
1223 PyType_GenericAlloc, /* tp_alloc */
1224 fileio_new, /* tp_new */
1225 PyObject_GC_Del, /* tp_free */
Guido van Rossuma9e20242007-03-08 00:43:48 +00001226};