blob: bb3e9b9f94a2c4775b356871622af1584bc6926a [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;
Antoine Pitroue93b63b2013-09-04 20:46:33 +020052 unsigned int appending : 1;
Antoine Pitrouae4b4722010-05-05 16:31:07 +000053 signed int seekable : 2; /* -1 means unknown */
54 unsigned int closefd : 1;
Antoine Pitrou796564c2013-07-30 19:59:21 +020055 char finalizing;
Antoine Pitroude687222014-06-29 20:07:28 -040056 unsigned int blksize;
Antoine Pitrouae4b4722010-05-05 16:31:07 +000057 PyObject *weakreflist;
58 PyObject *dict;
Benjamin Peterson680bf1a2009-06-12 02:07:12 +000059} fileio;
Guido van Rossuma9e20242007-03-08 00:43:48 +000060
Collin Winteraf334382007-03-08 21:46:15 +000061PyTypeObject PyFileIO_Type;
62
Victor Stinnerd9d04192013-11-06 23:50:10 +010063_Py_IDENTIFIER(name);
64
Guido van Rossuma9e20242007-03-08 00:43:48 +000065#define PyFileIO_Check(op) (PyObject_TypeCheck((op), &PyFileIO_Type))
66
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +000067int
68_PyFileIO_closed(PyObject *self)
69{
Antoine Pitrouae4b4722010-05-05 16:31:07 +000070 return ((fileio *)self)->fd < 0;
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +000071}
Antoine Pitrou08838b62009-01-21 00:55:13 +000072
Antoine Pitroue033e062010-10-29 10:38:18 +000073/* Because this can call arbitrary code, it shouldn't be called when
74 the refcount is 0 (that is, not directly from tp_dealloc unless
75 the refcount has been temporarily re-incremented). */
76static PyObject *
77fileio_dealloc_warn(fileio *self, PyObject *source)
78{
79 if (self->fd >= 0 && self->closefd) {
80 PyObject *exc, *val, *tb;
81 PyErr_Fetch(&exc, &val, &tb);
82 if (PyErr_WarnFormat(PyExc_ResourceWarning, 1,
83 "unclosed file %R", source)) {
84 /* Spurious errors can appear at shutdown */
85 if (PyErr_ExceptionMatches(PyExc_Warning))
86 PyErr_WriteUnraisable((PyObject *) self);
87 }
88 PyErr_Restore(exc, val, tb);
89 }
90 Py_RETURN_NONE;
91}
92
Antoine Pitrou7fb111b2009-03-04 11:14:01 +000093static PyObject *
94portable_lseek(int fd, PyObject *posobj, int whence);
95
Antoine Pitroua28fcfd2009-03-13 23:42:55 +000096static PyObject *portable_lseek(int fd, PyObject *posobj, int whence);
97
Kristján Valur Jónsson19288c22008-12-18 17:15:54 +000098/* Returns 0 on success, -1 with exception set on failure. */
Neal Norwitz88b44da2007-08-12 17:23:54 +000099static int
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000100internal_close(fileio *self)
Guido van Rossuma9e20242007-03-08 00:43:48 +0000101{
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000102 int err = 0;
103 int save_errno = 0;
104 if (self->fd >= 0) {
105 int fd = self->fd;
106 self->fd = -1;
107 /* fd is accessible and someone else may have closed it */
108 if (_PyVerify_fd(fd)) {
109 Py_BEGIN_ALLOW_THREADS
110 err = close(fd);
111 if (err < 0)
112 save_errno = errno;
113 Py_END_ALLOW_THREADS
114 } else {
115 save_errno = errno;
116 err = -1;
117 }
118 }
119 if (err < 0) {
120 errno = save_errno;
121 PyErr_SetFromErrno(PyExc_IOError);
122 return -1;
123 }
124 return 0;
Neal Norwitz88b44da2007-08-12 17:23:54 +0000125}
126
127static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000128fileio_close(fileio *self)
Neal Norwitz88b44da2007-08-12 17:23:54 +0000129{
Serhiy Storchakaa3712a92015-02-21 00:35:09 +0200130 PyObject *res;
131 PyObject *exc, *val, *tb;
132 int rc;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +0200133 _Py_IDENTIFIER(close);
Serhiy Storchakaa3712a92015-02-21 00:35:09 +0200134 res = _PyObject_CallMethodId((PyObject*)&PyRawIOBase_Type,
135 &PyId_close, "O", self);
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000136 if (!self->closefd) {
137 self->fd = -1;
Serhiy Storchakaa3712a92015-02-21 00:35:09 +0200138 return res;
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000139 }
Serhiy Storchakaa3712a92015-02-21 00:35:09 +0200140 if (res == NULL)
141 PyErr_Fetch(&exc, &val, &tb);
Antoine Pitrou796564c2013-07-30 19:59:21 +0200142 if (self->finalizing) {
Antoine Pitroue033e062010-10-29 10:38:18 +0000143 PyObject *r = fileio_dealloc_warn(self, (PyObject *) self);
144 if (r)
145 Py_DECREF(r);
146 else
147 PyErr_Clear();
148 }
Serhiy Storchakaa3712a92015-02-21 00:35:09 +0200149 rc = internal_close(self);
150 if (res == NULL)
151 _PyErr_ChainExceptions(exc, val, tb);
152 if (rc < 0)
153 Py_CLEAR(res);
154 return res;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000155}
156
157static PyObject *
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000158fileio_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
Guido van Rossuma9e20242007-03-08 00:43:48 +0000159{
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000160 fileio *self;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000161
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000162 assert(type != NULL && type->tp_alloc != NULL);
Guido van Rossuma9e20242007-03-08 00:43:48 +0000163
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000164 self = (fileio *) type->tp_alloc(type, 0);
165 if (self != NULL) {
166 self->fd = -1;
Charles-François Natalidc3044c2012-01-09 22:40:02 +0100167 self->created = 0;
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000168 self->readable = 0;
169 self->writable = 0;
Antoine Pitroue93b63b2013-09-04 20:46:33 +0200170 self->appending = 0;
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000171 self->seekable = -1;
Antoine Pitroude687222014-06-29 20:07:28 -0400172 self->blksize = 0;
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000173 self->closefd = 1;
174 self->weakreflist = NULL;
175 }
Guido van Rossuma9e20242007-03-08 00:43:48 +0000176
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000177 return (PyObject *) self;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000178}
179
Victor Stinnerdaf45552013-08-28 00:53:59 +0200180#ifdef O_CLOEXEC
181extern int _Py_open_cloexec_works;
182#endif
Guido van Rossuma9e20242007-03-08 00:43:48 +0000183
184static int
185fileio_init(PyObject *oself, PyObject *args, PyObject *kwds)
186{
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000187 fileio *self = (fileio *) oself;
Ross Lagerwall59142db2011-10-31 20:34:46 +0200188 static char *kwlist[] = {"file", "mode", "closefd", "opener", NULL};
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000189 const char *name = NULL;
Ross Lagerwall59142db2011-10-31 20:34:46 +0200190 PyObject *nameobj, *stringobj = NULL, *opener = Py_None;
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000191 char *mode = "r";
192 char *s;
Thomas Helleraf2be262007-07-12 11:03:13 +0000193#ifdef MS_WINDOWS
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000194 Py_UNICODE *widename = NULL;
Thomas Helleraf2be262007-07-12 11:03:13 +0000195#endif
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000196 int ret = 0;
Antoine Pitroue93b63b2013-09-04 20:46:33 +0200197 int rwa = 0, plus = 0;
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000198 int flags = 0;
199 int fd = -1;
200 int closefd = 1;
Hynek Schlawack9ed8b4e2012-06-21 20:20:25 +0200201 int fd_is_own = 0;
Victor Stinnerdaf45552013-08-28 00:53:59 +0200202#ifdef O_CLOEXEC
203 int *atomic_flag_works = &_Py_open_cloexec_works;
204#elif !defined(MS_WINDOWS)
205 int *atomic_flag_works = NULL;
206#endif
Steve Dowerf2f373f2015-02-21 08:44:05 -0800207 struct _Py_stat_struct fdfstat;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +0000208 int async_err = 0;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000209
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000210 assert(PyFileIO_Check(oself));
211 if (self->fd >= 0) {
Hynek Schlawack2cc71562012-05-25 10:05:53 +0200212 if (self->closefd) {
213 /* Have to close the existing file first. */
214 if (internal_close(self) < 0)
215 return -1;
216 }
217 else
218 self->fd = -1;
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000219 }
Guido van Rossuma9e20242007-03-08 00:43:48 +0000220
Ross Lagerwall59142db2011-10-31 20:34:46 +0200221 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|siO:fileio",
222 kwlist, &nameobj, &mode, &closefd,
223 &opener))
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000224 return -1;
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000225
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000226 if (PyFloat_Check(nameobj)) {
227 PyErr_SetString(PyExc_TypeError,
228 "integer argument expected, got float");
229 return -1;
230 }
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000231
Serhiy Storchaka78980432013-01-15 01:12:17 +0200232 fd = _PyLong_AsInt(nameobj);
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000233 if (fd < 0) {
234 if (!PyErr_Occurred()) {
235 PyErr_SetString(PyExc_ValueError,
Serhiy Storchaka3d2279f2015-04-10 16:08:43 +0300236 "negative file descriptor");
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000237 return -1;
238 }
239 PyErr_Clear();
240 }
Guido van Rossumb0428152007-04-08 17:44:42 +0000241
Hirokazu Yamamoto8223c242009-05-17 04:21:53 +0000242#ifdef MS_WINDOWS
Victor Stinnerfe9a8612011-09-29 23:19:04 +0200243 if (PyUnicode_Check(nameobj)) {
Antoine Pitrou13348842012-01-29 18:36:34 +0100244 int rv = _PyUnicode_HasNULChars(nameobj);
245 if (rv) {
246 if (rv != -1)
Serhiy Storchakad8a14472014-09-06 20:07:17 +0300247 PyErr_SetString(PyExc_ValueError, "embedded null character");
Antoine Pitrou13348842012-01-29 18:36:34 +0100248 return -1;
249 }
Victor Stinnerfe9a8612011-09-29 23:19:04 +0200250 widename = PyUnicode_AsUnicode(nameobj);
251 if (widename == NULL)
252 return -1;
253 } else
Guido van Rossuma9e20242007-03-08 00:43:48 +0000254#endif
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000255 if (fd < 0)
256 {
Antoine Pitrou13348842012-01-29 18:36:34 +0100257 if (!PyUnicode_FSConverter(nameobj, &stringobj)) {
258 return -1;
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000259 }
Antoine Pitrou13348842012-01-29 18:36:34 +0100260 name = PyBytes_AS_STRING(stringobj);
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000261 }
Guido van Rossuma9e20242007-03-08 00:43:48 +0000262
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000263 s = mode;
264 while (*s) {
265 switch (*s++) {
Charles-François Natalidc3044c2012-01-09 22:40:02 +0100266 case 'x':
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000267 if (rwa) {
268 bad_mode:
269 PyErr_SetString(PyExc_ValueError,
Charles-François Natalidc3044c2012-01-09 22:40:02 +0100270 "Must have exactly one of create/read/write/append "
Georg Brandl28928ae2010-10-21 13:45:52 +0000271 "mode and at most one plus");
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000272 goto error;
273 }
274 rwa = 1;
Charles-François Natalidc3044c2012-01-09 22:40:02 +0100275 self->created = 1;
276 self->writable = 1;
277 flags |= O_EXCL | O_CREAT;
278 break;
279 case 'r':
280 if (rwa)
281 goto bad_mode;
282 rwa = 1;
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000283 self->readable = 1;
284 break;
285 case 'w':
286 if (rwa)
287 goto bad_mode;
288 rwa = 1;
289 self->writable = 1;
290 flags |= O_CREAT | O_TRUNC;
291 break;
292 case 'a':
293 if (rwa)
294 goto bad_mode;
295 rwa = 1;
296 self->writable = 1;
Antoine Pitroue93b63b2013-09-04 20:46:33 +0200297 self->appending = 1;
298 flags |= O_APPEND | O_CREAT;
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000299 break;
300 case 'b':
301 break;
302 case '+':
303 if (plus)
304 goto bad_mode;
305 self->readable = self->writable = 1;
306 plus = 1;
307 break;
308 default:
309 PyErr_Format(PyExc_ValueError,
310 "invalid mode: %.200s", mode);
311 goto error;
312 }
313 }
Guido van Rossuma9e20242007-03-08 00:43:48 +0000314
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000315 if (!rwa)
316 goto bad_mode;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000317
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000318 if (self->readable && self->writable)
319 flags |= O_RDWR;
320 else if (self->readable)
321 flags |= O_RDONLY;
322 else
323 flags |= O_WRONLY;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000324
325#ifdef O_BINARY
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000326 flags |= O_BINARY;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000327#endif
328
Victor Stinnerdaf45552013-08-28 00:53:59 +0200329#ifdef MS_WINDOWS
330 flags |= O_NOINHERIT;
331#elif defined(O_CLOEXEC)
332 flags |= O_CLOEXEC;
333#endif
Walter Dörwald0e411482007-06-06 16:55:38 +0000334
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000335 if (fd >= 0) {
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000336 self->fd = fd;
337 self->closefd = closefd;
338 }
339 else {
340 self->closefd = 1;
341 if (!closefd) {
342 PyErr_SetString(PyExc_ValueError,
343 "Cannot use closefd=False with file name");
344 goto error;
345 }
Guido van Rossum2dced8b2007-10-30 17:27:30 +0000346
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000347 errno = 0;
Ross Lagerwall59142db2011-10-31 20:34:46 +0200348 if (opener == Py_None) {
Charles-François Natali6e6c59b2015-02-07 13:27:50 +0000349 do {
350 Py_BEGIN_ALLOW_THREADS
Thomas Helleraf2be262007-07-12 11:03:13 +0000351#ifdef MS_WINDOWS
Charles-François Natali6e6c59b2015-02-07 13:27:50 +0000352 if (widename != NULL)
353 self->fd = _wopen(widename, flags, 0666);
354 else
Thomas Helleraf2be262007-07-12 11:03:13 +0000355#endif
Charles-François Natali6e6c59b2015-02-07 13:27:50 +0000356 self->fd = open(name, flags, 0666);
Charles-François Natali6e6c59b2015-02-07 13:27:50 +0000357 Py_END_ALLOW_THREADS
358 } while (self->fd < 0 && errno == EINTR &&
359 !(async_err = PyErr_CheckSignals()));
Victor Stinner9672da72015-03-04 18:40:10 +0100360
361 if (async_err)
362 goto error;
Victor Stinnerdaf45552013-08-28 00:53:59 +0200363 }
364 else {
365 PyObject *fdobj;
366
367#ifndef MS_WINDOWS
368 /* the opener may clear the atomic flag */
369 atomic_flag_works = NULL;
370#endif
371
372 fdobj = PyObject_CallFunction(opener, "Oi", nameobj, flags);
Ross Lagerwall59142db2011-10-31 20:34:46 +0200373 if (fdobj == NULL)
374 goto error;
375 if (!PyLong_Check(fdobj)) {
376 Py_DECREF(fdobj);
377 PyErr_SetString(PyExc_TypeError,
378 "expected integer from opener");
379 goto error;
380 }
381
Serhiy Storchaka78980432013-01-15 01:12:17 +0200382 self->fd = _PyLong_AsInt(fdobj);
Ross Lagerwall59142db2011-10-31 20:34:46 +0200383 Py_DECREF(fdobj);
384 if (self->fd == -1) {
385 goto error;
386 }
387 }
388
Hynek Schlawack7f59fd72012-06-22 09:32:22 +0200389 fd_is_own = 1;
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000390 if (self->fd < 0) {
Victor Stinner9672da72015-03-04 18:40:10 +0100391 PyErr_SetFromErrnoWithFilenameObject(PyExc_OSError, nameobj);
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000392 goto error;
393 }
Victor Stinnerdaf45552013-08-28 00:53:59 +0200394
395#ifndef MS_WINDOWS
396 if (_Py_set_inheritable(self->fd, 0, atomic_flag_works) < 0)
397 goto error;
398#endif
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000399 }
Antoine Pitroude687222014-06-29 20:07:28 -0400400
401 self->blksize = DEFAULT_BUFFER_SIZE;
Victor Stinnere134a7f2015-03-30 10:09:31 +0200402 if (_Py_fstat(self->fd, &fdfstat) < 0)
Antoine Pitrou9235b252012-07-06 18:48:24 +0200403 goto error;
Antoine Pitroude687222014-06-29 20:07:28 -0400404#if defined(S_ISDIR) && defined(EISDIR)
405 /* On Unix, open will succeed for directories.
406 In Python, there should be no file objects referring to
407 directories, so we need a check. */
408 if (S_ISDIR(fdfstat.st_mode)) {
409 errno = EISDIR;
410 PyErr_SetFromErrnoWithFilenameObject(PyExc_IOError, nameobj);
411 goto error;
412 }
413#endif /* defined(S_ISDIR) */
414#ifdef HAVE_STRUCT_STAT_ST_BLKSIZE
415 if (fdfstat.st_blksize > 1)
416 self->blksize = fdfstat.st_blksize;
417#endif /* HAVE_STRUCT_STAT_ST_BLKSIZE */
Guido van Rossuma9e20242007-03-08 00:43:48 +0000418
Victor Stinner89e34362011-01-07 18:47:22 +0000419#if defined(MS_WINDOWS) || defined(__CYGWIN__)
420 /* don't translate newlines (\r\n <=> \n) */
421 _setmode(self->fd, O_BINARY);
422#endif
423
Victor Stinnerd9d04192013-11-06 23:50:10 +0100424 if (_PyObject_SetAttrId((PyObject *)self, &PyId_name, nameobj) < 0)
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000425 goto error;
Antoine Pitrou08838b62009-01-21 00:55:13 +0000426
Antoine Pitroue93b63b2013-09-04 20:46:33 +0200427 if (self->appending) {
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000428 /* For consistent behaviour, we explicitly seek to the
429 end of file (otherwise, it might be done only on the
430 first write()). */
431 PyObject *pos = portable_lseek(self->fd, NULL, 2);
Hynek Schlawack9ed8b4e2012-06-21 20:20:25 +0200432 if (pos == NULL)
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000433 goto error;
434 Py_DECREF(pos);
435 }
Antoine Pitrou7fb111b2009-03-04 11:14:01 +0000436
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000437 goto done;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000438
439 error:
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000440 ret = -1;
Hynek Schlawack9ed8b4e2012-06-21 20:20:25 +0200441 if (!fd_is_own)
442 self->fd = -1;
Benjamin Petersonbbb04122010-10-30 23:16:28 +0000443 if (self->fd >= 0)
444 internal_close(self);
Guido van Rossum53807da2007-04-10 19:01:47 +0000445
Guido van Rossuma9e20242007-03-08 00:43:48 +0000446 done:
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000447 Py_CLEAR(stringobj);
448 return ret;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000449}
450
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000451static int
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000452fileio_traverse(fileio *self, visitproc visit, void *arg)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000453{
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000454 Py_VISIT(self->dict);
455 return 0;
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000456}
457
458static int
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000459fileio_clear(fileio *self)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000460{
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000461 Py_CLEAR(self->dict);
462 return 0;
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000463}
464
Guido van Rossuma9e20242007-03-08 00:43:48 +0000465static void
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000466fileio_dealloc(fileio *self)
Guido van Rossuma9e20242007-03-08 00:43:48 +0000467{
Antoine Pitrou796564c2013-07-30 19:59:21 +0200468 self->finalizing = 1;
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000469 if (_PyIOBase_finalize((PyObject *) self) < 0)
470 return;
471 _PyObject_GC_UNTRACK(self);
472 if (self->weakreflist != NULL)
473 PyObject_ClearWeakRefs((PyObject *) self);
474 Py_CLEAR(self->dict);
475 Py_TYPE(self)->tp_free((PyObject *)self);
Guido van Rossuma9e20242007-03-08 00:43:48 +0000476}
477
478static PyObject *
479err_closed(void)
480{
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000481 PyErr_SetString(PyExc_ValueError, "I/O operation on closed file");
482 return NULL;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000483}
484
485static PyObject *
Guido van Rossum53807da2007-04-10 19:01:47 +0000486err_mode(char *action)
487{
Antoine Pitrou712cb732013-12-21 15:51:54 +0100488 _PyIO_State *state = IO_STATE();
489 if (state != NULL)
490 PyErr_Format(state->unsupported_operation,
491 "File not open for %s", action);
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000492 return NULL;
Guido van Rossum53807da2007-04-10 19:01:47 +0000493}
494
495static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000496fileio_fileno(fileio *self)
Guido van Rossuma9e20242007-03-08 00:43:48 +0000497{
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000498 if (self->fd < 0)
499 return err_closed();
500 return PyLong_FromLong((long) self->fd);
Guido van Rossuma9e20242007-03-08 00:43:48 +0000501}
502
503static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000504fileio_readable(fileio *self)
Guido van Rossuma9e20242007-03-08 00:43:48 +0000505{
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000506 if (self->fd < 0)
507 return err_closed();
508 return PyBool_FromLong((long) self->readable);
Guido van Rossuma9e20242007-03-08 00:43:48 +0000509}
510
511static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000512fileio_writable(fileio *self)
Guido van Rossuma9e20242007-03-08 00:43:48 +0000513{
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000514 if (self->fd < 0)
515 return err_closed();
516 return PyBool_FromLong((long) self->writable);
Guido van Rossuma9e20242007-03-08 00:43:48 +0000517}
518
519static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000520fileio_seekable(fileio *self)
Guido van Rossuma9e20242007-03-08 00:43:48 +0000521{
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000522 if (self->fd < 0)
523 return err_closed();
524 if (self->seekable < 0) {
525 PyObject *pos = portable_lseek(self->fd, NULL, SEEK_CUR);
526 if (pos == NULL) {
527 PyErr_Clear();
528 self->seekable = 0;
529 } else {
530 Py_DECREF(pos);
531 self->seekable = 1;
532 }
533 }
534 return PyBool_FromLong((long) self->seekable);
Guido van Rossuma9e20242007-03-08 00:43:48 +0000535}
536
537static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000538fileio_readinto(fileio *self, PyObject *args)
Guido van Rossuma9e20242007-03-08 00:43:48 +0000539{
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000540 Py_buffer pbuf;
Victor Stinner66aab0c2015-03-19 22:53:20 +0100541 Py_ssize_t n;
542 int err;
Guido van Rossum53807da2007-04-10 19:01:47 +0000543
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000544 if (self->fd < 0)
545 return err_closed();
546 if (!self->readable)
547 return err_mode("reading");
Guido van Rossum53807da2007-04-10 19:01:47 +0000548
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000549 if (!PyArg_ParseTuple(args, "w*", &pbuf))
550 return NULL;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000551
Victor Stinner66aab0c2015-03-19 22:53:20 +0100552 n = _Py_read(self->fd, pbuf.buf, pbuf.len);
553 /* copy errno because PyBuffer_Release() can indirectly modify it */
Antoine Pitrouc345ce12011-12-16 12:28:32 +0100554 err = errno;
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000555 PyBuffer_Release(&pbuf);
Victor Stinner66aab0c2015-03-19 22:53:20 +0100556
557 if (n == -1) {
558 if (err == EAGAIN) {
559 PyErr_Clear();
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000560 Py_RETURN_NONE;
Victor Stinner66aab0c2015-03-19 22:53:20 +0100561 }
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000562 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
Richard Oudkerkaf7260e2013-05-17 23:34:42 +0100569new_buffersize(fileio *self, size_t currentsize)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000570{
Antoine Pitroua3f44572012-04-17 13:50:58 +0200571 size_t addend;
Richard Oudkerkaf7260e2013-05-17 23:34:42 +0100572
Nadeem Vawdad41a98b2011-10-13 13:34:16 +0200573 /* Expand the buffer by an amount proportional to the current size,
Antoine Pitroua3f44572012-04-17 13:50:58 +0200574 giving us amortized linear-time behavior. For bigger sizes, use a
575 less-than-double growth factor to avoid excessive allocation. */
Richard Oudkerkaf7260e2013-05-17 23:34:42 +0100576 assert(currentsize <= PY_SSIZE_T_MAX);
Antoine Pitroua3f44572012-04-17 13:50:58 +0200577 if (currentsize > 65536)
578 addend = currentsize >> 3;
579 else
580 addend = 256 + currentsize;
581 if (addend < SMALLCHUNK)
582 /* Avoid tiny read() calls. */
583 addend = SMALLCHUNK;
584 return addend + currentsize;
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000585}
586
Guido van Rossum7165cb12007-07-10 06:54:34 +0000587static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000588fileio_readall(fileio *self)
Guido van Rossum7165cb12007-07-10 06:54:34 +0000589{
Victor Stinnere134a7f2015-03-30 10:09:31 +0200590 struct _Py_stat_struct status;
Victor Stinnera2a64772011-10-11 22:45:02 +0200591 Py_off_t pos, end;
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000592 PyObject *result;
Richard Oudkerkaf7260e2013-05-17 23:34:42 +0100593 Py_ssize_t bytes_read = 0;
Victor Stinner66aab0c2015-03-19 22:53:20 +0100594 Py_ssize_t n;
Richard Oudkerkaf7260e2013-05-17 23:34:42 +0100595 size_t bufsize;
Guido van Rossum7165cb12007-07-10 06:54:34 +0000596
Victor Stinnerb79f28c2011-05-25 22:09:03 +0200597 if (self->fd < 0)
598 return err_closed();
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000599 if (!_PyVerify_fd(self->fd))
600 return PyErr_SetFromErrno(PyExc_IOError);
Kristján Valur Jónssona8abe862009-03-24 15:27:42 +0000601
Victor Stinner14b9b112013-06-25 00:37:25 +0200602#ifdef MS_WINDOWS
Victor Stinnere9d44ccb2011-05-26 00:16:44 +0200603 pos = _lseeki64(self->fd, 0L, SEEK_CUR);
604#else
605 pos = lseek(self->fd, 0L, SEEK_CUR);
606#endif
Victor Stinnere134a7f2015-03-30 10:09:31 +0200607 if (_Py_fstat_noraise(self->fd, &status) == 0)
608 end = status.st_size;
Victor Stinnere9d44ccb2011-05-26 00:16:44 +0200609 else
Victor Stinnera2a64772011-10-11 22:45:02 +0200610 end = (Py_off_t)-1;
Christian Heimesa872de52008-12-05 08:26:55 +0000611
Richard Oudkerkaf7260e2013-05-17 23:34:42 +0100612 if (end > 0 && end >= pos && pos >= 0 && end - pos < PY_SSIZE_T_MAX) {
613 /* This is probably a real file, so we try to allocate a
614 buffer one byte larger than the rest of the file. If the
615 calculation is right then we should get EOF without having
616 to enlarge the buffer. */
617 bufsize = (size_t)(end - pos + 1);
618 } else {
619 bufsize = SMALLCHUNK;
620 }
621
622 result = PyBytes_FromStringAndSize(NULL, bufsize);
623 if (result == NULL)
624 return NULL;
625
626 while (1) {
627 if (bytes_read >= (Py_ssize_t)bufsize) {
628 bufsize = new_buffersize(self, bytes_read);
629 if (bufsize > PY_SSIZE_T_MAX || bufsize <= 0) {
630 PyErr_SetString(PyExc_OverflowError,
631 "unbounded read returned more bytes "
Serhiy Storchakab817b772015-04-10 02:18:44 +0300632 "than a Python bytes object can hold");
Richard Oudkerkaf7260e2013-05-17 23:34:42 +0100633 Py_DECREF(result);
634 return NULL;
635 }
636
637 if (PyBytes_GET_SIZE(result) < (Py_ssize_t)bufsize) {
638 if (_PyBytes_Resize(&result, bufsize) < 0)
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000639 return NULL;
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000640 }
641 }
Victor Stinner9672da72015-03-04 18:40:10 +0100642
Victor Stinner66aab0c2015-03-19 22:53:20 +0100643 n = _Py_read(self->fd,
644 PyBytes_AS_STRING(result) + bytes_read,
645 bufsize - bytes_read);
Victor Stinner9672da72015-03-04 18:40:10 +0100646
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000647 if (n == 0)
648 break;
Victor Stinner66aab0c2015-03-19 22:53:20 +0100649 if (n == -1) {
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000650 if (errno == EAGAIN) {
Victor Stinner66aab0c2015-03-19 22:53:20 +0100651 PyErr_Clear();
Victor Stinnere10920f2014-07-02 22:59:31 +0200652 if (bytes_read > 0)
653 break;
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000654 Py_DECREF(result);
655 Py_RETURN_NONE;
656 }
657 Py_DECREF(result);
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000658 return NULL;
659 }
Richard Oudkerkaf7260e2013-05-17 23:34:42 +0100660 bytes_read += n;
Victor Stinnere9d44ccb2011-05-26 00:16:44 +0200661 pos += n;
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000662 }
Guido van Rossum7165cb12007-07-10 06:54:34 +0000663
Richard Oudkerkaf7260e2013-05-17 23:34:42 +0100664 if (PyBytes_GET_SIZE(result) > bytes_read) {
665 if (_PyBytes_Resize(&result, bytes_read) < 0)
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000666 return NULL;
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000667 }
668 return result;
Guido van Rossum7165cb12007-07-10 06:54:34 +0000669}
670
Guido van Rossuma9e20242007-03-08 00:43:48 +0000671static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000672fileio_read(fileio *self, PyObject *args)
Guido van Rossuma9e20242007-03-08 00:43:48 +0000673{
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000674 char *ptr;
675 Py_ssize_t n;
676 Py_ssize_t size = -1;
677 PyObject *bytes;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000678
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000679 if (self->fd < 0)
680 return err_closed();
681 if (!self->readable)
682 return err_mode("reading");
Guido van Rossuma9e20242007-03-08 00:43:48 +0000683
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000684 if (!PyArg_ParseTuple(args, "|O&", &_PyIO_ConvertSsize_t, &size))
685 return NULL;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000686
Victor Stinner66aab0c2015-03-19 22:53:20 +0100687 if (size < 0)
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000688 return fileio_readall(self);
Guido van Rossumc2f93dc2007-05-24 00:50:02 +0000689
Victor Stinner14b9b112013-06-25 00:37:25 +0200690#ifdef MS_WINDOWS
Victor Stinner66aab0c2015-03-19 22:53:20 +0100691 /* On Windows, the count parameter of read() is an int */
Victor Stinnerc655a722011-07-05 11:31:49 +0200692 if (size > INT_MAX)
693 size = INT_MAX;
694#endif
Victor Stinner66aab0c2015-03-19 22:53:20 +0100695
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000696 bytes = PyBytes_FromStringAndSize(NULL, size);
697 if (bytes == NULL)
698 return NULL;
699 ptr = PyBytes_AS_STRING(bytes);
Guido van Rossuma9e20242007-03-08 00:43:48 +0000700
Victor Stinner66aab0c2015-03-19 22:53:20 +0100701 n = _Py_read(self->fd, ptr, size);
702 if (n == -1) {
703 /* copy errno because Py_DECREF() can indirectly modify it */
Antoine Pitrouc345ce12011-12-16 12:28:32 +0100704 int err = errno;
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000705 Py_DECREF(bytes);
Victor Stinner66aab0c2015-03-19 22:53:20 +0100706 if (err == EAGAIN) {
707 PyErr_Clear();
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000708 Py_RETURN_NONE;
Victor Stinner66aab0c2015-03-19 22:53:20 +0100709 }
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000710 return NULL;
711 }
Guido van Rossuma9e20242007-03-08 00:43:48 +0000712
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000713 if (n != size) {
714 if (_PyBytes_Resize(&bytes, n) < 0) {
Victor Stinner85c761d2013-07-16 21:36:02 +0200715 Py_CLEAR(bytes);
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000716 return NULL;
717 }
718 }
Guido van Rossuma9e20242007-03-08 00:43:48 +0000719
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000720 return (PyObject *) bytes;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000721}
722
723static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000724fileio_write(fileio *self, PyObject *args)
Guido van Rossuma9e20242007-03-08 00:43:48 +0000725{
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000726 Py_buffer pbuf;
Victor Stinner66aab0c2015-03-19 22:53:20 +0100727 Py_ssize_t n;
728 int err;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000729
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000730 if (self->fd < 0)
731 return err_closed();
732 if (!self->writable)
733 return err_mode("writing");
Guido van Rossum53807da2007-04-10 19:01:47 +0000734
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000735 if (!PyArg_ParseTuple(args, "y*", &pbuf))
736 return NULL;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000737
Victor Stinner66aab0c2015-03-19 22:53:20 +0100738 n = _Py_write(self->fd, pbuf.buf, pbuf.len);
739 /* copy errno because PyBuffer_Release() can indirectly modify it */
Antoine Pitrouc345ce12011-12-16 12:28:32 +0100740 err = errno;
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000741 PyBuffer_Release(&pbuf);
Martin v. Löwis423be952008-08-13 15:53:07 +0000742
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000743 if (n < 0) {
Victor Stinner66aab0c2015-03-19 22:53:20 +0100744 if (err == EAGAIN) {
745 PyErr_Clear();
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000746 Py_RETURN_NONE;
Victor Stinner66aab0c2015-03-19 22:53:20 +0100747 }
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000748 return NULL;
749 }
Guido van Rossuma9e20242007-03-08 00:43:48 +0000750
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000751 return PyLong_FromSsize_t(n);
Guido van Rossuma9e20242007-03-08 00:43:48 +0000752}
753
Guido van Rossum53807da2007-04-10 19:01:47 +0000754/* XXX Windows support below is likely incomplete */
755
Guido van Rossum53807da2007-04-10 19:01:47 +0000756/* Cribbed from posix_lseek() */
757static PyObject *
758portable_lseek(int fd, PyObject *posobj, int whence)
759{
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000760 Py_off_t pos, res;
Guido van Rossum53807da2007-04-10 19:01:47 +0000761
762#ifdef SEEK_SET
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000763 /* Turn 0, 1, 2 into SEEK_{SET,CUR,END} */
764 switch (whence) {
Guido van Rossum53807da2007-04-10 19:01:47 +0000765#if SEEK_SET != 0
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000766 case 0: whence = SEEK_SET; break;
Guido van Rossum53807da2007-04-10 19:01:47 +0000767#endif
768#if SEEK_CUR != 1
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000769 case 1: whence = SEEK_CUR; break;
Guido van Rossum53807da2007-04-10 19:01:47 +0000770#endif
Antoine Pitrou4f7945f2009-01-20 11:42:11 +0000771#if SEEK_END != 2
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000772 case 2: whence = SEEK_END; break;
Guido van Rossum53807da2007-04-10 19:01:47 +0000773#endif
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000774 }
Guido van Rossum53807da2007-04-10 19:01:47 +0000775#endif /* SEEK_SET */
776
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000777 if (posobj == NULL)
778 pos = 0;
779 else {
780 if(PyFloat_Check(posobj)) {
781 PyErr_SetString(PyExc_TypeError, "an integer is required");
782 return NULL;
783 }
Alexandre Vassalotti77250f42008-05-06 19:48:38 +0000784#if defined(HAVE_LARGEFILE_SUPPORT)
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000785 pos = PyLong_AsLongLong(posobj);
Guido van Rossum53807da2007-04-10 19:01:47 +0000786#else
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000787 pos = PyLong_AsLong(posobj);
Guido van Rossum53807da2007-04-10 19:01:47 +0000788#endif
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000789 if (PyErr_Occurred())
790 return NULL;
791 }
Guido van Rossum53807da2007-04-10 19:01:47 +0000792
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000793 if (_PyVerify_fd(fd)) {
794 Py_BEGIN_ALLOW_THREADS
Victor Stinner14b9b112013-06-25 00:37:25 +0200795#ifdef MS_WINDOWS
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000796 res = _lseeki64(fd, pos, whence);
Guido van Rossum53807da2007-04-10 19:01:47 +0000797#else
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000798 res = lseek(fd, pos, whence);
Guido van Rossum53807da2007-04-10 19:01:47 +0000799#endif
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000800 Py_END_ALLOW_THREADS
801 } else
802 res = -1;
803 if (res < 0)
804 return PyErr_SetFromErrno(PyExc_IOError);
Guido van Rossum53807da2007-04-10 19:01:47 +0000805
Alexandre Vassalotti77250f42008-05-06 19:48:38 +0000806#if defined(HAVE_LARGEFILE_SUPPORT)
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000807 return PyLong_FromLongLong(res);
Alexandre Vassalotti77250f42008-05-06 19:48:38 +0000808#else
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000809 return PyLong_FromLong(res);
Guido van Rossum53807da2007-04-10 19:01:47 +0000810#endif
811}
812
Guido van Rossuma9e20242007-03-08 00:43:48 +0000813static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000814fileio_seek(fileio *self, PyObject *args)
Guido van Rossuma9e20242007-03-08 00:43:48 +0000815{
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000816 PyObject *posobj;
817 int whence = 0;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000818
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000819 if (self->fd < 0)
820 return err_closed();
Guido van Rossuma9e20242007-03-08 00:43:48 +0000821
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000822 if (!PyArg_ParseTuple(args, "O|i", &posobj, &whence))
823 return NULL;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000824
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000825 return portable_lseek(self->fd, posobj, whence);
Guido van Rossuma9e20242007-03-08 00:43:48 +0000826}
827
828static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000829fileio_tell(fileio *self, PyObject *args)
Guido van Rossuma9e20242007-03-08 00:43:48 +0000830{
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000831 if (self->fd < 0)
832 return err_closed();
Guido van Rossuma9e20242007-03-08 00:43:48 +0000833
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000834 return portable_lseek(self->fd, NULL, 1);
Guido van Rossuma9e20242007-03-08 00:43:48 +0000835}
836
Thomas Hellerc6a55ee2007-07-11 12:45:46 +0000837#ifdef HAVE_FTRUNCATE
Guido van Rossuma9e20242007-03-08 00:43:48 +0000838static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000839fileio_truncate(fileio *self, PyObject *args)
Guido van Rossuma9e20242007-03-08 00:43:48 +0000840{
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000841 PyObject *posobj = NULL; /* the new size wanted by the user */
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000842 Py_off_t pos;
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000843 int ret;
844 int fd;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000845
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000846 fd = self->fd;
847 if (fd < 0)
848 return err_closed();
849 if (!self->writable)
850 return err_mode("writing");
Guido van Rossuma9e20242007-03-08 00:43:48 +0000851
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000852 if (!PyArg_ParseTuple(args, "|O", &posobj))
853 return NULL;
Guido van Rossum53807da2007-04-10 19:01:47 +0000854
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000855 if (posobj == Py_None || posobj == NULL) {
856 /* Get the current position. */
857 posobj = portable_lseek(fd, NULL, 1);
858 if (posobj == NULL)
859 return NULL;
860 }
861 else {
862 Py_INCREF(posobj);
863 }
Guido van Rossum53807da2007-04-10 19:01:47 +0000864
Antoine Pitrou905a2ff2010-01-31 22:47:27 +0000865#if defined(HAVE_LARGEFILE_SUPPORT)
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000866 pos = PyLong_AsLongLong(posobj);
Antoine Pitrou905a2ff2010-01-31 22:47:27 +0000867#else
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000868 pos = PyLong_AsLong(posobj);
Antoine Pitrou905a2ff2010-01-31 22:47:27 +0000869#endif
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000870 if (PyErr_Occurred()){
871 Py_DECREF(posobj);
872 return NULL;
873 }
Antoine Pitrou905a2ff2010-01-31 22:47:27 +0000874
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000875 Py_BEGIN_ALLOW_THREADS
876 errno = 0;
Steve Dowerfe0a41a2015-03-20 19:50:46 -0700877#ifdef MS_WINDOWS
878 ret = _chsize_s(fd, pos);
879#else
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000880 ret = ftruncate(fd, pos);
Steve Dowerfe0a41a2015-03-20 19:50:46 -0700881#endif
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000882 Py_END_ALLOW_THREADS
Antoine Pitrou905a2ff2010-01-31 22:47:27 +0000883
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000884 if (ret != 0) {
885 Py_DECREF(posobj);
886 PyErr_SetFromErrno(PyExc_IOError);
887 return NULL;
888 }
Guido van Rossuma9e20242007-03-08 00:43:48 +0000889
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000890 return posobj;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000891}
Antoine Pitrou905a2ff2010-01-31 22:47:27 +0000892#endif /* HAVE_FTRUNCATE */
Guido van Rossum53807da2007-04-10 19:01:47 +0000893
894static char *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000895mode_string(fileio *self)
Guido van Rossum53807da2007-04-10 19:01:47 +0000896{
Charles-François Natalidc3044c2012-01-09 22:40:02 +0100897 if (self->created) {
898 if (self->readable)
899 return "xb+";
900 else
901 return "xb";
902 }
Antoine Pitroue93b63b2013-09-04 20:46:33 +0200903 if (self->appending) {
904 if (self->readable)
905 return "ab+";
906 else
907 return "ab";
908 }
909 else if (self->readable) {
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000910 if (self->writable)
911 return "rb+";
912 else
913 return "rb";
914 }
915 else
916 return "wb";
Guido van Rossum53807da2007-04-10 19:01:47 +0000917}
Guido van Rossuma9e20242007-03-08 00:43:48 +0000918
919static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000920fileio_repr(fileio *self)
Guido van Rossuma9e20242007-03-08 00:43:48 +0000921{
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000922 PyObject *nameobj, *res;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000923
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000924 if (self->fd < 0)
925 return PyUnicode_FromFormat("<_io.FileIO [closed]>");
Antoine Pitrou716c4442009-05-23 19:04:03 +0000926
Martin v. Löwis767046a2011-10-14 15:35:36 +0200927 nameobj = _PyObject_GetAttrId((PyObject *) self, &PyId_name);
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000928 if (nameobj == NULL) {
929 if (PyErr_ExceptionMatches(PyExc_AttributeError))
930 PyErr_Clear();
931 else
932 return NULL;
Robert Collins933430a2014-10-18 13:32:43 +1300933 res = PyUnicode_FromFormat(
Serhiy Storchaka4954f9f2014-12-02 23:39:56 +0200934 "<_io.FileIO fd=%d mode='%s' closefd=%s>",
935 self->fd, mode_string(self), self->closefd ? "True" : "False");
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000936 }
937 else {
Robert Collins933430a2014-10-18 13:32:43 +1300938 res = PyUnicode_FromFormat(
Serhiy Storchaka4954f9f2014-12-02 23:39:56 +0200939 "<_io.FileIO name=%R mode='%s' closefd=%s>",
940 nameobj, mode_string(self), self->closefd ? "True" : "False");
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000941 Py_DECREF(nameobj);
942 }
943 return res;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000944}
945
946static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000947fileio_isatty(fileio *self)
Guido van Rossuma9e20242007-03-08 00:43:48 +0000948{
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000949 long res;
Guido van Rossum53807da2007-04-10 19:01:47 +0000950
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000951 if (self->fd < 0)
952 return err_closed();
953 Py_BEGIN_ALLOW_THREADS
954 res = isatty(self->fd);
955 Py_END_ALLOW_THREADS
956 return PyBool_FromLong(res);
Guido van Rossuma9e20242007-03-08 00:43:48 +0000957}
958
Antoine Pitrou243757e2010-11-05 21:15:39 +0000959static PyObject *
960fileio_getstate(fileio *self)
961{
962 PyErr_Format(PyExc_TypeError,
963 "cannot serialize '%s' object", Py_TYPE(self)->tp_name);
964 return NULL;
965}
966
Guido van Rossuma9e20242007-03-08 00:43:48 +0000967
968PyDoc_STRVAR(fileio_doc,
Ross Lagerwall59142db2011-10-31 20:34:46 +0200969"file(name: str[, mode: str][, opener: None]) -> file IO object\n"
Guido van Rossuma9e20242007-03-08 00:43:48 +0000970"\n"
Serhiy Storchaka3d2279f2015-04-10 16:08:43 +0300971"Open a file. The mode can be 'r' (default), 'w', 'x' or 'a' for reading,\n"
Charles-François Natalid612de12012-01-14 11:51:00 +0100972"writing, exclusive creation or appending. The file will be created if it\n"
973"doesn't exist when opened for writing or appending; it will be truncated\n"
Serhiy Storchaka3d2279f2015-04-10 16:08:43 +0300974"when opened for writing. A FileExistsError will be raised if it already\n"
Charles-François Natalidc3044c2012-01-09 22:40:02 +0100975"exists when opened for creating. Opening a file for creating implies\n"
976"writing so this mode behaves in a similar way to 'w'.Add a '+' to the mode\n"
977"to allow simultaneous reading and writing. A custom opener can be used by\n"
978"passing a callable as *opener*. The underlying file descriptor for the file\n"
Ross Lagerwall59142db2011-10-31 20:34:46 +0200979"object is then obtained by calling opener with (*name*, *flags*).\n"
Charles-François Natalidc3044c2012-01-09 22:40:02 +0100980"*opener* must return an open file descriptor (passing os.open as *opener*\n"
981"results in functionality similar to passing None).");
Guido van Rossuma9e20242007-03-08 00:43:48 +0000982
983PyDoc_STRVAR(read_doc,
984"read(size: int) -> bytes. read at most size bytes, returned as bytes.\n"
985"\n"
986"Only makes one system call, so less data may be returned than requested\n"
Guido van Rossum7165cb12007-07-10 06:54:34 +0000987"In non-blocking mode, returns None if no data is available.\n"
Serhiy Storchakab817b772015-04-10 02:18:44 +0300988"Return an empty bytes object at EOF.");
Guido van Rossum7165cb12007-07-10 06:54:34 +0000989
990PyDoc_STRVAR(readall_doc,
991"readall() -> bytes. read all data from the file, returned as bytes.\n"
992"\n"
993"In non-blocking mode, returns as much as is immediately available,\n"
Serhiy Storchakab817b772015-04-10 02:18:44 +0300994"or None if no data is available. Return an empty bytes object at EOF.");
Guido van Rossuma9e20242007-03-08 00:43:48 +0000995
996PyDoc_STRVAR(write_doc,
997"write(b: bytes) -> int. Write bytes b to file, return number written.\n"
998"\n"
999"Only makes one system call, so not all of the data may be written.\n"
Serhiy Storchaka3d2279f2015-04-10 16:08:43 +03001000"The number of bytes actually written is returned. In non-blocking mode,\n"
1001"returns None if the write would block."
1002);
Guido van Rossuma9e20242007-03-08 00:43:48 +00001003
1004PyDoc_STRVAR(fileno_doc,
Serhiy Storchaka3d2279f2015-04-10 16:08:43 +03001005"fileno() -> int. Return the underlying file descriptor (an integer).");
Guido van Rossuma9e20242007-03-08 00:43:48 +00001006
1007PyDoc_STRVAR(seek_doc,
Berker Peksagb87630c2014-09-24 12:43:29 +03001008"seek(offset: int[, whence: int]) -> int. Move to new file position and\n"
1009"return the file position.\n"
Guido van Rossuma9e20242007-03-08 00:43:48 +00001010"\n"
1011"Argument offset is a byte count. Optional argument whence defaults to\n"
Serhiy Storchaka3d2279f2015-04-10 16:08:43 +03001012"SEEK_SET or 0 (offset from start of file, offset should be >= 0); other values\n"
1013"are SEEK_CUR or 1 (move relative to current position, positive or negative),\n"
1014"and SEEK_END or 2 (move relative to end of file, usually negative, although\n"
1015"many platforms allow seeking beyond the end of a file).\n"
Guido van Rossuma9e20242007-03-08 00:43:48 +00001016"\n"
1017"Note that not all file objects are seekable.");
1018
Thomas Hellerc6a55ee2007-07-11 12:45:46 +00001019#ifdef HAVE_FTRUNCATE
Guido van Rossuma9e20242007-03-08 00:43:48 +00001020PyDoc_STRVAR(truncate_doc,
Berker Peksagb87630c2014-09-24 12:43:29 +03001021"truncate([size: int]) -> int. Truncate the file to at most size bytes\n"
1022"and return the truncated size.\n"
Guido van Rossuma9e20242007-03-08 00:43:48 +00001023"\n"
Berker Peksagb87630c2014-09-24 12:43:29 +03001024"Size defaults to the current file position, as returned by tell().\n"
Alexandre Vassalotti77250f42008-05-06 19:48:38 +00001025"The current file position is changed to the value of size.");
Thomas Hellerc6a55ee2007-07-11 12:45:46 +00001026#endif
Guido van Rossuma9e20242007-03-08 00:43:48 +00001027
1028PyDoc_STRVAR(tell_doc,
Serhiy Storchaka3d2279f2015-04-10 16:08:43 +03001029"tell() -> int. Current file position.\n"
1030"\n"
1031"Can raise OSError for non seekable files."
1032);
Guido van Rossuma9e20242007-03-08 00:43:48 +00001033
1034PyDoc_STRVAR(readinto_doc,
Benjamin Peterson9a8082f2009-03-05 00:55:56 +00001035"readinto() -> Same as RawIOBase.readinto().");
Guido van Rossuma9e20242007-03-08 00:43:48 +00001036
1037PyDoc_STRVAR(close_doc,
1038"close() -> None. Close the file.\n"
1039"\n"
1040"A closed file cannot be used for further I/O operations. close() may be\n"
Serhiy Storchaka3d2279f2015-04-10 16:08:43 +03001041"called more than once without error.");
Guido van Rossuma9e20242007-03-08 00:43:48 +00001042
1043PyDoc_STRVAR(isatty_doc,
Serhiy Storchaka3d2279f2015-04-10 16:08:43 +03001044"isatty() -> bool. True if the file is connected to a TTY device.");
Guido van Rossuma9e20242007-03-08 00:43:48 +00001045
Guido van Rossuma9e20242007-03-08 00:43:48 +00001046PyDoc_STRVAR(seekable_doc,
1047"seekable() -> bool. True if file supports random-access.");
1048
1049PyDoc_STRVAR(readable_doc,
1050"readable() -> bool. True if file was opened in a read mode.");
1051
1052PyDoc_STRVAR(writable_doc,
1053"writable() -> bool. True if file was opened in a write mode.");
1054
1055static PyMethodDef fileio_methods[] = {
Antoine Pitrouae4b4722010-05-05 16:31:07 +00001056 {"read", (PyCFunction)fileio_read, METH_VARARGS, read_doc},
1057 {"readall", (PyCFunction)fileio_readall, METH_NOARGS, readall_doc},
1058 {"readinto", (PyCFunction)fileio_readinto, METH_VARARGS, readinto_doc},
1059 {"write", (PyCFunction)fileio_write, METH_VARARGS, write_doc},
1060 {"seek", (PyCFunction)fileio_seek, METH_VARARGS, seek_doc},
1061 {"tell", (PyCFunction)fileio_tell, METH_VARARGS, tell_doc},
Thomas Hellerc6a55ee2007-07-11 12:45:46 +00001062#ifdef HAVE_FTRUNCATE
Antoine Pitrouae4b4722010-05-05 16:31:07 +00001063 {"truncate", (PyCFunction)fileio_truncate, METH_VARARGS, truncate_doc},
Thomas Hellerc6a55ee2007-07-11 12:45:46 +00001064#endif
Antoine Pitrouae4b4722010-05-05 16:31:07 +00001065 {"close", (PyCFunction)fileio_close, METH_NOARGS, close_doc},
1066 {"seekable", (PyCFunction)fileio_seekable, METH_NOARGS, seekable_doc},
1067 {"readable", (PyCFunction)fileio_readable, METH_NOARGS, readable_doc},
1068 {"writable", (PyCFunction)fileio_writable, METH_NOARGS, writable_doc},
1069 {"fileno", (PyCFunction)fileio_fileno, METH_NOARGS, fileno_doc},
1070 {"isatty", (PyCFunction)fileio_isatty, METH_NOARGS, isatty_doc},
Antoine Pitroue033e062010-10-29 10:38:18 +00001071 {"_dealloc_warn", (PyCFunction)fileio_dealloc_warn, METH_O, NULL},
Antoine Pitrou243757e2010-11-05 21:15:39 +00001072 {"__getstate__", (PyCFunction)fileio_getstate, METH_NOARGS, NULL},
Antoine Pitrouae4b4722010-05-05 16:31:07 +00001073 {NULL, NULL} /* sentinel */
Guido van Rossuma9e20242007-03-08 00:43:48 +00001074};
1075
Guido van Rossum53807da2007-04-10 19:01:47 +00001076/* 'closed' and 'mode' are attributes for backwards compatibility reasons. */
1077
Guido van Rossumb0428152007-04-08 17:44:42 +00001078static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +00001079get_closed(fileio *self, void *closure)
Guido van Rossumb0428152007-04-08 17:44:42 +00001080{
Antoine Pitrouae4b4722010-05-05 16:31:07 +00001081 return PyBool_FromLong((long)(self->fd < 0));
Guido van Rossum53807da2007-04-10 19:01:47 +00001082}
1083
1084static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +00001085get_closefd(fileio *self, void *closure)
Christian Heimesecc42a22008-11-05 19:30:32 +00001086{
Antoine Pitrouae4b4722010-05-05 16:31:07 +00001087 return PyBool_FromLong((long)(self->closefd));
Christian Heimesecc42a22008-11-05 19:30:32 +00001088}
1089
1090static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +00001091get_mode(fileio *self, void *closure)
Guido van Rossum53807da2007-04-10 19:01:47 +00001092{
Antoine Pitrouae4b4722010-05-05 16:31:07 +00001093 return PyUnicode_FromString(mode_string(self));
Guido van Rossumb0428152007-04-08 17:44:42 +00001094}
1095
1096static PyGetSetDef fileio_getsetlist[] = {
Antoine Pitrouae4b4722010-05-05 16:31:07 +00001097 {"closed", (getter)get_closed, NULL, "True if the file is closed"},
1098 {"closefd", (getter)get_closefd, NULL,
Serhiy Storchaka3d2279f2015-04-10 16:08:43 +03001099 "True if the file descriptor will be closed by close()."},
Antoine Pitrouae4b4722010-05-05 16:31:07 +00001100 {"mode", (getter)get_mode, NULL, "String giving the file mode"},
1101 {NULL},
Guido van Rossumb0428152007-04-08 17:44:42 +00001102};
1103
Antoine Pitrou796564c2013-07-30 19:59:21 +02001104static PyMemberDef fileio_members[] = {
Antoine Pitroude687222014-06-29 20:07:28 -04001105 {"_blksize", T_UINT, offsetof(fileio, blksize), 0},
Antoine Pitrou796564c2013-07-30 19:59:21 +02001106 {"_finalizing", T_BOOL, offsetof(fileio, finalizing), 0},
1107 {NULL}
1108};
1109
Guido van Rossuma9e20242007-03-08 00:43:48 +00001110PyTypeObject PyFileIO_Type = {
Antoine Pitrouae4b4722010-05-05 16:31:07 +00001111 PyVarObject_HEAD_INIT(NULL, 0)
1112 "_io.FileIO",
1113 sizeof(fileio),
1114 0,
1115 (destructor)fileio_dealloc, /* tp_dealloc */
1116 0, /* tp_print */
1117 0, /* tp_getattr */
1118 0, /* tp_setattr */
1119 0, /* tp_reserved */
1120 (reprfunc)fileio_repr, /* tp_repr */
1121 0, /* tp_as_number */
1122 0, /* tp_as_sequence */
1123 0, /* tp_as_mapping */
1124 0, /* tp_hash */
1125 0, /* tp_call */
1126 0, /* tp_str */
1127 PyObject_GenericGetAttr, /* tp_getattro */
1128 0, /* tp_setattro */
1129 0, /* tp_as_buffer */
1130 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE
Antoine Pitrou796564c2013-07-30 19:59:21 +02001131 | Py_TPFLAGS_HAVE_GC | Py_TPFLAGS_HAVE_FINALIZE, /* tp_flags */
Antoine Pitrouae4b4722010-05-05 16:31:07 +00001132 fileio_doc, /* tp_doc */
1133 (traverseproc)fileio_traverse, /* tp_traverse */
1134 (inquiry)fileio_clear, /* tp_clear */
1135 0, /* tp_richcompare */
1136 offsetof(fileio, weakreflist), /* tp_weaklistoffset */
1137 0, /* tp_iter */
1138 0, /* tp_iternext */
1139 fileio_methods, /* tp_methods */
Antoine Pitrou796564c2013-07-30 19:59:21 +02001140 fileio_members, /* tp_members */
Antoine Pitrouae4b4722010-05-05 16:31:07 +00001141 fileio_getsetlist, /* tp_getset */
1142 0, /* tp_base */
1143 0, /* tp_dict */
1144 0, /* tp_descr_get */
1145 0, /* tp_descr_set */
1146 offsetof(fileio, dict), /* tp_dictoffset */
1147 fileio_init, /* tp_init */
1148 PyType_GenericAlloc, /* tp_alloc */
1149 fileio_new, /* tp_new */
1150 PyObject_GC_Del, /* tp_free */
Antoine Pitrou796564c2013-07-30 19:59:21 +02001151 0, /* tp_is_gc */
1152 0, /* tp_bases */
1153 0, /* tp_mro */
1154 0, /* tp_cache */
1155 0, /* tp_subclasses */
1156 0, /* tp_weaklist */
1157 0, /* tp_del */
1158 0, /* tp_version_tag */
1159 0, /* tp_finalize */
Guido van Rossuma9e20242007-03-08 00:43:48 +00001160};