blob: df3affe1ee2de7a7c9abc68b6c979c3ee8f29e3f [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
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000172dircheck(fileio* self, const char *name)
Guido van Rossuma9e20242007-03-08 00:43:48 +0000173{
174#if defined(HAVE_FSTAT) && defined(S_IFDIR) && 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)) {
179 char *msg = strerror(EISDIR);
180 PyObject *exc;
181 if (internal_close(self))
182 return -1;
Guido van Rossum53807da2007-04-10 19:01:47 +0000183
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000184 exc = PyObject_CallFunction(PyExc_IOError, "(iss)",
185 EISDIR, msg, name);
186 PyErr_SetObject(PyExc_IOError, exc);
187 Py_XDECREF(exc);
188 return -1;
189 }
Guido van Rossuma9e20242007-03-08 00:43:48 +0000190#endif
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000191 return 0;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000192}
193
Benjamin Peterson806d4022009-01-19 15:11:51 +0000194static int
195check_fd(int fd)
196{
197#if defined(HAVE_FSTAT)
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000198 struct stat buf;
199 if (!_PyVerify_fd(fd) || (fstat(fd, &buf) < 0 && errno == EBADF)) {
200 PyObject *exc;
201 char *msg = strerror(EBADF);
202 exc = PyObject_CallFunction(PyExc_OSError, "(is)",
203 EBADF, msg);
204 PyErr_SetObject(PyExc_OSError, exc);
205 Py_XDECREF(exc);
206 return -1;
207 }
Benjamin Peterson806d4022009-01-19 15:11:51 +0000208#endif
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000209 return 0;
Benjamin Peterson806d4022009-01-19 15:11:51 +0000210}
211
Guido van Rossuma9e20242007-03-08 00:43:48 +0000212
213static int
214fileio_init(PyObject *oself, PyObject *args, PyObject *kwds)
215{
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000216 fileio *self = (fileio *) oself;
Ross Lagerwall59142db2011-10-31 20:34:46 +0200217 static char *kwlist[] = {"file", "mode", "closefd", "opener", NULL};
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000218 const char *name = NULL;
Ross Lagerwall59142db2011-10-31 20:34:46 +0200219 PyObject *nameobj, *stringobj = NULL, *opener = Py_None;
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000220 char *mode = "r";
221 char *s;
Thomas Helleraf2be262007-07-12 11:03:13 +0000222#ifdef MS_WINDOWS
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000223 Py_UNICODE *widename = NULL;
Thomas Helleraf2be262007-07-12 11:03:13 +0000224#endif
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000225 int ret = 0;
226 int rwa = 0, plus = 0, append = 0;
227 int flags = 0;
228 int fd = -1;
229 int closefd = 1;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000230
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000231 assert(PyFileIO_Check(oself));
232 if (self->fd >= 0) {
233 /* Have to close the existing file first. */
234 if (internal_close(self) < 0)
235 return -1;
236 }
Guido van Rossuma9e20242007-03-08 00:43:48 +0000237
Ross Lagerwall59142db2011-10-31 20:34:46 +0200238 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|siO:fileio",
239 kwlist, &nameobj, &mode, &closefd,
240 &opener))
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000241 return -1;
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000242
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000243 if (PyFloat_Check(nameobj)) {
244 PyErr_SetString(PyExc_TypeError,
245 "integer argument expected, got float");
246 return -1;
247 }
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000248
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000249 fd = PyLong_AsLong(nameobj);
250 if (fd < 0) {
251 if (!PyErr_Occurred()) {
252 PyErr_SetString(PyExc_ValueError,
253 "Negative filedescriptor");
254 return -1;
255 }
256 PyErr_Clear();
257 }
Guido van Rossumb0428152007-04-08 17:44:42 +0000258
Hirokazu Yamamoto8223c242009-05-17 04:21:53 +0000259#ifdef MS_WINDOWS
Victor Stinnerfe9a8612011-09-29 23:19:04 +0200260 if (PyUnicode_Check(nameobj)) {
Antoine Pitrou13348842012-01-29 18:36:34 +0100261 int rv = _PyUnicode_HasNULChars(nameobj);
262 if (rv) {
263 if (rv != -1)
264 PyErr_SetString(PyExc_TypeError, "embedded NUL character");
265 return -1;
266 }
Victor Stinnerfe9a8612011-09-29 23:19:04 +0200267 widename = PyUnicode_AsUnicode(nameobj);
268 if (widename == NULL)
269 return -1;
270 } else
Guido van Rossuma9e20242007-03-08 00:43:48 +0000271#endif
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000272 if (fd < 0)
273 {
Antoine Pitrou13348842012-01-29 18:36:34 +0100274 if (!PyUnicode_FSConverter(nameobj, &stringobj)) {
275 return -1;
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000276 }
Antoine Pitrou13348842012-01-29 18:36:34 +0100277 name = PyBytes_AS_STRING(stringobj);
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000278 }
Guido van Rossuma9e20242007-03-08 00:43:48 +0000279
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000280 s = mode;
281 while (*s) {
282 switch (*s++) {
Charles-François Natalidc3044c2012-01-09 22:40:02 +0100283 case 'x':
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000284 if (rwa) {
285 bad_mode:
286 PyErr_SetString(PyExc_ValueError,
Charles-François Natalidc3044c2012-01-09 22:40:02 +0100287 "Must have exactly one of create/read/write/append "
Georg Brandl28928ae2010-10-21 13:45:52 +0000288 "mode and at most one plus");
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000289 goto error;
290 }
291 rwa = 1;
Charles-François Natalidc3044c2012-01-09 22:40:02 +0100292 self->created = 1;
293 self->writable = 1;
294 flags |= O_EXCL | O_CREAT;
295 break;
296 case 'r':
297 if (rwa)
298 goto bad_mode;
299 rwa = 1;
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000300 self->readable = 1;
301 break;
302 case 'w':
303 if (rwa)
304 goto bad_mode;
305 rwa = 1;
306 self->writable = 1;
307 flags |= O_CREAT | O_TRUNC;
308 break;
309 case 'a':
310 if (rwa)
311 goto bad_mode;
312 rwa = 1;
313 self->writable = 1;
314 flags |= O_CREAT;
315 append = 1;
316 break;
317 case 'b':
318 break;
319 case '+':
320 if (plus)
321 goto bad_mode;
322 self->readable = self->writable = 1;
323 plus = 1;
324 break;
325 default:
326 PyErr_Format(PyExc_ValueError,
327 "invalid mode: %.200s", mode);
328 goto error;
329 }
330 }
Guido van Rossuma9e20242007-03-08 00:43:48 +0000331
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000332 if (!rwa)
333 goto bad_mode;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000334
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000335 if (self->readable && self->writable)
336 flags |= O_RDWR;
337 else if (self->readable)
338 flags |= O_RDONLY;
339 else
340 flags |= O_WRONLY;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000341
342#ifdef O_BINARY
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000343 flags |= O_BINARY;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000344#endif
345
Walter Dörwald0e411482007-06-06 16:55:38 +0000346#ifdef O_APPEND
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000347 if (append)
348 flags |= O_APPEND;
Walter Dörwald0e411482007-06-06 16:55:38 +0000349#endif
350
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000351 if (fd >= 0) {
352 if (check_fd(fd))
353 goto error;
354 self->fd = fd;
355 self->closefd = closefd;
356 }
357 else {
358 self->closefd = 1;
359 if (!closefd) {
360 PyErr_SetString(PyExc_ValueError,
361 "Cannot use closefd=False with file name");
362 goto error;
363 }
Guido van Rossum2dced8b2007-10-30 17:27:30 +0000364
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000365 errno = 0;
Ross Lagerwall59142db2011-10-31 20:34:46 +0200366 if (opener == Py_None) {
367 Py_BEGIN_ALLOW_THREADS
Thomas Helleraf2be262007-07-12 11:03:13 +0000368#ifdef MS_WINDOWS
Ross Lagerwall59142db2011-10-31 20:34:46 +0200369 if (widename != NULL)
370 self->fd = _wopen(widename, flags, 0666);
371 else
Thomas Helleraf2be262007-07-12 11:03:13 +0000372#endif
Ross Lagerwall59142db2011-10-31 20:34:46 +0200373 self->fd = open(name, flags, 0666);
374 Py_END_ALLOW_THREADS
375 } else {
376 PyObject *fdobj = PyObject_CallFunction(
377 opener, "Oi", nameobj, flags);
378 if (fdobj == NULL)
379 goto error;
380 if (!PyLong_Check(fdobj)) {
381 Py_DECREF(fdobj);
382 PyErr_SetString(PyExc_TypeError,
383 "expected integer from opener");
384 goto error;
385 }
386
387 self->fd = PyLong_AsLong(fdobj);
388 Py_DECREF(fdobj);
389 if (self->fd == -1) {
390 goto error;
391 }
392 }
393
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000394 if (self->fd < 0) {
Christian Heimes0b489542007-10-31 19:20:48 +0000395#ifdef MS_WINDOWS
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000396 if (widename != NULL)
Victor Stinnerfe9a8612011-09-29 23:19:04 +0200397 PyErr_SetFromErrnoWithFilenameObject(PyExc_IOError, nameobj);
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000398 else
Christian Heimes0b489542007-10-31 19:20:48 +0000399#endif
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000400 PyErr_SetFromErrnoWithFilename(PyExc_IOError, name);
401 goto error;
402 }
Benjamin Peterson430d4692010-10-30 23:13:57 +0000403 if (dircheck(self, name) < 0)
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000404 goto error;
405 }
Guido van Rossuma9e20242007-03-08 00:43:48 +0000406
Victor Stinner89e34362011-01-07 18:47:22 +0000407#if defined(MS_WINDOWS) || defined(__CYGWIN__)
408 /* don't translate newlines (\r\n <=> \n) */
409 _setmode(self->fd, O_BINARY);
410#endif
411
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000412 if (PyObject_SetAttrString((PyObject *)self, "name", nameobj) < 0)
413 goto error;
Antoine Pitrou08838b62009-01-21 00:55:13 +0000414
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000415 if (append) {
416 /* For consistent behaviour, we explicitly seek to the
417 end of file (otherwise, it might be done only on the
418 first write()). */
419 PyObject *pos = portable_lseek(self->fd, NULL, 2);
Antoine Pitrou8d2b51b2010-10-30 16:19:14 +0000420 if (pos == NULL) {
421 if (closefd) {
422 close(self->fd);
423 self->fd = -1;
424 }
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000425 goto error;
Antoine Pitrou8d2b51b2010-10-30 16:19:14 +0000426 }
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000427 Py_DECREF(pos);
428 }
Antoine Pitrou7fb111b2009-03-04 11:14:01 +0000429
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000430 goto done;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000431
432 error:
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000433 ret = -1;
Benjamin Petersonbbb04122010-10-30 23:16:28 +0000434 if (self->fd >= 0)
435 internal_close(self);
Guido van Rossum53807da2007-04-10 19:01:47 +0000436
Guido van Rossuma9e20242007-03-08 00:43:48 +0000437 done:
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000438 Py_CLEAR(stringobj);
439 return ret;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000440}
441
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000442static int
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000443fileio_traverse(fileio *self, visitproc visit, void *arg)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000444{
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000445 Py_VISIT(self->dict);
446 return 0;
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000447}
448
449static int
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000450fileio_clear(fileio *self)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000451{
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000452 Py_CLEAR(self->dict);
453 return 0;
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000454}
455
Guido van Rossuma9e20242007-03-08 00:43:48 +0000456static void
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000457fileio_dealloc(fileio *self)
Guido van Rossuma9e20242007-03-08 00:43:48 +0000458{
Antoine Pitroue033e062010-10-29 10:38:18 +0000459 self->deallocating = 1;
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000460 if (_PyIOBase_finalize((PyObject *) self) < 0)
461 return;
462 _PyObject_GC_UNTRACK(self);
463 if (self->weakreflist != NULL)
464 PyObject_ClearWeakRefs((PyObject *) self);
465 Py_CLEAR(self->dict);
466 Py_TYPE(self)->tp_free((PyObject *)self);
Guido van Rossuma9e20242007-03-08 00:43:48 +0000467}
468
469static PyObject *
470err_closed(void)
471{
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000472 PyErr_SetString(PyExc_ValueError, "I/O operation on closed file");
473 return NULL;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000474}
475
476static PyObject *
Guido van Rossum53807da2007-04-10 19:01:47 +0000477err_mode(char *action)
478{
Antoine Pitrou0d739d72010-09-05 23:01:12 +0000479 PyErr_Format(IO_STATE->unsupported_operation,
480 "File not open for %s", action);
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000481 return NULL;
Guido van Rossum53807da2007-04-10 19:01:47 +0000482}
483
484static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000485fileio_fileno(fileio *self)
Guido van Rossuma9e20242007-03-08 00:43:48 +0000486{
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000487 if (self->fd < 0)
488 return err_closed();
489 return PyLong_FromLong((long) self->fd);
Guido van Rossuma9e20242007-03-08 00:43:48 +0000490}
491
492static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000493fileio_readable(fileio *self)
Guido van Rossuma9e20242007-03-08 00:43:48 +0000494{
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000495 if (self->fd < 0)
496 return err_closed();
497 return PyBool_FromLong((long) self->readable);
Guido van Rossuma9e20242007-03-08 00:43:48 +0000498}
499
500static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000501fileio_writable(fileio *self)
Guido van Rossuma9e20242007-03-08 00:43:48 +0000502{
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000503 if (self->fd < 0)
504 return err_closed();
505 return PyBool_FromLong((long) self->writable);
Guido van Rossuma9e20242007-03-08 00:43:48 +0000506}
507
508static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000509fileio_seekable(fileio *self)
Guido van Rossuma9e20242007-03-08 00:43:48 +0000510{
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000511 if (self->fd < 0)
512 return err_closed();
513 if (self->seekable < 0) {
514 PyObject *pos = portable_lseek(self->fd, NULL, SEEK_CUR);
515 if (pos == NULL) {
516 PyErr_Clear();
517 self->seekable = 0;
518 } else {
519 Py_DECREF(pos);
520 self->seekable = 1;
521 }
522 }
523 return PyBool_FromLong((long) self->seekable);
Guido van Rossuma9e20242007-03-08 00:43:48 +0000524}
525
526static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000527fileio_readinto(fileio *self, PyObject *args)
Guido van Rossuma9e20242007-03-08 00:43:48 +0000528{
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000529 Py_buffer pbuf;
Victor Stinnere6edec22011-01-04 00:29:35 +0000530 Py_ssize_t n, len;
Antoine Pitrouc345ce12011-12-16 12:28:32 +0100531 int err;
Guido van Rossum53807da2007-04-10 19:01:47 +0000532
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000533 if (self->fd < 0)
534 return err_closed();
535 if (!self->readable)
536 return err_mode("reading");
Guido van Rossum53807da2007-04-10 19:01:47 +0000537
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000538 if (!PyArg_ParseTuple(args, "w*", &pbuf))
539 return NULL;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000540
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000541 if (_PyVerify_fd(self->fd)) {
Victor Stinnere6edec22011-01-04 00:29:35 +0000542 len = pbuf.len;
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000543 Py_BEGIN_ALLOW_THREADS
544 errno = 0;
Victor Stinnere6edec22011-01-04 00:29:35 +0000545#if defined(MS_WIN64) || defined(MS_WINDOWS)
546 if (len > INT_MAX)
547 len = INT_MAX;
548 n = read(self->fd, pbuf.buf, (int)len);
549#else
Victor Stinner72344792011-01-11 00:04:12 +0000550 n = read(self->fd, pbuf.buf, len);
Victor Stinnere6edec22011-01-04 00:29:35 +0000551#endif
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000552 Py_END_ALLOW_THREADS
553 } else
554 n = -1;
Antoine Pitrouc345ce12011-12-16 12:28:32 +0100555 err = errno;
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000556 PyBuffer_Release(&pbuf);
557 if (n < 0) {
Antoine Pitrouc345ce12011-12-16 12:28:32 +0100558 if (err == EAGAIN)
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000559 Py_RETURN_NONE;
Antoine Pitrouc345ce12011-12-16 12:28:32 +0100560 errno = err;
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000561 PyErr_SetFromErrno(PyExc_IOError);
562 return NULL;
563 }
Guido van Rossuma9e20242007-03-08 00:43:48 +0000564
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000565 return PyLong_FromSsize_t(n);
Guido van Rossuma9e20242007-03-08 00:43:48 +0000566}
567
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000568static size_t
Victor Stinnere9d44ccb2011-05-26 00:16:44 +0200569new_buffersize(fileio *self, size_t currentsize
570#ifdef HAVE_FSTAT
Victor Stinnera2a64772011-10-11 22:45:02 +0200571 , Py_off_t pos, Py_off_t end
Victor Stinnere9d44ccb2011-05-26 00:16:44 +0200572#endif
573 )
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000574{
Antoine Pitroua3f44572012-04-17 13:50:58 +0200575 size_t addend;
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000576#ifdef HAVE_FSTAT
Victor Stinnera2a64772011-10-11 22:45:02 +0200577 if (end != (Py_off_t)-1) {
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000578 /* Files claiming a size smaller than SMALLCHUNK may
579 actually be streaming pseudo-files. In this case, we
580 apply the more aggressive algorithm below.
581 */
582 if (end >= SMALLCHUNK && end >= pos && pos >= 0) {
583 /* Add 1 so if the file were to grow we'd notice. */
Victor Stinnerc5af7732011-10-11 23:00:31 +0200584 Py_off_t bufsize = currentsize + end - pos + 1;
585 if (bufsize < PY_SSIZE_T_MAX)
586 return (size_t)bufsize;
587 else
588 return PY_SSIZE_T_MAX;
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000589 }
590 }
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000591#endif
Nadeem Vawdad41a98b2011-10-13 13:34:16 +0200592 /* Expand the buffer by an amount proportional to the current size,
Antoine Pitroua3f44572012-04-17 13:50:58 +0200593 giving us amortized linear-time behavior. For bigger sizes, use a
594 less-than-double growth factor to avoid excessive allocation. */
595 if (currentsize > 65536)
596 addend = currentsize >> 3;
597 else
598 addend = 256 + currentsize;
599 if (addend < SMALLCHUNK)
600 /* Avoid tiny read() calls. */
601 addend = SMALLCHUNK;
602 return addend + currentsize;
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000603}
604
Guido van Rossum7165cb12007-07-10 06:54:34 +0000605static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000606fileio_readall(fileio *self)
Guido van Rossum7165cb12007-07-10 06:54:34 +0000607{
Victor Stinnere9d44ccb2011-05-26 00:16:44 +0200608#ifdef HAVE_FSTAT
609 struct stat st;
Victor Stinnera2a64772011-10-11 22:45:02 +0200610 Py_off_t pos, end;
Victor Stinnere9d44ccb2011-05-26 00:16:44 +0200611#endif
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000612 PyObject *result;
613 Py_ssize_t total = 0;
614 int n;
Victor Stinnere9d44ccb2011-05-26 00:16:44 +0200615 size_t newsize;
Guido van Rossum7165cb12007-07-10 06:54:34 +0000616
Victor Stinnerb79f28c2011-05-25 22:09:03 +0200617 if (self->fd < 0)
618 return err_closed();
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000619 if (!_PyVerify_fd(self->fd))
620 return PyErr_SetFromErrno(PyExc_IOError);
Kristján Valur Jónssona8abe862009-03-24 15:27:42 +0000621
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000622 result = PyBytes_FromStringAndSize(NULL, SMALLCHUNK);
623 if (result == NULL)
624 return NULL;
Guido van Rossum7165cb12007-07-10 06:54:34 +0000625
Victor Stinnere9d44ccb2011-05-26 00:16:44 +0200626#ifdef HAVE_FSTAT
627#if defined(MS_WIN64) || defined(MS_WINDOWS)
628 pos = _lseeki64(self->fd, 0L, SEEK_CUR);
629#else
630 pos = lseek(self->fd, 0L, SEEK_CUR);
631#endif
632 if (fstat(self->fd, &st) == 0)
633 end = st.st_size;
634 else
Victor Stinnera2a64772011-10-11 22:45:02 +0200635 end = (Py_off_t)-1;
Victor Stinnere9d44ccb2011-05-26 00:16:44 +0200636#endif
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000637 while (1) {
Victor Stinnere9d44ccb2011-05-26 00:16:44 +0200638#ifdef HAVE_FSTAT
639 newsize = new_buffersize(self, total, pos, end);
640#else
641 newsize = new_buffersize(self, total);
642#endif
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000643 if (newsize > PY_SSIZE_T_MAX || newsize <= 0) {
644 PyErr_SetString(PyExc_OverflowError,
645 "unbounded read returned more bytes "
646 "than a Python string can hold ");
647 Py_DECREF(result);
648 return NULL;
649 }
Christian Heimesa872de52008-12-05 08:26:55 +0000650
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000651 if (PyBytes_GET_SIZE(result) < (Py_ssize_t)newsize) {
652 if (_PyBytes_Resize(&result, newsize) < 0) {
653 if (total == 0) {
654 Py_DECREF(result);
655 return NULL;
656 }
657 PyErr_Clear();
658 break;
659 }
660 }
661 Py_BEGIN_ALLOW_THREADS
662 errno = 0;
663 n = read(self->fd,
664 PyBytes_AS_STRING(result) + total,
665 newsize - total);
666 Py_END_ALLOW_THREADS
667 if (n == 0)
668 break;
669 if (n < 0) {
670 if (total > 0)
671 break;
672 if (errno == EAGAIN) {
673 Py_DECREF(result);
674 Py_RETURN_NONE;
675 }
676 Py_DECREF(result);
677 PyErr_SetFromErrno(PyExc_IOError);
678 return NULL;
679 }
680 total += n;
Victor Stinnere9d44ccb2011-05-26 00:16:44 +0200681#ifdef HAVE_FSTAT
682 pos += n;
683#endif
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000684 }
Guido van Rossum7165cb12007-07-10 06:54:34 +0000685
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000686 if (PyBytes_GET_SIZE(result) > total) {
687 if (_PyBytes_Resize(&result, total) < 0) {
688 /* This should never happen, but just in case */
689 Py_DECREF(result);
690 return NULL;
691 }
692 }
693 return result;
Guido van Rossum7165cb12007-07-10 06:54:34 +0000694}
695
Guido van Rossuma9e20242007-03-08 00:43:48 +0000696static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000697fileio_read(fileio *self, PyObject *args)
Guido van Rossuma9e20242007-03-08 00:43:48 +0000698{
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000699 char *ptr;
700 Py_ssize_t n;
701 Py_ssize_t size = -1;
702 PyObject *bytes;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000703
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000704 if (self->fd < 0)
705 return err_closed();
706 if (!self->readable)
707 return err_mode("reading");
Guido van Rossuma9e20242007-03-08 00:43:48 +0000708
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000709 if (!PyArg_ParseTuple(args, "|O&", &_PyIO_ConvertSsize_t, &size))
710 return NULL;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000711
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000712 if (size < 0) {
713 return fileio_readall(self);
714 }
Guido van Rossumc2f93dc2007-05-24 00:50:02 +0000715
Victor Stinnerc655a722011-07-05 11:31:49 +0200716#if defined(MS_WIN64) || defined(MS_WINDOWS)
717 if (size > INT_MAX)
718 size = INT_MAX;
719#endif
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000720 bytes = PyBytes_FromStringAndSize(NULL, size);
721 if (bytes == NULL)
722 return NULL;
723 ptr = PyBytes_AS_STRING(bytes);
Guido van Rossuma9e20242007-03-08 00:43:48 +0000724
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000725 if (_PyVerify_fd(self->fd)) {
726 Py_BEGIN_ALLOW_THREADS
727 errno = 0;
Victor Stinnerc655a722011-07-05 11:31:49 +0200728#if defined(MS_WIN64) || defined(MS_WINDOWS)
729 n = read(self->fd, ptr, (int)size);
730#else
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000731 n = read(self->fd, ptr, size);
Victor Stinnerc655a722011-07-05 11:31:49 +0200732#endif
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000733 Py_END_ALLOW_THREADS
734 } else
735 n = -1;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000736
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000737 if (n < 0) {
Antoine Pitrouc345ce12011-12-16 12:28:32 +0100738 int err = errno;
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000739 Py_DECREF(bytes);
Antoine Pitrouc345ce12011-12-16 12:28:32 +0100740 if (err == EAGAIN)
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000741 Py_RETURN_NONE;
Antoine Pitrouc345ce12011-12-16 12:28:32 +0100742 errno = err;
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000743 PyErr_SetFromErrno(PyExc_IOError);
744 return NULL;
745 }
Guido van Rossuma9e20242007-03-08 00:43:48 +0000746
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000747 if (n != size) {
748 if (_PyBytes_Resize(&bytes, n) < 0) {
749 Py_DECREF(bytes);
750 return NULL;
751 }
752 }
Guido van Rossuma9e20242007-03-08 00:43:48 +0000753
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000754 return (PyObject *) bytes;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000755}
756
757static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000758fileio_write(fileio *self, PyObject *args)
Guido van Rossuma9e20242007-03-08 00:43:48 +0000759{
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000760 Py_buffer pbuf;
Victor Stinnere6edec22011-01-04 00:29:35 +0000761 Py_ssize_t n, len;
Antoine Pitrouc345ce12011-12-16 12:28:32 +0100762 int err;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000763
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000764 if (self->fd < 0)
765 return err_closed();
766 if (!self->writable)
767 return err_mode("writing");
Guido van Rossum53807da2007-04-10 19:01:47 +0000768
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000769 if (!PyArg_ParseTuple(args, "y*", &pbuf))
770 return NULL;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000771
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000772 if (_PyVerify_fd(self->fd)) {
773 Py_BEGIN_ALLOW_THREADS
774 errno = 0;
Victor Stinnere6edec22011-01-04 00:29:35 +0000775 len = pbuf.len;
776#if defined(MS_WIN64) || defined(MS_WINDOWS)
Victor Stinnere0daff12011-03-20 23:36:35 +0100777 if (len > 32767 && isatty(self->fd)) {
778 /* Issue #11395: the Windows console returns an error (12: not
779 enough space error) on writing into stdout if stdout mode is
780 binary and the length is greater than 66,000 bytes (or less,
781 depending on heap usage). */
782 len = 32767;
783 }
784 else if (len > INT_MAX)
Victor Stinnere6edec22011-01-04 00:29:35 +0000785 len = INT_MAX;
786 n = write(self->fd, pbuf.buf, (int)len);
787#else
Victor Stinner72344792011-01-11 00:04:12 +0000788 n = write(self->fd, pbuf.buf, len);
Victor Stinnere6edec22011-01-04 00:29:35 +0000789#endif
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000790 Py_END_ALLOW_THREADS
791 } else
792 n = -1;
Antoine Pitrouc345ce12011-12-16 12:28:32 +0100793 err = errno;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000794
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000795 PyBuffer_Release(&pbuf);
Martin v. Löwis423be952008-08-13 15:53:07 +0000796
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000797 if (n < 0) {
Antoine Pitrouc345ce12011-12-16 12:28:32 +0100798 if (err == EAGAIN)
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000799 Py_RETURN_NONE;
Antoine Pitrouc345ce12011-12-16 12:28:32 +0100800 errno = err;
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000801 PyErr_SetFromErrno(PyExc_IOError);
802 return NULL;
803 }
Guido van Rossuma9e20242007-03-08 00:43:48 +0000804
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000805 return PyLong_FromSsize_t(n);
Guido van Rossuma9e20242007-03-08 00:43:48 +0000806}
807
Guido van Rossum53807da2007-04-10 19:01:47 +0000808/* XXX Windows support below is likely incomplete */
809
Guido van Rossum53807da2007-04-10 19:01:47 +0000810/* Cribbed from posix_lseek() */
811static PyObject *
812portable_lseek(int fd, PyObject *posobj, int whence)
813{
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000814 Py_off_t pos, res;
Guido van Rossum53807da2007-04-10 19:01:47 +0000815
816#ifdef SEEK_SET
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000817 /* Turn 0, 1, 2 into SEEK_{SET,CUR,END} */
818 switch (whence) {
Guido van Rossum53807da2007-04-10 19:01:47 +0000819#if SEEK_SET != 0
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000820 case 0: whence = SEEK_SET; break;
Guido van Rossum53807da2007-04-10 19:01:47 +0000821#endif
822#if SEEK_CUR != 1
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000823 case 1: whence = SEEK_CUR; break;
Guido van Rossum53807da2007-04-10 19:01:47 +0000824#endif
Antoine Pitrou4f7945f2009-01-20 11:42:11 +0000825#if SEEK_END != 2
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000826 case 2: whence = SEEK_END; break;
Guido van Rossum53807da2007-04-10 19:01:47 +0000827#endif
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000828 }
Guido van Rossum53807da2007-04-10 19:01:47 +0000829#endif /* SEEK_SET */
830
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000831 if (posobj == NULL)
832 pos = 0;
833 else {
834 if(PyFloat_Check(posobj)) {
835 PyErr_SetString(PyExc_TypeError, "an integer is required");
836 return NULL;
837 }
Alexandre Vassalotti77250f42008-05-06 19:48:38 +0000838#if defined(HAVE_LARGEFILE_SUPPORT)
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000839 pos = PyLong_AsLongLong(posobj);
Guido van Rossum53807da2007-04-10 19:01:47 +0000840#else
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000841 pos = PyLong_AsLong(posobj);
Guido van Rossum53807da2007-04-10 19:01:47 +0000842#endif
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000843 if (PyErr_Occurred())
844 return NULL;
845 }
Guido van Rossum53807da2007-04-10 19:01:47 +0000846
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000847 if (_PyVerify_fd(fd)) {
848 Py_BEGIN_ALLOW_THREADS
Guido van Rossum53807da2007-04-10 19:01:47 +0000849#if defined(MS_WIN64) || defined(MS_WINDOWS)
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000850 res = _lseeki64(fd, pos, whence);
Guido van Rossum53807da2007-04-10 19:01:47 +0000851#else
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000852 res = lseek(fd, pos, whence);
Guido van Rossum53807da2007-04-10 19:01:47 +0000853#endif
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000854 Py_END_ALLOW_THREADS
855 } else
856 res = -1;
857 if (res < 0)
858 return PyErr_SetFromErrno(PyExc_IOError);
Guido van Rossum53807da2007-04-10 19:01:47 +0000859
Alexandre Vassalotti77250f42008-05-06 19:48:38 +0000860#if defined(HAVE_LARGEFILE_SUPPORT)
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000861 return PyLong_FromLongLong(res);
Alexandre Vassalotti77250f42008-05-06 19:48:38 +0000862#else
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000863 return PyLong_FromLong(res);
Guido van Rossum53807da2007-04-10 19:01:47 +0000864#endif
865}
866
Guido van Rossuma9e20242007-03-08 00:43:48 +0000867static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000868fileio_seek(fileio *self, PyObject *args)
Guido van Rossuma9e20242007-03-08 00:43:48 +0000869{
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000870 PyObject *posobj;
871 int whence = 0;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000872
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000873 if (self->fd < 0)
874 return err_closed();
Guido van Rossuma9e20242007-03-08 00:43:48 +0000875
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000876 if (!PyArg_ParseTuple(args, "O|i", &posobj, &whence))
877 return NULL;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000878
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000879 return portable_lseek(self->fd, posobj, whence);
Guido van Rossuma9e20242007-03-08 00:43:48 +0000880}
881
882static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000883fileio_tell(fileio *self, PyObject *args)
Guido van Rossuma9e20242007-03-08 00:43:48 +0000884{
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000885 if (self->fd < 0)
886 return err_closed();
Guido van Rossuma9e20242007-03-08 00:43:48 +0000887
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000888 return portable_lseek(self->fd, NULL, 1);
Guido van Rossuma9e20242007-03-08 00:43:48 +0000889}
890
Thomas Hellerc6a55ee2007-07-11 12:45:46 +0000891#ifdef HAVE_FTRUNCATE
Guido van Rossuma9e20242007-03-08 00:43:48 +0000892static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000893fileio_truncate(fileio *self, PyObject *args)
Guido van Rossuma9e20242007-03-08 00:43:48 +0000894{
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000895 PyObject *posobj = NULL; /* the new size wanted by the user */
Antoine Pitrou905a2ff2010-01-31 22:47:27 +0000896#ifndef MS_WINDOWS
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000897 Py_off_t pos;
Antoine Pitrou905a2ff2010-01-31 22:47:27 +0000898#endif
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000899 int ret;
900 int fd;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000901
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000902 fd = self->fd;
903 if (fd < 0)
904 return err_closed();
905 if (!self->writable)
906 return err_mode("writing");
Guido van Rossuma9e20242007-03-08 00:43:48 +0000907
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000908 if (!PyArg_ParseTuple(args, "|O", &posobj))
909 return NULL;
Guido van Rossum53807da2007-04-10 19:01:47 +0000910
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000911 if (posobj == Py_None || posobj == NULL) {
912 /* Get the current position. */
913 posobj = portable_lseek(fd, NULL, 1);
914 if (posobj == NULL)
915 return NULL;
916 }
917 else {
918 Py_INCREF(posobj);
919 }
Guido van Rossum53807da2007-04-10 19:01:47 +0000920
Thomas Hellerfdeee3a2007-07-12 11:21:36 +0000921#ifdef MS_WINDOWS
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000922 /* MS _chsize doesn't work if newsize doesn't fit in 32 bits,
923 so don't even try using it. */
924 {
925 PyObject *oldposobj, *tempposobj;
926 HANDLE hFile;
Antoine Pitrou905a2ff2010-01-31 22:47:27 +0000927
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000928 /* we save the file pointer position */
929 oldposobj = portable_lseek(fd, NULL, 1);
930 if (oldposobj == NULL) {
931 Py_DECREF(posobj);
932 return NULL;
933 }
Thomas Hellerfdeee3a2007-07-12 11:21:36 +0000934
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000935 /* we then move to the truncation position */
936 tempposobj = portable_lseek(fd, posobj, 0);
937 if (tempposobj == NULL) {
938 Py_DECREF(oldposobj);
939 Py_DECREF(posobj);
940 return NULL;
941 }
942 Py_DECREF(tempposobj);
Antoine Pitrou905a2ff2010-01-31 22:47:27 +0000943
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000944 /* Truncate. Note that this may grow the file! */
945 Py_BEGIN_ALLOW_THREADS
946 errno = 0;
947 hFile = (HANDLE)_get_osfhandle(fd);
948 ret = hFile == (HANDLE)-1; /* testing for INVALID_HANDLE value */
949 if (ret == 0) {
950 ret = SetEndOfFile(hFile) == 0;
951 if (ret)
952 errno = EACCES;
953 }
954 Py_END_ALLOW_THREADS
955
956 /* we restore the file pointer position in any case */
957 tempposobj = portable_lseek(fd, oldposobj, 0);
958 Py_DECREF(oldposobj);
959 if (tempposobj == NULL) {
960 Py_DECREF(posobj);
961 return NULL;
962 }
963 Py_DECREF(tempposobj);
964 }
Thomas Hellerfdeee3a2007-07-12 11:21:36 +0000965#else
Antoine Pitrou905a2ff2010-01-31 22:47:27 +0000966
967#if defined(HAVE_LARGEFILE_SUPPORT)
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000968 pos = PyLong_AsLongLong(posobj);
Antoine Pitrou905a2ff2010-01-31 22:47:27 +0000969#else
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000970 pos = PyLong_AsLong(posobj);
Antoine Pitrou905a2ff2010-01-31 22:47:27 +0000971#endif
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000972 if (PyErr_Occurred()){
973 Py_DECREF(posobj);
974 return NULL;
975 }
Antoine Pitrou905a2ff2010-01-31 22:47:27 +0000976
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000977 Py_BEGIN_ALLOW_THREADS
978 errno = 0;
979 ret = ftruncate(fd, pos);
980 Py_END_ALLOW_THREADS
Antoine Pitrou905a2ff2010-01-31 22:47:27 +0000981
Thomas Hellerfdeee3a2007-07-12 11:21:36 +0000982#endif /* !MS_WINDOWS */
Guido van Rossuma9e20242007-03-08 00:43:48 +0000983
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000984 if (ret != 0) {
985 Py_DECREF(posobj);
986 PyErr_SetFromErrno(PyExc_IOError);
987 return NULL;
988 }
Guido van Rossuma9e20242007-03-08 00:43:48 +0000989
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000990 return posobj;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000991}
Antoine Pitrou905a2ff2010-01-31 22:47:27 +0000992#endif /* HAVE_FTRUNCATE */
Guido van Rossum53807da2007-04-10 19:01:47 +0000993
994static char *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000995mode_string(fileio *self)
Guido van Rossum53807da2007-04-10 19:01:47 +0000996{
Charles-François Natalidc3044c2012-01-09 22:40:02 +0100997 if (self->created) {
998 if (self->readable)
999 return "xb+";
1000 else
1001 return "xb";
1002 }
Antoine Pitrouae4b4722010-05-05 16:31:07 +00001003 if (self->readable) {
1004 if (self->writable)
1005 return "rb+";
1006 else
1007 return "rb";
1008 }
1009 else
1010 return "wb";
Guido van Rossum53807da2007-04-10 19:01:47 +00001011}
Guido van Rossuma9e20242007-03-08 00:43:48 +00001012
1013static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +00001014fileio_repr(fileio *self)
Guido van Rossuma9e20242007-03-08 00:43:48 +00001015{
Martin v. Löwis767046a2011-10-14 15:35:36 +02001016 _Py_IDENTIFIER(name);
Antoine Pitrouae4b4722010-05-05 16:31:07 +00001017 PyObject *nameobj, *res;
Guido van Rossuma9e20242007-03-08 00:43:48 +00001018
Antoine Pitrouae4b4722010-05-05 16:31:07 +00001019 if (self->fd < 0)
1020 return PyUnicode_FromFormat("<_io.FileIO [closed]>");
Antoine Pitrou716c4442009-05-23 19:04:03 +00001021
Martin v. Löwis767046a2011-10-14 15:35:36 +02001022 nameobj = _PyObject_GetAttrId((PyObject *) self, &PyId_name);
Antoine Pitrouae4b4722010-05-05 16:31:07 +00001023 if (nameobj == NULL) {
1024 if (PyErr_ExceptionMatches(PyExc_AttributeError))
1025 PyErr_Clear();
1026 else
1027 return NULL;
1028 res = PyUnicode_FromFormat("<_io.FileIO fd=%d mode='%s'>",
1029 self->fd, mode_string(self));
1030 }
1031 else {
1032 res = PyUnicode_FromFormat("<_io.FileIO name=%R mode='%s'>",
1033 nameobj, mode_string(self));
1034 Py_DECREF(nameobj);
1035 }
1036 return res;
Guido van Rossuma9e20242007-03-08 00:43:48 +00001037}
1038
1039static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +00001040fileio_isatty(fileio *self)
Guido van Rossuma9e20242007-03-08 00:43:48 +00001041{
Antoine Pitrouae4b4722010-05-05 16:31:07 +00001042 long res;
Guido van Rossum53807da2007-04-10 19:01:47 +00001043
Antoine Pitrouae4b4722010-05-05 16:31:07 +00001044 if (self->fd < 0)
1045 return err_closed();
1046 Py_BEGIN_ALLOW_THREADS
1047 res = isatty(self->fd);
1048 Py_END_ALLOW_THREADS
1049 return PyBool_FromLong(res);
Guido van Rossuma9e20242007-03-08 00:43:48 +00001050}
1051
Antoine Pitrou243757e2010-11-05 21:15:39 +00001052static PyObject *
1053fileio_getstate(fileio *self)
1054{
1055 PyErr_Format(PyExc_TypeError,
1056 "cannot serialize '%s' object", Py_TYPE(self)->tp_name);
1057 return NULL;
1058}
1059
Guido van Rossuma9e20242007-03-08 00:43:48 +00001060
1061PyDoc_STRVAR(fileio_doc,
Ross Lagerwall59142db2011-10-31 20:34:46 +02001062"file(name: str[, mode: str][, opener: None]) -> file IO object\n"
Guido van Rossuma9e20242007-03-08 00:43:48 +00001063"\n"
Charles-François Natalidc3044c2012-01-09 22:40:02 +01001064"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 +01001065"writing, exclusive creation or appending. The file will be created if it\n"
1066"doesn't exist when opened for writing or appending; it will be truncated\n"
1067"when opened for writing. A `FileExistsError` will be raised if it already\n"
Charles-François Natalidc3044c2012-01-09 22:40:02 +01001068"exists when opened for creating. Opening a file for creating implies\n"
1069"writing so this mode behaves in a similar way to 'w'.Add a '+' to the mode\n"
1070"to allow simultaneous reading and writing. A custom opener can be used by\n"
1071"passing a callable as *opener*. The underlying file descriptor for the file\n"
Ross Lagerwall59142db2011-10-31 20:34:46 +02001072"object is then obtained by calling opener with (*name*, *flags*).\n"
Charles-François Natalidc3044c2012-01-09 22:40:02 +01001073"*opener* must return an open file descriptor (passing os.open as *opener*\n"
1074"results in functionality similar to passing None).");
Guido van Rossuma9e20242007-03-08 00:43:48 +00001075
1076PyDoc_STRVAR(read_doc,
1077"read(size: int) -> bytes. read at most size bytes, returned as bytes.\n"
1078"\n"
1079"Only makes one system call, so less data may be returned than requested\n"
Guido van Rossum7165cb12007-07-10 06:54:34 +00001080"In non-blocking mode, returns None if no data is available.\n"
1081"On end-of-file, returns ''.");
1082
1083PyDoc_STRVAR(readall_doc,
1084"readall() -> bytes. read all data from the file, returned as bytes.\n"
1085"\n"
1086"In non-blocking mode, returns as much as is immediately available,\n"
1087"or None if no data is available. On end-of-file, returns ''.");
Guido van Rossuma9e20242007-03-08 00:43:48 +00001088
1089PyDoc_STRVAR(write_doc,
1090"write(b: bytes) -> int. Write bytes b to file, return number written.\n"
1091"\n"
1092"Only makes one system call, so not all of the data may be written.\n"
1093"The number of bytes actually written is returned.");
1094
1095PyDoc_STRVAR(fileno_doc,
1096"fileno() -> int. \"file descriptor\".\n"
1097"\n"
1098"This is needed for lower-level file interfaces, such the fcntl module.");
1099
1100PyDoc_STRVAR(seek_doc,
1101"seek(offset: int[, whence: int]) -> None. Move to new file position.\n"
1102"\n"
1103"Argument offset is a byte count. Optional argument whence defaults to\n"
1104"0 (offset from start of file, offset should be >= 0); other values are 1\n"
1105"(move relative to current position, positive or negative), and 2 (move\n"
1106"relative to end of file, usually negative, although many platforms allow\n"
1107"seeking beyond the end of a file)."
1108"\n"
1109"Note that not all file objects are seekable.");
1110
Thomas Hellerc6a55ee2007-07-11 12:45:46 +00001111#ifdef HAVE_FTRUNCATE
Guido van Rossuma9e20242007-03-08 00:43:48 +00001112PyDoc_STRVAR(truncate_doc,
Antoine Pitrouae4b4722010-05-05 16:31:07 +00001113"truncate([size: int]) -> None. Truncate the file to at most size bytes.\n"
Guido van Rossuma9e20242007-03-08 00:43:48 +00001114"\n"
Alexandre Vassalotti77250f42008-05-06 19:48:38 +00001115"Size defaults to the current file position, as returned by tell()."
1116"The current file position is changed to the value of size.");
Thomas Hellerc6a55ee2007-07-11 12:45:46 +00001117#endif
Guido van Rossuma9e20242007-03-08 00:43:48 +00001118
1119PyDoc_STRVAR(tell_doc,
Antoine Pitrouae4b4722010-05-05 16:31:07 +00001120"tell() -> int. Current file position");
Guido van Rossuma9e20242007-03-08 00:43:48 +00001121
1122PyDoc_STRVAR(readinto_doc,
Benjamin Peterson9a8082f2009-03-05 00:55:56 +00001123"readinto() -> Same as RawIOBase.readinto().");
Guido van Rossuma9e20242007-03-08 00:43:48 +00001124
1125PyDoc_STRVAR(close_doc,
1126"close() -> None. Close the file.\n"
1127"\n"
1128"A closed file cannot be used for further I/O operations. close() may be\n"
1129"called more than once without error. Changes the fileno to -1.");
1130
1131PyDoc_STRVAR(isatty_doc,
1132"isatty() -> bool. True if the file is connected to a tty device.");
1133
Guido van Rossuma9e20242007-03-08 00:43:48 +00001134PyDoc_STRVAR(seekable_doc,
1135"seekable() -> bool. True if file supports random-access.");
1136
1137PyDoc_STRVAR(readable_doc,
1138"readable() -> bool. True if file was opened in a read mode.");
1139
1140PyDoc_STRVAR(writable_doc,
1141"writable() -> bool. True if file was opened in a write mode.");
1142
1143static PyMethodDef fileio_methods[] = {
Antoine Pitrouae4b4722010-05-05 16:31:07 +00001144 {"read", (PyCFunction)fileio_read, METH_VARARGS, read_doc},
1145 {"readall", (PyCFunction)fileio_readall, METH_NOARGS, readall_doc},
1146 {"readinto", (PyCFunction)fileio_readinto, METH_VARARGS, readinto_doc},
1147 {"write", (PyCFunction)fileio_write, METH_VARARGS, write_doc},
1148 {"seek", (PyCFunction)fileio_seek, METH_VARARGS, seek_doc},
1149 {"tell", (PyCFunction)fileio_tell, METH_VARARGS, tell_doc},
Thomas Hellerc6a55ee2007-07-11 12:45:46 +00001150#ifdef HAVE_FTRUNCATE
Antoine Pitrouae4b4722010-05-05 16:31:07 +00001151 {"truncate", (PyCFunction)fileio_truncate, METH_VARARGS, truncate_doc},
Thomas Hellerc6a55ee2007-07-11 12:45:46 +00001152#endif
Antoine Pitrouae4b4722010-05-05 16:31:07 +00001153 {"close", (PyCFunction)fileio_close, METH_NOARGS, close_doc},
1154 {"seekable", (PyCFunction)fileio_seekable, METH_NOARGS, seekable_doc},
1155 {"readable", (PyCFunction)fileio_readable, METH_NOARGS, readable_doc},
1156 {"writable", (PyCFunction)fileio_writable, METH_NOARGS, writable_doc},
1157 {"fileno", (PyCFunction)fileio_fileno, METH_NOARGS, fileno_doc},
1158 {"isatty", (PyCFunction)fileio_isatty, METH_NOARGS, isatty_doc},
Antoine Pitroue033e062010-10-29 10:38:18 +00001159 {"_dealloc_warn", (PyCFunction)fileio_dealloc_warn, METH_O, NULL},
Antoine Pitrou243757e2010-11-05 21:15:39 +00001160 {"__getstate__", (PyCFunction)fileio_getstate, METH_NOARGS, NULL},
Antoine Pitrouae4b4722010-05-05 16:31:07 +00001161 {NULL, NULL} /* sentinel */
Guido van Rossuma9e20242007-03-08 00:43:48 +00001162};
1163
Guido van Rossum53807da2007-04-10 19:01:47 +00001164/* 'closed' and 'mode' are attributes for backwards compatibility reasons. */
1165
Guido van Rossumb0428152007-04-08 17:44:42 +00001166static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +00001167get_closed(fileio *self, void *closure)
Guido van Rossumb0428152007-04-08 17:44:42 +00001168{
Antoine Pitrouae4b4722010-05-05 16:31:07 +00001169 return PyBool_FromLong((long)(self->fd < 0));
Guido van Rossum53807da2007-04-10 19:01:47 +00001170}
1171
1172static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +00001173get_closefd(fileio *self, void *closure)
Christian Heimesecc42a22008-11-05 19:30:32 +00001174{
Antoine Pitrouae4b4722010-05-05 16:31:07 +00001175 return PyBool_FromLong((long)(self->closefd));
Christian Heimesecc42a22008-11-05 19:30:32 +00001176}
1177
1178static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +00001179get_mode(fileio *self, void *closure)
Guido van Rossum53807da2007-04-10 19:01:47 +00001180{
Antoine Pitrouae4b4722010-05-05 16:31:07 +00001181 return PyUnicode_FromString(mode_string(self));
Guido van Rossumb0428152007-04-08 17:44:42 +00001182}
1183
1184static PyGetSetDef fileio_getsetlist[] = {
Antoine Pitrouae4b4722010-05-05 16:31:07 +00001185 {"closed", (getter)get_closed, NULL, "True if the file is closed"},
1186 {"closefd", (getter)get_closefd, NULL,
1187 "True if the file descriptor will be closed"},
1188 {"mode", (getter)get_mode, NULL, "String giving the file mode"},
1189 {NULL},
Guido van Rossumb0428152007-04-08 17:44:42 +00001190};
1191
Guido van Rossuma9e20242007-03-08 00:43:48 +00001192PyTypeObject PyFileIO_Type = {
Antoine Pitrouae4b4722010-05-05 16:31:07 +00001193 PyVarObject_HEAD_INIT(NULL, 0)
1194 "_io.FileIO",
1195 sizeof(fileio),
1196 0,
1197 (destructor)fileio_dealloc, /* tp_dealloc */
1198 0, /* tp_print */
1199 0, /* tp_getattr */
1200 0, /* tp_setattr */
1201 0, /* tp_reserved */
1202 (reprfunc)fileio_repr, /* tp_repr */
1203 0, /* tp_as_number */
1204 0, /* tp_as_sequence */
1205 0, /* tp_as_mapping */
1206 0, /* tp_hash */
1207 0, /* tp_call */
1208 0, /* tp_str */
1209 PyObject_GenericGetAttr, /* tp_getattro */
1210 0, /* tp_setattro */
1211 0, /* tp_as_buffer */
1212 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE
1213 | Py_TPFLAGS_HAVE_GC, /* tp_flags */
1214 fileio_doc, /* tp_doc */
1215 (traverseproc)fileio_traverse, /* tp_traverse */
1216 (inquiry)fileio_clear, /* tp_clear */
1217 0, /* tp_richcompare */
1218 offsetof(fileio, weakreflist), /* tp_weaklistoffset */
1219 0, /* tp_iter */
1220 0, /* tp_iternext */
1221 fileio_methods, /* tp_methods */
1222 0, /* tp_members */
1223 fileio_getsetlist, /* tp_getset */
1224 0, /* tp_base */
1225 0, /* tp_dict */
1226 0, /* tp_descr_get */
1227 0, /* tp_descr_set */
1228 offsetof(fileio, dict), /* tp_dictoffset */
1229 fileio_init, /* tp_init */
1230 PyType_GenericAlloc, /* tp_alloc */
1231 fileio_new, /* tp_new */
1232 PyObject_GC_Del, /* tp_free */
Guido van Rossuma9e20242007-03-08 00:43:48 +00001233};