blob: 7fe245491bb481f711e0c369ba128f3f4c0d29c8 [file] [log] [blame]
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001/* Author: Daniel Stutzbach */
2
3#define PY_SSIZE_T_CLEAN
4#include "Python.h"
Andrew M. Kuchling4b81bc72010-02-22 23:12:00 +00005#ifdef HAVE_SYS_TYPES_H
Christian Heimes7f39c9f2008-01-25 12:18:43 +00006#include <sys/types.h>
Andrew M. Kuchling4b81bc72010-02-22 23:12:00 +00007#endif
8#ifdef HAVE_SYS_STAT_H
Christian Heimes7f39c9f2008-01-25 12:18:43 +00009#include <sys/stat.h>
Andrew M. Kuchling4b81bc72010-02-22 23:12:00 +000010#endif
11#ifdef HAVE_FCNTL_H
Christian Heimes7f39c9f2008-01-25 12:18:43 +000012#include <fcntl.h>
Andrew M. Kuchling4b81bc72010-02-22 23:12:00 +000013#endif
Christian Heimes7f39c9f2008-01-25 12:18:43 +000014#include <stddef.h> /* For offsetof */
Antoine Pitrou19690592009-06-12 20:14:08 +000015#include "_iomodule.h"
Christian Heimes7f39c9f2008-01-25 12:18:43 +000016
17/*
18 * Known likely problems:
19 *
20 * - Files larger then 2**32-1
21 * - Files with unicode filenames
22 * - Passing numbers greater than 2**32-1 when an integer is expected
23 * - Making it work on Windows and other oddball platforms
24 *
25 * To Do:
26 *
27 * - autoconfify header file inclusion
28 */
29
30#ifdef MS_WINDOWS
31/* can simulate truncate with Win32 API functions; see file_truncate */
32#define HAVE_FTRUNCATE
33#define WIN32_LEAN_AND_MEAN
34#include <windows.h>
35#endif
36
Antoine Pitrou19690592009-06-12 20:14:08 +000037#if BUFSIZ < (8*1024)
38#define SMALLCHUNK (8*1024)
39#elif (BUFSIZ >= (2 << 25))
40#error "unreasonable BUFSIZ > 64MB defined"
41#else
42#define SMALLCHUNK BUFSIZ
43#endif
44
Christian Heimes7f39c9f2008-01-25 12:18:43 +000045typedef struct {
Antoine Pitroub26dc462010-05-05 16:27:30 +000046 PyObject_HEAD
47 int fd;
48 unsigned int readable : 1;
49 unsigned int writable : 1;
50 signed int seekable : 2; /* -1 means unknown */
51 unsigned int closefd : 1;
52 PyObject *weakreflist;
53 PyObject *dict;
Antoine Pitrou19690592009-06-12 20:14:08 +000054} fileio;
Christian Heimes7f39c9f2008-01-25 12:18:43 +000055
56PyTypeObject PyFileIO_Type;
57
58#define PyFileIO_Check(op) (PyObject_TypeCheck((op), &PyFileIO_Type))
59
Antoine Pitrou19690592009-06-12 20:14:08 +000060int
61_PyFileIO_closed(PyObject *self)
62{
Antoine Pitroub26dc462010-05-05 16:27:30 +000063 return ((fileio *)self)->fd < 0;
Antoine Pitrou19690592009-06-12 20:14:08 +000064}
65
Antoine Pitroue741cc62009-01-21 00:45:36 +000066static PyObject *
67portable_lseek(int fd, PyObject *posobj, int whence);
68
Antoine Pitrou19690592009-06-12 20:14:08 +000069static PyObject *portable_lseek(int fd, PyObject *posobj, int whence);
70
71/* Returns 0 on success, -1 with exception set on failure. */
Christian Heimes7f39c9f2008-01-25 12:18:43 +000072static int
Antoine Pitrou19690592009-06-12 20:14:08 +000073internal_close(fileio *self)
Christian Heimes7f39c9f2008-01-25 12:18:43 +000074{
Antoine Pitroub26dc462010-05-05 16:27:30 +000075 int err = 0;
76 int save_errno = 0;
77 if (self->fd >= 0) {
78 int fd = self->fd;
79 self->fd = -1;
80 /* fd is accessible and someone else may have closed it */
81 if (_PyVerify_fd(fd)) {
82 Py_BEGIN_ALLOW_THREADS
83 err = close(fd);
84 if (err < 0)
85 save_errno = errno;
86 Py_END_ALLOW_THREADS
87 } else {
88 save_errno = errno;
89 err = -1;
90 }
91 }
92 if (err < 0) {
93 errno = save_errno;
94 PyErr_SetFromErrno(PyExc_IOError);
95 return -1;
96 }
97 return 0;
Christian Heimes7f39c9f2008-01-25 12:18:43 +000098}
99
100static PyObject *
Antoine Pitrou19690592009-06-12 20:14:08 +0000101fileio_close(fileio *self)
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000102{
Antoine Pitroub26dc462010-05-05 16:27:30 +0000103 if (!self->closefd) {
104 self->fd = -1;
105 Py_RETURN_NONE;
106 }
107 errno = internal_close(self);
108 if (errno < 0)
109 return NULL;
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000110
Antoine Pitroub26dc462010-05-05 16:27:30 +0000111 return PyObject_CallMethod((PyObject*)&PyRawIOBase_Type,
112 "close", "O", self);
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000113}
114
115static PyObject *
Antoine Pitrou19690592009-06-12 20:14:08 +0000116fileio_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000117{
Antoine Pitroub26dc462010-05-05 16:27:30 +0000118 fileio *self;
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000119
Antoine Pitroub26dc462010-05-05 16:27:30 +0000120 assert(type != NULL && type->tp_alloc != NULL);
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000121
Antoine Pitroub26dc462010-05-05 16:27:30 +0000122 self = (fileio *) type->tp_alloc(type, 0);
123 if (self != NULL) {
124 self->fd = -1;
125 self->readable = 0;
126 self->writable = 0;
127 self->seekable = -1;
128 self->closefd = 1;
129 self->weakreflist = NULL;
130 }
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000131
Antoine Pitroub26dc462010-05-05 16:27:30 +0000132 return (PyObject *) self;
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000133}
134
135/* On Unix, open will succeed for directories.
136 In Python, there should be no file objects referring to
137 directories, so we need a check. */
138
139static int
Antoine Pitrouc2ec9922012-07-06 18:48:24 +0200140dircheck(fileio* self, PyObject *nameobj)
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000141{
142#if defined(HAVE_FSTAT) && defined(S_IFDIR) && defined(EISDIR)
Antoine Pitroub26dc462010-05-05 16:27:30 +0000143 struct stat buf;
144 if (self->fd < 0)
145 return 0;
146 if (fstat(self->fd, &buf) == 0 && S_ISDIR(buf.st_mode)) {
Antoine Pitrouc2ec9922012-07-06 18:48:24 +0200147 errno = EISDIR;
148 PyErr_SetFromErrnoWithFilenameObject(PyExc_IOError, nameobj);
Antoine Pitroub26dc462010-05-05 16:27:30 +0000149 return -1;
150 }
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000151#endif
Antoine Pitroub26dc462010-05-05 16:27:30 +0000152 return 0;
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000153}
154
Benjamin Peterson5848d1f2009-01-19 00:08:08 +0000155static int
156check_fd(int fd)
157{
158#if defined(HAVE_FSTAT)
Antoine Pitroub26dc462010-05-05 16:27:30 +0000159 struct stat buf;
160 if (!_PyVerify_fd(fd) || (fstat(fd, &buf) < 0 && errno == EBADF)) {
161 PyObject *exc;
162 char *msg = strerror(EBADF);
163 exc = PyObject_CallFunction(PyExc_OSError, "(is)",
164 EBADF, msg);
165 PyErr_SetObject(PyExc_OSError, exc);
166 Py_XDECREF(exc);
167 return -1;
168 }
Benjamin Peterson5848d1f2009-01-19 00:08:08 +0000169#endif
Antoine Pitroub26dc462010-05-05 16:27:30 +0000170 return 0;
Benjamin Peterson5848d1f2009-01-19 00:08:08 +0000171}
172
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000173
174static int
175fileio_init(PyObject *oself, PyObject *args, PyObject *kwds)
176{
Antoine Pitroub26dc462010-05-05 16:27:30 +0000177 fileio *self = (fileio *) oself;
178 static char *kwlist[] = {"file", "mode", "closefd", NULL};
179 const char *name = NULL;
180 PyObject *nameobj, *stringobj = NULL;
181 char *mode = "r";
182 char *s;
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000183#ifdef MS_WINDOWS
Antoine Pitroub26dc462010-05-05 16:27:30 +0000184 Py_UNICODE *widename = NULL;
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000185#endif
Antoine Pitroub26dc462010-05-05 16:27:30 +0000186 int ret = 0;
187 int rwa = 0, plus = 0, append = 0;
188 int flags = 0;
189 int fd = -1;
190 int closefd = 1;
Hynek Schlawack9bd4bf22012-06-21 19:45:19 +0200191 int fd_is_own = 0;
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000192
Antoine Pitroub26dc462010-05-05 16:27:30 +0000193 assert(PyFileIO_Check(oself));
194 if (self->fd >= 0) {
Hynek Schlawack877effc2012-05-25 09:24:18 +0200195 if (self->closefd) {
196 /* Have to close the existing file first. */
197 if (internal_close(self) < 0)
198 return -1;
199 }
200 else
201 self->fd = -1;
Antoine Pitroub26dc462010-05-05 16:27:30 +0000202 }
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000203
Antoine Pitroub26dc462010-05-05 16:27:30 +0000204 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|si:fileio",
205 kwlist, &nameobj, &mode, &closefd))
206 return -1;
Antoine Pitrou19690592009-06-12 20:14:08 +0000207
Antoine Pitroub26dc462010-05-05 16:27:30 +0000208 if (PyFloat_Check(nameobj)) {
209 PyErr_SetString(PyExc_TypeError,
210 "integer argument expected, got float");
211 return -1;
212 }
Antoine Pitrou19690592009-06-12 20:14:08 +0000213
Antoine Pitroub26dc462010-05-05 16:27:30 +0000214 fd = PyLong_AsLong(nameobj);
215 if (fd < 0) {
216 if (!PyErr_Occurred()) {
217 PyErr_SetString(PyExc_ValueError,
218 "Negative filedescriptor");
219 return -1;
220 }
221 PyErr_Clear();
222 }
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000223
Hirokazu Yamamotob24bb272009-05-17 02:52:09 +0000224#ifdef MS_WINDOWS
Antoine Pitroub26dc462010-05-05 16:27:30 +0000225 if (PyUnicode_Check(nameobj))
226 widename = PyUnicode_AS_UNICODE(nameobj);
227 if (widename == NULL)
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000228#endif
Antoine Pitroub26dc462010-05-05 16:27:30 +0000229 if (fd < 0)
230 {
231 if (PyBytes_Check(nameobj) || PyByteArray_Check(nameobj)) {
232 Py_ssize_t namelen;
233 if (PyObject_AsCharBuffer(nameobj, &name, &namelen) < 0)
234 return -1;
235 }
236 else {
237 PyObject *u = PyUnicode_FromObject(nameobj);
Antoine Pitrou19690592009-06-12 20:14:08 +0000238
Antoine Pitroub26dc462010-05-05 16:27:30 +0000239 if (u == NULL)
240 return -1;
Antoine Pitrou19690592009-06-12 20:14:08 +0000241
Antoine Pitroub26dc462010-05-05 16:27:30 +0000242 stringobj = PyUnicode_AsEncodedString(
243 u, Py_FileSystemDefaultEncoding, NULL);
244 Py_DECREF(u);
245 if (stringobj == NULL)
246 return -1;
247 if (!PyBytes_Check(stringobj)) {
248 PyErr_SetString(PyExc_TypeError,
249 "encoder failed to return bytes");
250 goto error;
251 }
252 name = PyBytes_AS_STRING(stringobj);
253 }
254 }
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000255
Antoine Pitroub26dc462010-05-05 16:27:30 +0000256 s = mode;
257 while (*s) {
258 switch (*s++) {
259 case 'r':
260 if (rwa) {
261 bad_mode:
262 PyErr_SetString(PyExc_ValueError,
Georg Brandl10603802010-11-26 08:10:41 +0000263 "Must have exactly one of read/write/append "
264 "mode and at most one plus");
Antoine Pitroub26dc462010-05-05 16:27:30 +0000265 goto error;
266 }
267 rwa = 1;
268 self->readable = 1;
269 break;
270 case 'w':
271 if (rwa)
272 goto bad_mode;
273 rwa = 1;
274 self->writable = 1;
275 flags |= O_CREAT | O_TRUNC;
276 break;
277 case 'a':
278 if (rwa)
279 goto bad_mode;
280 rwa = 1;
281 self->writable = 1;
282 flags |= O_CREAT;
283 append = 1;
284 break;
285 case 'b':
286 break;
287 case '+':
288 if (plus)
289 goto bad_mode;
290 self->readable = self->writable = 1;
291 plus = 1;
292 break;
293 default:
294 PyErr_Format(PyExc_ValueError,
295 "invalid mode: %.200s", mode);
296 goto error;
297 }
298 }
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000299
Antoine Pitroub26dc462010-05-05 16:27:30 +0000300 if (!rwa)
301 goto bad_mode;
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000302
Antoine Pitroub26dc462010-05-05 16:27:30 +0000303 if (self->readable && self->writable)
304 flags |= O_RDWR;
305 else if (self->readable)
306 flags |= O_RDONLY;
307 else
308 flags |= O_WRONLY;
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000309
310#ifdef O_BINARY
Antoine Pitroub26dc462010-05-05 16:27:30 +0000311 flags |= O_BINARY;
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000312#endif
313
314#ifdef O_APPEND
Antoine Pitroub26dc462010-05-05 16:27:30 +0000315 if (append)
316 flags |= O_APPEND;
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000317#endif
318
Antoine Pitroub26dc462010-05-05 16:27:30 +0000319 if (fd >= 0) {
320 if (check_fd(fd))
321 goto error;
322 self->fd = fd;
323 self->closefd = closefd;
324 }
325 else {
326 self->closefd = 1;
327 if (!closefd) {
328 PyErr_SetString(PyExc_ValueError,
329 "Cannot use closefd=False with file name");
330 goto error;
331 }
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000332
Antoine Pitroub26dc462010-05-05 16:27:30 +0000333 Py_BEGIN_ALLOW_THREADS
334 errno = 0;
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000335#ifdef MS_WINDOWS
Antoine Pitroub26dc462010-05-05 16:27:30 +0000336 if (widename != NULL)
337 self->fd = _wopen(widename, flags, 0666);
338 else
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000339#endif
Antoine Pitroub26dc462010-05-05 16:27:30 +0000340 self->fd = open(name, flags, 0666);
341 Py_END_ALLOW_THREADS
Hynek Schlawack9bd4bf22012-06-21 19:45:19 +0200342 fd_is_own = 1;
Antoine Pitroub26dc462010-05-05 16:27:30 +0000343 if (self->fd < 0) {
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000344#ifdef MS_WINDOWS
Antoine Pitroub26dc462010-05-05 16:27:30 +0000345 if (widename != NULL)
346 PyErr_SetFromErrnoWithUnicodeFilename(PyExc_IOError, widename);
347 else
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000348#endif
Antoine Pitroub26dc462010-05-05 16:27:30 +0000349 PyErr_SetFromErrnoWithFilename(PyExc_IOError, name);
350 goto error;
351 }
Antoine Pitroub26dc462010-05-05 16:27:30 +0000352 }
Antoine Pitrouc2ec9922012-07-06 18:48:24 +0200353 if (dircheck(self, nameobj) < 0)
354 goto error;
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000355
Antoine Pitroub26dc462010-05-05 16:27:30 +0000356 if (PyObject_SetAttrString((PyObject *)self, "name", nameobj) < 0)
357 goto error;
Antoine Pitrou19690592009-06-12 20:14:08 +0000358
Antoine Pitroub26dc462010-05-05 16:27:30 +0000359 if (append) {
360 /* For consistent behaviour, we explicitly seek to the
361 end of file (otherwise, it might be done only on the
362 first write()). */
363 PyObject *pos = portable_lseek(self->fd, NULL, 2);
Hynek Schlawack9bd4bf22012-06-21 19:45:19 +0200364 if (pos == NULL)
Antoine Pitroub26dc462010-05-05 16:27:30 +0000365 goto error;
366 Py_DECREF(pos);
367 }
Antoine Pitroue741cc62009-01-21 00:45:36 +0000368
Antoine Pitroub26dc462010-05-05 16:27:30 +0000369 goto done;
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000370
371 error:
Hynek Schlawack9bd4bf22012-06-21 19:45:19 +0200372 if (!fd_is_own)
373 self->fd = -1;
374
Antoine Pitroub26dc462010-05-05 16:27:30 +0000375 ret = -1;
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000376
377 done:
Antoine Pitroub26dc462010-05-05 16:27:30 +0000378 Py_CLEAR(stringobj);
379 return ret;
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000380}
381
Antoine Pitrou19690592009-06-12 20:14:08 +0000382static int
383fileio_traverse(fileio *self, visitproc visit, void *arg)
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000384{
Antoine Pitroub26dc462010-05-05 16:27:30 +0000385 Py_VISIT(self->dict);
386 return 0;
Antoine Pitrou19690592009-06-12 20:14:08 +0000387}
388
389static int
390fileio_clear(fileio *self)
391{
Antoine Pitroub26dc462010-05-05 16:27:30 +0000392 Py_CLEAR(self->dict);
393 return 0;
Antoine Pitrou19690592009-06-12 20:14:08 +0000394}
395
396static void
397fileio_dealloc(fileio *self)
398{
Antoine Pitroub26dc462010-05-05 16:27:30 +0000399 if (_PyIOBase_finalize((PyObject *) self) < 0)
400 return;
401 _PyObject_GC_UNTRACK(self);
402 if (self->weakreflist != NULL)
403 PyObject_ClearWeakRefs((PyObject *) self);
404 Py_CLEAR(self->dict);
405 Py_TYPE(self)->tp_free((PyObject *)self);
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000406}
407
408static PyObject *
409err_closed(void)
410{
Antoine Pitroub26dc462010-05-05 16:27:30 +0000411 PyErr_SetString(PyExc_ValueError, "I/O operation on closed file");
412 return NULL;
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000413}
414
415static PyObject *
416err_mode(char *action)
417{
Antoine Pitroub26dc462010-05-05 16:27:30 +0000418 PyErr_Format(PyExc_ValueError, "File not open for %s", action);
419 return NULL;
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000420}
421
422static PyObject *
Antoine Pitrou19690592009-06-12 20:14:08 +0000423fileio_fileno(fileio *self)
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000424{
Antoine Pitroub26dc462010-05-05 16:27:30 +0000425 if (self->fd < 0)
426 return err_closed();
427 return PyInt_FromLong((long) self->fd);
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000428}
429
430static PyObject *
Antoine Pitrou19690592009-06-12 20:14:08 +0000431fileio_readable(fileio *self)
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000432{
Antoine Pitroub26dc462010-05-05 16:27:30 +0000433 if (self->fd < 0)
434 return err_closed();
435 return PyBool_FromLong((long) self->readable);
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000436}
437
438static PyObject *
Antoine Pitrou19690592009-06-12 20:14:08 +0000439fileio_writable(fileio *self)
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000440{
Antoine Pitroub26dc462010-05-05 16:27:30 +0000441 if (self->fd < 0)
442 return err_closed();
443 return PyBool_FromLong((long) self->writable);
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000444}
445
446static PyObject *
Antoine Pitrou19690592009-06-12 20:14:08 +0000447fileio_seekable(fileio *self)
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000448{
Antoine Pitroub26dc462010-05-05 16:27:30 +0000449 if (self->fd < 0)
450 return err_closed();
451 if (self->seekable < 0) {
452 PyObject *pos = portable_lseek(self->fd, NULL, SEEK_CUR);
453 if (pos == NULL) {
454 PyErr_Clear();
455 self->seekable = 0;
456 } else {
457 Py_DECREF(pos);
458 self->seekable = 1;
459 }
460 }
461 return PyBool_FromLong((long) self->seekable);
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000462}
463
464static PyObject *
Antoine Pitrou19690592009-06-12 20:14:08 +0000465fileio_readinto(fileio *self, PyObject *args)
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000466{
Antoine Pitroub26dc462010-05-05 16:27:30 +0000467 Py_buffer pbuf;
Victor Stinner59729ff2011-07-05 11:28:19 +0200468 Py_ssize_t n, len;
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000469
Antoine Pitroub26dc462010-05-05 16:27:30 +0000470 if (self->fd < 0)
471 return err_closed();
472 if (!self->readable)
473 return err_mode("reading");
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000474
Antoine Pitroub26dc462010-05-05 16:27:30 +0000475 if (!PyArg_ParseTuple(args, "w*", &pbuf))
476 return NULL;
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000477
Antoine Pitroub26dc462010-05-05 16:27:30 +0000478 if (_PyVerify_fd(self->fd)) {
Victor Stinner59729ff2011-07-05 11:28:19 +0200479 len = pbuf.len;
Antoine Pitroub26dc462010-05-05 16:27:30 +0000480 Py_BEGIN_ALLOW_THREADS
481 errno = 0;
Victor Stinner59729ff2011-07-05 11:28:19 +0200482#if defined(MS_WIN64) || defined(MS_WINDOWS)
483 if (len > INT_MAX)
484 len = INT_MAX;
485 n = read(self->fd, pbuf.buf, (int)len);
486#else
487 n = read(self->fd, pbuf.buf, len);
488#endif
Antoine Pitroub26dc462010-05-05 16:27:30 +0000489 Py_END_ALLOW_THREADS
490 } else
491 n = -1;
492 PyBuffer_Release(&pbuf);
493 if (n < 0) {
494 if (errno == EAGAIN)
495 Py_RETURN_NONE;
496 PyErr_SetFromErrno(PyExc_IOError);
497 return NULL;
498 }
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000499
Antoine Pitroub26dc462010-05-05 16:27:30 +0000500 return PyLong_FromSsize_t(n);
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000501}
502
Antoine Pitrou19690592009-06-12 20:14:08 +0000503static size_t
504new_buffersize(fileio *self, size_t currentsize)
505{
506#ifdef HAVE_FSTAT
Antoine Pitroub26dc462010-05-05 16:27:30 +0000507 off_t pos, end;
508 struct stat st;
509 if (fstat(self->fd, &st) == 0) {
510 end = st.st_size;
511 pos = lseek(self->fd, 0L, SEEK_CUR);
512 /* Files claiming a size smaller than SMALLCHUNK may
513 actually be streaming pseudo-files. In this case, we
514 apply the more aggressive algorithm below.
515 */
516 if (end >= SMALLCHUNK && end >= pos && pos >= 0) {
517 /* Add 1 so if the file were to grow we'd notice. */
518 return currentsize + end - pos + 1;
519 }
520 }
Antoine Pitrou19690592009-06-12 20:14:08 +0000521#endif
Nadeem Vawda36248152011-10-13 13:52:46 +0200522 /* Expand the buffer by an amount proportional to the current size,
523 giving us amortized linear-time behavior. Use a less-than-double
524 growth factor to avoid excessive allocation. */
525 return currentsize + (currentsize >> 3) + 6;
Antoine Pitrou19690592009-06-12 20:14:08 +0000526}
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000527
528static PyObject *
Antoine Pitrou19690592009-06-12 20:14:08 +0000529fileio_readall(fileio *self)
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000530{
Antoine Pitroub26dc462010-05-05 16:27:30 +0000531 PyObject *result;
532 Py_ssize_t total = 0;
Victor Stinner23a32ba2013-01-03 03:33:21 +0100533 Py_ssize_t n;
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000534
Victor Stinner5100a402011-05-25 22:15:36 +0200535 if (self->fd < 0)
536 return err_closed();
Antoine Pitroub26dc462010-05-05 16:27:30 +0000537 if (!_PyVerify_fd(self->fd))
538 return PyErr_SetFromErrno(PyExc_IOError);
Antoine Pitrou19690592009-06-12 20:14:08 +0000539
Antoine Pitroub26dc462010-05-05 16:27:30 +0000540 result = PyBytes_FromStringAndSize(NULL, SMALLCHUNK);
541 if (result == NULL)
542 return NULL;
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000543
Antoine Pitroub26dc462010-05-05 16:27:30 +0000544 while (1) {
545 size_t newsize = new_buffersize(self, total);
546 if (newsize > PY_SSIZE_T_MAX || newsize <= 0) {
547 PyErr_SetString(PyExc_OverflowError,
548 "unbounded read returned more bytes "
549 "than a Python string can hold ");
550 Py_DECREF(result);
551 return NULL;
552 }
Antoine Pitrou19690592009-06-12 20:14:08 +0000553
Antoine Pitroub26dc462010-05-05 16:27:30 +0000554 if (PyBytes_GET_SIZE(result) < (Py_ssize_t)newsize) {
555 if (_PyBytes_Resize(&result, newsize) < 0) {
556 if (total == 0) {
557 Py_DECREF(result);
558 return NULL;
559 }
560 PyErr_Clear();
561 break;
562 }
563 }
564 Py_BEGIN_ALLOW_THREADS
565 errno = 0;
Victor Stinner23a32ba2013-01-03 03:33:21 +0100566 n = newsize - total;
567#if defined(MS_WIN64) || defined(MS_WINDOWS)
568 if (n > INT_MAX)
569 n = INT_MAX;
Antoine Pitroub26dc462010-05-05 16:27:30 +0000570 n = read(self->fd,
571 PyBytes_AS_STRING(result) + total,
Victor Stinner23a32ba2013-01-03 03:33:21 +0100572 (int)n);
573#else
574 n = read(self->fd,
575 PyBytes_AS_STRING(result) + total,
576 n);
577#endif
Antoine Pitroub26dc462010-05-05 16:27:30 +0000578 Py_END_ALLOW_THREADS
579 if (n == 0)
580 break;
581 if (n < 0) {
Gregory P. Smith99716162012-10-12 13:02:06 -0700582 if (errno == EINTR) {
583 if (PyErr_CheckSignals()) {
584 Py_DECREF(result);
585 return NULL;
586 }
587 continue;
588 }
Antoine Pitroub26dc462010-05-05 16:27:30 +0000589 if (total > 0)
590 break;
591 if (errno == EAGAIN) {
592 Py_DECREF(result);
593 Py_RETURN_NONE;
594 }
595 Py_DECREF(result);
596 PyErr_SetFromErrno(PyExc_IOError);
597 return NULL;
598 }
599 total += n;
600 }
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000601
Antoine Pitroub26dc462010-05-05 16:27:30 +0000602 if (PyBytes_GET_SIZE(result) > total) {
603 if (_PyBytes_Resize(&result, total) < 0) {
604 /* This should never happen, but just in case */
605 Py_DECREF(result);
606 return NULL;
607 }
608 }
609 return result;
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000610}
611
612static PyObject *
Antoine Pitrou19690592009-06-12 20:14:08 +0000613fileio_read(fileio *self, PyObject *args)
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000614{
Antoine Pitroub26dc462010-05-05 16:27:30 +0000615 char *ptr;
616 Py_ssize_t n;
617 Py_ssize_t size = -1;
618 PyObject *bytes;
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000619
Antoine Pitroub26dc462010-05-05 16:27:30 +0000620 if (self->fd < 0)
621 return err_closed();
622 if (!self->readable)
623 return err_mode("reading");
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000624
Antoine Pitroub26dc462010-05-05 16:27:30 +0000625 if (!PyArg_ParseTuple(args, "|O&", &_PyIO_ConvertSsize_t, &size))
626 return NULL;
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000627
Antoine Pitroub26dc462010-05-05 16:27:30 +0000628 if (size < 0) {
629 return fileio_readall(self);
630 }
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000631
Victor Stinner59729ff2011-07-05 11:28:19 +0200632#if defined(MS_WIN64) || defined(MS_WINDOWS)
633 if (size > INT_MAX)
634 size = INT_MAX;
635#endif
Antoine Pitroub26dc462010-05-05 16:27:30 +0000636 bytes = PyBytes_FromStringAndSize(NULL, size);
637 if (bytes == NULL)
638 return NULL;
639 ptr = PyBytes_AS_STRING(bytes);
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000640
Antoine Pitroub26dc462010-05-05 16:27:30 +0000641 if (_PyVerify_fd(self->fd)) {
642 Py_BEGIN_ALLOW_THREADS
643 errno = 0;
Victor Stinner59729ff2011-07-05 11:28:19 +0200644#if defined(MS_WIN64) || defined(MS_WINDOWS)
645 n = read(self->fd, ptr, (int)size);
646#else
Antoine Pitroub26dc462010-05-05 16:27:30 +0000647 n = read(self->fd, ptr, size);
Victor Stinner59729ff2011-07-05 11:28:19 +0200648#endif
Antoine Pitroub26dc462010-05-05 16:27:30 +0000649 Py_END_ALLOW_THREADS
650 } else
651 n = -1;
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000652
Antoine Pitroub26dc462010-05-05 16:27:30 +0000653 if (n < 0) {
654 Py_DECREF(bytes);
655 if (errno == EAGAIN)
656 Py_RETURN_NONE;
657 PyErr_SetFromErrno(PyExc_IOError);
658 return NULL;
659 }
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000660
Antoine Pitroub26dc462010-05-05 16:27:30 +0000661 if (n != size) {
662 if (_PyBytes_Resize(&bytes, n) < 0) {
663 Py_DECREF(bytes);
664 return NULL;
665 }
666 }
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000667
Antoine Pitroub26dc462010-05-05 16:27:30 +0000668 return (PyObject *) bytes;
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000669}
670
671static PyObject *
Antoine Pitrou19690592009-06-12 20:14:08 +0000672fileio_write(fileio *self, PyObject *args)
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000673{
Antoine Pitroub26dc462010-05-05 16:27:30 +0000674 Py_buffer pbuf;
Victor Stinner59729ff2011-07-05 11:28:19 +0200675 Py_ssize_t n, len;
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000676
Antoine Pitroub26dc462010-05-05 16:27:30 +0000677 if (self->fd < 0)
678 return err_closed();
679 if (!self->writable)
680 return err_mode("writing");
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000681
Antoine Pitroub26dc462010-05-05 16:27:30 +0000682 if (!PyArg_ParseTuple(args, "s*", &pbuf))
683 return NULL;
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000684
Antoine Pitroub26dc462010-05-05 16:27:30 +0000685 if (_PyVerify_fd(self->fd)) {
686 Py_BEGIN_ALLOW_THREADS
687 errno = 0;
Victor Stinner59729ff2011-07-05 11:28:19 +0200688 len = pbuf.len;
689#if defined(MS_WIN64) || defined(MS_WINDOWS)
690 if (len > INT_MAX)
691 len = INT_MAX;
692 n = write(self->fd, pbuf.buf, (int)len);
693#else
694 n = write(self->fd, pbuf.buf, len);
695#endif
Antoine Pitroub26dc462010-05-05 16:27:30 +0000696 Py_END_ALLOW_THREADS
697 } else
698 n = -1;
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000699
Antoine Pitroub26dc462010-05-05 16:27:30 +0000700 PyBuffer_Release(&pbuf);
Martin v. Löwisf91d46a2008-08-12 14:49:50 +0000701
Antoine Pitroub26dc462010-05-05 16:27:30 +0000702 if (n < 0) {
703 if (errno == EAGAIN)
704 Py_RETURN_NONE;
705 PyErr_SetFromErrno(PyExc_IOError);
706 return NULL;
707 }
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000708
Antoine Pitroub26dc462010-05-05 16:27:30 +0000709 return PyLong_FromSsize_t(n);
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000710}
711
712/* XXX Windows support below is likely incomplete */
713
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000714/* Cribbed from posix_lseek() */
715static PyObject *
716portable_lseek(int fd, PyObject *posobj, int whence)
717{
Antoine Pitroub26dc462010-05-05 16:27:30 +0000718 Py_off_t pos, res;
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000719
720#ifdef SEEK_SET
Antoine Pitroub26dc462010-05-05 16:27:30 +0000721 /* Turn 0, 1, 2 into SEEK_{SET,CUR,END} */
722 switch (whence) {
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000723#if SEEK_SET != 0
Antoine Pitroub26dc462010-05-05 16:27:30 +0000724 case 0: whence = SEEK_SET; break;
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000725#endif
726#if SEEK_CUR != 1
Antoine Pitroub26dc462010-05-05 16:27:30 +0000727 case 1: whence = SEEK_CUR; break;
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000728#endif
Benjamin Peterson8024cec2009-01-20 14:31:08 +0000729#if SEEK_END != 2
Antoine Pitroub26dc462010-05-05 16:27:30 +0000730 case 2: whence = SEEK_END; break;
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000731#endif
Antoine Pitroub26dc462010-05-05 16:27:30 +0000732 }
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000733#endif /* SEEK_SET */
734
Antoine Pitroub26dc462010-05-05 16:27:30 +0000735 if (posobj == NULL)
736 pos = 0;
737 else {
738 if(PyFloat_Check(posobj)) {
739 PyErr_SetString(PyExc_TypeError, "an integer is required");
740 return NULL;
741 }
Alexandre Vassalotti1aed6242008-05-09 21:49:43 +0000742#if defined(HAVE_LARGEFILE_SUPPORT)
Antoine Pitroub26dc462010-05-05 16:27:30 +0000743 pos = PyLong_AsLongLong(posobj);
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000744#else
Antoine Pitroub26dc462010-05-05 16:27:30 +0000745 pos = PyLong_AsLong(posobj);
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000746#endif
Antoine Pitroub26dc462010-05-05 16:27:30 +0000747 if (PyErr_Occurred())
748 return NULL;
749 }
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000750
Antoine Pitroub26dc462010-05-05 16:27:30 +0000751 if (_PyVerify_fd(fd)) {
752 Py_BEGIN_ALLOW_THREADS
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000753#if defined(MS_WIN64) || defined(MS_WINDOWS)
Antoine Pitroub26dc462010-05-05 16:27:30 +0000754 res = _lseeki64(fd, pos, whence);
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000755#else
Antoine Pitroub26dc462010-05-05 16:27:30 +0000756 res = lseek(fd, pos, whence);
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000757#endif
Antoine Pitroub26dc462010-05-05 16:27:30 +0000758 Py_END_ALLOW_THREADS
759 } else
760 res = -1;
761 if (res < 0)
762 return PyErr_SetFromErrno(PyExc_IOError);
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000763
Alexandre Vassalotti1aed6242008-05-09 21:49:43 +0000764#if defined(HAVE_LARGEFILE_SUPPORT)
Antoine Pitroub26dc462010-05-05 16:27:30 +0000765 return PyLong_FromLongLong(res);
Alexandre Vassalotti1aed6242008-05-09 21:49:43 +0000766#else
Antoine Pitroub26dc462010-05-05 16:27:30 +0000767 return PyLong_FromLong(res);
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000768#endif
769}
770
771static PyObject *
Antoine Pitrou19690592009-06-12 20:14:08 +0000772fileio_seek(fileio *self, PyObject *args)
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000773{
Antoine Pitroub26dc462010-05-05 16:27:30 +0000774 PyObject *posobj;
775 int whence = 0;
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000776
Antoine Pitroub26dc462010-05-05 16:27:30 +0000777 if (self->fd < 0)
778 return err_closed();
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000779
Antoine Pitroub26dc462010-05-05 16:27:30 +0000780 if (!PyArg_ParseTuple(args, "O|i", &posobj, &whence))
781 return NULL;
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000782
Antoine Pitroub26dc462010-05-05 16:27:30 +0000783 return portable_lseek(self->fd, posobj, whence);
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000784}
785
786static PyObject *
Antoine Pitrou19690592009-06-12 20:14:08 +0000787fileio_tell(fileio *self, PyObject *args)
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000788{
Antoine Pitroub26dc462010-05-05 16:27:30 +0000789 if (self->fd < 0)
790 return err_closed();
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000791
Antoine Pitroub26dc462010-05-05 16:27:30 +0000792 return portable_lseek(self->fd, NULL, 1);
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000793}
794
795#ifdef HAVE_FTRUNCATE
796static PyObject *
Antoine Pitrou19690592009-06-12 20:14:08 +0000797fileio_truncate(fileio *self, PyObject *args)
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000798{
Antoine Pitroub26dc462010-05-05 16:27:30 +0000799 PyObject *posobj = NULL; /* the new size wanted by the user */
Antoine Pitrouf3fa0742010-01-31 22:26:04 +0000800#ifndef MS_WINDOWS
Antoine Pitroub26dc462010-05-05 16:27:30 +0000801 Py_off_t pos;
Antoine Pitrouf3fa0742010-01-31 22:26:04 +0000802#endif
Antoine Pitroub26dc462010-05-05 16:27:30 +0000803 int ret;
804 int fd;
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000805
Antoine Pitroub26dc462010-05-05 16:27:30 +0000806 fd = self->fd;
807 if (fd < 0)
808 return err_closed();
809 if (!self->writable)
810 return err_mode("writing");
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000811
Antoine Pitroub26dc462010-05-05 16:27:30 +0000812 if (!PyArg_ParseTuple(args, "|O", &posobj))
813 return NULL;
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000814
Antoine Pitroub26dc462010-05-05 16:27:30 +0000815 if (posobj == Py_None || posobj == NULL) {
816 /* Get the current position. */
817 posobj = portable_lseek(fd, NULL, 1);
818 if (posobj == NULL)
819 return NULL;
820 }
821 else {
822 Py_INCREF(posobj);
823 }
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000824
825#ifdef MS_WINDOWS
Antoine Pitroub26dc462010-05-05 16:27:30 +0000826 /* MS _chsize doesn't work if newsize doesn't fit in 32 bits,
827 so don't even try using it. */
828 {
829 PyObject *oldposobj, *tempposobj;
830 HANDLE hFile;
Antoine Pitrouf3fa0742010-01-31 22:26:04 +0000831
Antoine Pitroub26dc462010-05-05 16:27:30 +0000832 /* we save the file pointer position */
833 oldposobj = portable_lseek(fd, NULL, 1);
834 if (oldposobj == NULL) {
835 Py_DECREF(posobj);
836 return NULL;
837 }
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000838
Antoine Pitroub26dc462010-05-05 16:27:30 +0000839 /* we then move to the truncation position */
840 tempposobj = portable_lseek(fd, posobj, 0);
841 if (tempposobj == NULL) {
842 Py_DECREF(oldposobj);
843 Py_DECREF(posobj);
844 return NULL;
845 }
846 Py_DECREF(tempposobj);
Antoine Pitrouf3fa0742010-01-31 22:26:04 +0000847
Antoine Pitroub26dc462010-05-05 16:27:30 +0000848 /* Truncate. Note that this may grow the file! */
849 Py_BEGIN_ALLOW_THREADS
850 errno = 0;
851 hFile = (HANDLE)_get_osfhandle(fd);
852 ret = hFile == (HANDLE)-1; /* testing for INVALID_HANDLE value */
853 if (ret == 0) {
854 ret = SetEndOfFile(hFile) == 0;
855 if (ret)
856 errno = EACCES;
857 }
858 Py_END_ALLOW_THREADS
859
860 /* we restore the file pointer position in any case */
861 tempposobj = portable_lseek(fd, oldposobj, 0);
862 Py_DECREF(oldposobj);
863 if (tempposobj == NULL) {
864 Py_DECREF(posobj);
865 return NULL;
866 }
867 Py_DECREF(tempposobj);
868 }
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000869#else
Antoine Pitrouf3fa0742010-01-31 22:26:04 +0000870
871#if defined(HAVE_LARGEFILE_SUPPORT)
Antoine Pitroub26dc462010-05-05 16:27:30 +0000872 pos = PyLong_AsLongLong(posobj);
Antoine Pitrouf3fa0742010-01-31 22:26:04 +0000873#else
Antoine Pitroub26dc462010-05-05 16:27:30 +0000874 pos = PyLong_AsLong(posobj);
Antoine Pitrouf3fa0742010-01-31 22:26:04 +0000875#endif
Antoine Pitroub26dc462010-05-05 16:27:30 +0000876 if (PyErr_Occurred()){
877 Py_DECREF(posobj);
878 return NULL;
879 }
Antoine Pitrouf3fa0742010-01-31 22:26:04 +0000880
Antoine Pitroub26dc462010-05-05 16:27:30 +0000881 Py_BEGIN_ALLOW_THREADS
882 errno = 0;
883 ret = ftruncate(fd, pos);
884 Py_END_ALLOW_THREADS
Antoine Pitrouf3fa0742010-01-31 22:26:04 +0000885
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000886#endif /* !MS_WINDOWS */
887
Antoine Pitroub26dc462010-05-05 16:27:30 +0000888 if (ret != 0) {
889 Py_DECREF(posobj);
890 PyErr_SetFromErrno(PyExc_IOError);
891 return NULL;
892 }
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000893
Antoine Pitroub26dc462010-05-05 16:27:30 +0000894 return posobj;
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000895}
Antoine Pitrouf3fa0742010-01-31 22:26:04 +0000896#endif /* HAVE_FTRUNCATE */
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000897
898static char *
Antoine Pitrou19690592009-06-12 20:14:08 +0000899mode_string(fileio *self)
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000900{
Antoine Pitroub26dc462010-05-05 16:27:30 +0000901 if (self->readable) {
902 if (self->writable)
903 return "rb+";
904 else
905 return "rb";
906 }
907 else
908 return "wb";
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000909}
910
911static PyObject *
Antoine Pitrou19690592009-06-12 20:14:08 +0000912fileio_repr(fileio *self)
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000913{
Antoine Pitroub26dc462010-05-05 16:27:30 +0000914 PyObject *nameobj, *res;
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000915
Antoine Pitroub26dc462010-05-05 16:27:30 +0000916 if (self->fd < 0)
917 return PyString_FromFormat("<_io.FileIO [closed]>");
Antoine Pitrou19690592009-06-12 20:14:08 +0000918
Antoine Pitroub26dc462010-05-05 16:27:30 +0000919 nameobj = PyObject_GetAttrString((PyObject *) self, "name");
920 if (nameobj == NULL) {
921 if (PyErr_ExceptionMatches(PyExc_AttributeError))
922 PyErr_Clear();
923 else
924 return NULL;
925 res = PyString_FromFormat("<_io.FileIO fd=%d mode='%s'>",
926 self->fd, mode_string(self));
927 }
928 else {
929 PyObject *repr = PyObject_Repr(nameobj);
930 Py_DECREF(nameobj);
931 if (repr == NULL)
932 return NULL;
933 res = PyString_FromFormat("<_io.FileIO name=%s mode='%s'>",
934 PyString_AS_STRING(repr),
935 mode_string(self));
936 Py_DECREF(repr);
937 }
938 return res;
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000939}
940
941static PyObject *
Antoine Pitrou19690592009-06-12 20:14:08 +0000942fileio_isatty(fileio *self)
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000943{
Antoine Pitroub26dc462010-05-05 16:27:30 +0000944 long res;
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000945
Antoine Pitroub26dc462010-05-05 16:27:30 +0000946 if (self->fd < 0)
947 return err_closed();
948 Py_BEGIN_ALLOW_THREADS
949 res = isatty(self->fd);
950 Py_END_ALLOW_THREADS
951 return PyBool_FromLong(res);
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000952}
953
954
955PyDoc_STRVAR(fileio_doc,
956"file(name: str[, mode: str]) -> file IO object\n"
957"\n"
958"Open a file. The mode can be 'r', 'w' or 'a' for reading (default),\n"
Antoine Pitroub26dc462010-05-05 16:27:30 +0000959"writing or appending. The file will be created if it doesn't exist\n"
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000960"when opened for writing or appending; it will be truncated when\n"
961"opened for writing. Add a '+' to the mode to allow simultaneous\n"
962"reading and writing.");
963
964PyDoc_STRVAR(read_doc,
965"read(size: int) -> bytes. read at most size bytes, returned as bytes.\n"
966"\n"
967"Only makes one system call, so less data may be returned than requested\n"
968"In non-blocking mode, returns None if no data is available.\n"
969"On end-of-file, returns ''.");
970
971PyDoc_STRVAR(readall_doc,
972"readall() -> bytes. read all data from the file, returned as bytes.\n"
973"\n"
974"In non-blocking mode, returns as much as is immediately available,\n"
975"or None if no data is available. On end-of-file, returns ''.");
976
977PyDoc_STRVAR(write_doc,
978"write(b: bytes) -> int. Write bytes b to file, return number written.\n"
979"\n"
980"Only makes one system call, so not all of the data may be written.\n"
981"The number of bytes actually written is returned.");
982
983PyDoc_STRVAR(fileno_doc,
984"fileno() -> int. \"file descriptor\".\n"
985"\n"
986"This is needed for lower-level file interfaces, such the fcntl module.");
987
988PyDoc_STRVAR(seek_doc,
989"seek(offset: int[, whence: int]) -> None. Move to new file position.\n"
990"\n"
991"Argument offset is a byte count. Optional argument whence defaults to\n"
992"0 (offset from start of file, offset should be >= 0); other values are 1\n"
993"(move relative to current position, positive or negative), and 2 (move\n"
994"relative to end of file, usually negative, although many platforms allow\n"
995"seeking beyond the end of a file)."
996"\n"
997"Note that not all file objects are seekable.");
998
999#ifdef HAVE_FTRUNCATE
1000PyDoc_STRVAR(truncate_doc,
Antoine Pitroub26dc462010-05-05 16:27:30 +00001001"truncate([size: int]) -> None. Truncate the file to at most size bytes.\n"
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001002"\n"
Alexandre Vassalotti1aed6242008-05-09 21:49:43 +00001003"Size defaults to the current file position, as returned by tell()."
1004"The current file position is changed to the value of size.");
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001005#endif
1006
1007PyDoc_STRVAR(tell_doc,
Antoine Pitroub26dc462010-05-05 16:27:30 +00001008"tell() -> int. Current file position");
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001009
1010PyDoc_STRVAR(readinto_doc,
Antoine Pitrou19690592009-06-12 20:14:08 +00001011"readinto() -> Same as RawIOBase.readinto().");
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001012
1013PyDoc_STRVAR(close_doc,
1014"close() -> None. Close the file.\n"
1015"\n"
1016"A closed file cannot be used for further I/O operations. close() may be\n"
1017"called more than once without error. Changes the fileno to -1.");
1018
1019PyDoc_STRVAR(isatty_doc,
1020"isatty() -> bool. True if the file is connected to a tty device.");
1021
1022PyDoc_STRVAR(seekable_doc,
1023"seekable() -> bool. True if file supports random-access.");
1024
1025PyDoc_STRVAR(readable_doc,
1026"readable() -> bool. True if file was opened in a read mode.");
1027
1028PyDoc_STRVAR(writable_doc,
1029"writable() -> bool. True if file was opened in a write mode.");
1030
1031static PyMethodDef fileio_methods[] = {
Antoine Pitroub26dc462010-05-05 16:27:30 +00001032 {"read", (PyCFunction)fileio_read, METH_VARARGS, read_doc},
1033 {"readall", (PyCFunction)fileio_readall, METH_NOARGS, readall_doc},
1034 {"readinto", (PyCFunction)fileio_readinto, METH_VARARGS, readinto_doc},
1035 {"write", (PyCFunction)fileio_write, METH_VARARGS, write_doc},
1036 {"seek", (PyCFunction)fileio_seek, METH_VARARGS, seek_doc},
1037 {"tell", (PyCFunction)fileio_tell, METH_VARARGS, tell_doc},
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001038#ifdef HAVE_FTRUNCATE
Antoine Pitroub26dc462010-05-05 16:27:30 +00001039 {"truncate", (PyCFunction)fileio_truncate, METH_VARARGS, truncate_doc},
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001040#endif
Antoine Pitroub26dc462010-05-05 16:27:30 +00001041 {"close", (PyCFunction)fileio_close, METH_NOARGS, close_doc},
1042 {"seekable", (PyCFunction)fileio_seekable, METH_NOARGS, seekable_doc},
1043 {"readable", (PyCFunction)fileio_readable, METH_NOARGS, readable_doc},
1044 {"writable", (PyCFunction)fileio_writable, METH_NOARGS, writable_doc},
1045 {"fileno", (PyCFunction)fileio_fileno, METH_NOARGS, fileno_doc},
1046 {"isatty", (PyCFunction)fileio_isatty, METH_NOARGS, isatty_doc},
1047 {NULL, NULL} /* sentinel */
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001048};
1049
1050/* 'closed' and 'mode' are attributes for backwards compatibility reasons. */
1051
1052static PyObject *
Antoine Pitrou19690592009-06-12 20:14:08 +00001053get_closed(fileio *self, void *closure)
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001054{
Antoine Pitroub26dc462010-05-05 16:27:30 +00001055 return PyBool_FromLong((long)(self->fd < 0));
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001056}
1057
1058static PyObject *
Antoine Pitrou19690592009-06-12 20:14:08 +00001059get_closefd(fileio *self, void *closure)
Amaury Forgeot d'Arc32265652008-11-20 23:34:31 +00001060{
Antoine Pitroub26dc462010-05-05 16:27:30 +00001061 return PyBool_FromLong((long)(self->closefd));
Amaury Forgeot d'Arc32265652008-11-20 23:34:31 +00001062}
1063
1064static PyObject *
Antoine Pitrou19690592009-06-12 20:14:08 +00001065get_mode(fileio *self, void *closure)
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001066{
Antoine Pitroub26dc462010-05-05 16:27:30 +00001067 return PyUnicode_FromString(mode_string(self));
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001068}
1069
1070static PyGetSetDef fileio_getsetlist[] = {
Antoine Pitroub26dc462010-05-05 16:27:30 +00001071 {"closed", (getter)get_closed, NULL, "True if the file is closed"},
1072 {"closefd", (getter)get_closefd, NULL,
1073 "True if the file descriptor will be closed"},
1074 {"mode", (getter)get_mode, NULL, "String giving the file mode"},
1075 {NULL},
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001076};
1077
1078PyTypeObject PyFileIO_Type = {
Antoine Pitroub26dc462010-05-05 16:27:30 +00001079 PyVarObject_HEAD_INIT(NULL, 0)
1080 "_io.FileIO",
1081 sizeof(fileio),
1082 0,
1083 (destructor)fileio_dealloc, /* tp_dealloc */
1084 0, /* tp_print */
1085 0, /* tp_getattr */
1086 0, /* tp_setattr */
1087 0, /* tp_reserved */
1088 (reprfunc)fileio_repr, /* tp_repr */
1089 0, /* tp_as_number */
1090 0, /* tp_as_sequence */
1091 0, /* tp_as_mapping */
1092 0, /* tp_hash */
1093 0, /* tp_call */
1094 0, /* tp_str */
1095 PyObject_GenericGetAttr, /* tp_getattro */
1096 0, /* tp_setattro */
1097 0, /* tp_as_buffer */
1098 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE
1099 | Py_TPFLAGS_HAVE_GC, /* tp_flags */
1100 fileio_doc, /* tp_doc */
1101 (traverseproc)fileio_traverse, /* tp_traverse */
1102 (inquiry)fileio_clear, /* tp_clear */
1103 0, /* tp_richcompare */
1104 offsetof(fileio, weakreflist), /* tp_weaklistoffset */
1105 0, /* tp_iter */
1106 0, /* tp_iternext */
1107 fileio_methods, /* tp_methods */
1108 0, /* tp_members */
1109 fileio_getsetlist, /* tp_getset */
1110 0, /* tp_base */
1111 0, /* tp_dict */
1112 0, /* tp_descr_get */
1113 0, /* tp_descr_set */
1114 offsetof(fileio, dict), /* tp_dictoffset */
1115 fileio_init, /* tp_init */
1116 PyType_GenericAlloc, /* tp_alloc */
1117 fileio_new, /* tp_new */
1118 PyObject_GC_Del, /* tp_free */
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001119};