blob: 0fce1a33869de69ea32b8f98efe348fd6f1b5662 [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"
5#include <sys/types.h>
6#include <sys/stat.h>
7#include <fcntl.h>
8#include <stddef.h> /* For offsetof */
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00009#include "_iomodule.h"
Guido van Rossuma9e20242007-03-08 00:43:48 +000010
11/*
12 * Known likely problems:
13 *
14 * - Files larger then 2**32-1
15 * - Files with unicode filenames
16 * - Passing numbers greater than 2**32-1 when an integer is expected
17 * - Making it work on Windows and other oddball platforms
18 *
19 * To Do:
20 *
21 * - autoconfify header file inclusion
Guido van Rossuma9e20242007-03-08 00:43:48 +000022 */
23
24#ifdef MS_WINDOWS
25/* can simulate truncate with Win32 API functions; see file_truncate */
Thomas Hellerfdeee3a2007-07-12 11:21:36 +000026#define HAVE_FTRUNCATE
Guido van Rossuma9e20242007-03-08 00:43:48 +000027#define WIN32_LEAN_AND_MEAN
28#include <windows.h>
29#endif
30
Christian Heimesa872de52008-12-05 08:26:55 +000031#if BUFSIZ < (8*1024)
32#define SMALLCHUNK (8*1024)
33#elif (BUFSIZ >= (2 << 25))
34#error "unreasonable BUFSIZ > 64MB defined"
35#else
36#define SMALLCHUNK BUFSIZ
37#endif
38
39#if SIZEOF_INT < 4
40#define BIGCHUNK (512 * 32)
41#else
42#define BIGCHUNK (512 * 1024)
43#endif
44
Guido van Rossuma9e20242007-03-08 00:43:48 +000045typedef struct {
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +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;
Benjamin Peterson680bf1a2009-06-12 02:07:12 +000054} fileio;
Guido van Rossuma9e20242007-03-08 00:43:48 +000055
Collin Winteraf334382007-03-08 21:46:15 +000056PyTypeObject PyFileIO_Type;
57
Guido van Rossuma9e20242007-03-08 00:43:48 +000058#define PyFileIO_Check(op) (PyObject_TypeCheck((op), &PyFileIO_Type))
59
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +000060int
61_PyFileIO_closed(PyObject *self)
62{
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +000063 return ((fileio *)self)->fd < 0;
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +000064}
Antoine Pitrou08838b62009-01-21 00:55:13 +000065
Antoine Pitrou7fb111b2009-03-04 11:14:01 +000066static PyObject *
67portable_lseek(int fd, PyObject *posobj, int whence);
68
Antoine Pitroua28fcfd2009-03-13 23:42:55 +000069static PyObject *portable_lseek(int fd, PyObject *posobj, int whence);
70
Kristján Valur Jónsson19288c22008-12-18 17:15:54 +000071/* Returns 0 on success, -1 with exception set on failure. */
Neal Norwitz88b44da2007-08-12 17:23:54 +000072static int
Benjamin Peterson680bf1a2009-06-12 02:07:12 +000073internal_close(fileio *self)
Guido van Rossuma9e20242007-03-08 00:43:48 +000074{
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +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;
Neal Norwitz88b44da2007-08-12 17:23:54 +000098}
99
100static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000101fileio_close(fileio *self)
Neal Norwitz88b44da2007-08-12 17:23:54 +0000102{
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +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;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000110
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000111 return PyObject_CallMethod((PyObject*)&PyRawIOBase_Type,
112 "close", "O", self);
Guido van Rossuma9e20242007-03-08 00:43:48 +0000113}
114
115static PyObject *
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000116fileio_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
Guido van Rossuma9e20242007-03-08 00:43:48 +0000117{
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000118 fileio *self;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000119
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000120 assert(type != NULL && type->tp_alloc != NULL);
Guido van Rossuma9e20242007-03-08 00:43:48 +0000121
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +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 }
Guido van Rossuma9e20242007-03-08 00:43:48 +0000131
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000132 return (PyObject *) self;
Guido van Rossuma9e20242007-03-08 00:43:48 +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
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000140dircheck(fileio* self, const char *name)
Guido van Rossuma9e20242007-03-08 00:43:48 +0000141{
142#if defined(HAVE_FSTAT) && defined(S_IFDIR) && defined(EISDIR)
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000143 struct stat buf;
144 if (self->fd < 0)
145 return 0;
146 if (fstat(self->fd, &buf) == 0 && S_ISDIR(buf.st_mode)) {
147 char *msg = strerror(EISDIR);
148 PyObject *exc;
149 if (internal_close(self))
150 return -1;
Guido van Rossum53807da2007-04-10 19:01:47 +0000151
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000152 exc = PyObject_CallFunction(PyExc_IOError, "(iss)",
153 EISDIR, msg, name);
154 PyErr_SetObject(PyExc_IOError, exc);
155 Py_XDECREF(exc);
156 return -1;
157 }
Guido van Rossuma9e20242007-03-08 00:43:48 +0000158#endif
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000159 return 0;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000160}
161
Benjamin Peterson806d4022009-01-19 15:11:51 +0000162static int
163check_fd(int fd)
164{
165#if defined(HAVE_FSTAT)
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000166 struct stat buf;
167 if (!_PyVerify_fd(fd) || (fstat(fd, &buf) < 0 && errno == EBADF)) {
168 PyObject *exc;
169 char *msg = strerror(EBADF);
170 exc = PyObject_CallFunction(PyExc_OSError, "(is)",
171 EBADF, msg);
172 PyErr_SetObject(PyExc_OSError, exc);
173 Py_XDECREF(exc);
174 return -1;
175 }
Benjamin Peterson806d4022009-01-19 15:11:51 +0000176#endif
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000177 return 0;
Benjamin Peterson806d4022009-01-19 15:11:51 +0000178}
179
Guido van Rossuma9e20242007-03-08 00:43:48 +0000180
181static int
182fileio_init(PyObject *oself, PyObject *args, PyObject *kwds)
183{
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000184 fileio *self = (fileio *) oself;
185 static char *kwlist[] = {"file", "mode", "closefd", NULL};
186 const char *name = NULL;
187 PyObject *nameobj, *stringobj = NULL;
188 char *mode = "r";
189 char *s;
Thomas Helleraf2be262007-07-12 11:03:13 +0000190#ifdef MS_WINDOWS
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000191 Py_UNICODE *widename = NULL;
Thomas Helleraf2be262007-07-12 11:03:13 +0000192#endif
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000193 int ret = 0;
194 int rwa = 0, plus = 0, append = 0;
195 int flags = 0;
196 int fd = -1;
197 int closefd = 1;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000198
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000199 assert(PyFileIO_Check(oself));
200 if (self->fd >= 0) {
201 /* Have to close the existing file first. */
202 if (internal_close(self) < 0)
203 return -1;
204 }
Guido van Rossuma9e20242007-03-08 00:43:48 +0000205
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000206 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|si:fileio",
207 kwlist, &nameobj, &mode, &closefd))
208 return -1;
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000209
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000210 if (PyFloat_Check(nameobj)) {
211 PyErr_SetString(PyExc_TypeError,
212 "integer argument expected, got float");
213 return -1;
214 }
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000215
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000216 fd = PyLong_AsLong(nameobj);
217 if (fd < 0) {
218 if (!PyErr_Occurred()) {
219 PyErr_SetString(PyExc_ValueError,
220 "Negative filedescriptor");
221 return -1;
222 }
223 PyErr_Clear();
224 }
Guido van Rossumb0428152007-04-08 17:44:42 +0000225
Hirokazu Yamamoto8223c242009-05-17 04:21:53 +0000226#ifdef MS_WINDOWS
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000227 if (GetVersion() < 0x80000000) {
228 /* On NT, so wide API available */
229 if (PyUnicode_Check(nameobj))
230 widename = PyUnicode_AS_UNICODE(nameobj);
231 }
232 if (widename == NULL)
Guido van Rossuma9e20242007-03-08 00:43:48 +0000233#endif
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000234 if (fd < 0)
235 {
236 if (PyBytes_Check(nameobj) || PyByteArray_Check(nameobj)) {
237 Py_ssize_t namelen;
238 if (PyObject_AsCharBuffer(nameobj, &name, &namelen) < 0)
239 return -1;
240 }
241 else {
242 PyObject *u = PyUnicode_FromObject(nameobj);
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000243
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000244 if (u == NULL)
245 return -1;
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000246
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000247 stringobj = PyUnicode_AsEncodedString(
248 u, Py_FileSystemDefaultEncoding, "surrogateescape");
249 Py_DECREF(u);
250 if (stringobj == NULL)
251 return -1;
252 if (!PyBytes_Check(stringobj)) {
253 PyErr_SetString(PyExc_TypeError,
254 "encoder failed to return bytes");
255 goto error;
256 }
257 name = PyBytes_AS_STRING(stringobj);
258 }
259 }
Guido van Rossuma9e20242007-03-08 00:43:48 +0000260
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000261 s = mode;
262 while (*s) {
263 switch (*s++) {
264 case 'r':
265 if (rwa) {
266 bad_mode:
267 PyErr_SetString(PyExc_ValueError,
Georg Brandld62ecbf2010-11-26 08:52:36 +0000268 "Must have exactly one of read/write/append "
269 "mode and at most one plus");
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000270 goto error;
271 }
272 rwa = 1;
273 self->readable = 1;
274 break;
275 case 'w':
276 if (rwa)
277 goto bad_mode;
278 rwa = 1;
279 self->writable = 1;
280 flags |= O_CREAT | O_TRUNC;
281 break;
282 case 'a':
283 if (rwa)
284 goto bad_mode;
285 rwa = 1;
286 self->writable = 1;
287 flags |= O_CREAT;
288 append = 1;
289 break;
290 case 'b':
291 break;
292 case '+':
293 if (plus)
294 goto bad_mode;
295 self->readable = self->writable = 1;
296 plus = 1;
297 break;
298 default:
299 PyErr_Format(PyExc_ValueError,
300 "invalid mode: %.200s", mode);
301 goto error;
302 }
303 }
Guido van Rossuma9e20242007-03-08 00:43:48 +0000304
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000305 if (!rwa)
306 goto bad_mode;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000307
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000308 if (self->readable && self->writable)
309 flags |= O_RDWR;
310 else if (self->readable)
311 flags |= O_RDONLY;
312 else
313 flags |= O_WRONLY;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000314
315#ifdef O_BINARY
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000316 flags |= O_BINARY;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000317#endif
318
Walter Dörwald0e411482007-06-06 16:55:38 +0000319#ifdef O_APPEND
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000320 if (append)
321 flags |= O_APPEND;
Walter Dörwald0e411482007-06-06 16:55:38 +0000322#endif
323
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000324 if (fd >= 0) {
325 if (check_fd(fd))
326 goto error;
327 self->fd = fd;
328 self->closefd = closefd;
329 }
330 else {
331 self->closefd = 1;
332 if (!closefd) {
333 PyErr_SetString(PyExc_ValueError,
334 "Cannot use closefd=False with file name");
335 goto error;
336 }
Guido van Rossum2dced8b2007-10-30 17:27:30 +0000337
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000338 Py_BEGIN_ALLOW_THREADS
339 errno = 0;
Thomas Helleraf2be262007-07-12 11:03:13 +0000340#ifdef MS_WINDOWS
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000341 if (widename != NULL)
342 self->fd = _wopen(widename, flags, 0666);
343 else
Thomas Helleraf2be262007-07-12 11:03:13 +0000344#endif
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000345 self->fd = open(name, flags, 0666);
346 Py_END_ALLOW_THREADS
347 if (self->fd < 0) {
Christian Heimes0b489542007-10-31 19:20:48 +0000348#ifdef MS_WINDOWS
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000349 if (widename != NULL)
350 PyErr_SetFromErrnoWithUnicodeFilename(PyExc_IOError, widename);
351 else
Christian Heimes0b489542007-10-31 19:20:48 +0000352#endif
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000353 PyErr_SetFromErrnoWithFilename(PyExc_IOError, name);
354 goto error;
355 }
356 if(dircheck(self, name) < 0)
357 goto error;
358 }
Guido van Rossuma9e20242007-03-08 00:43:48 +0000359
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000360 if (PyObject_SetAttrString((PyObject *)self, "name", nameobj) < 0)
361 goto error;
Antoine Pitrou08838b62009-01-21 00:55:13 +0000362
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000363 if (append) {
364 /* For consistent behaviour, we explicitly seek to the
365 end of file (otherwise, it might be done only on the
366 first write()). */
367 PyObject *pos = portable_lseek(self->fd, NULL, 2);
Antoine Pitrou735e3b12010-10-31 13:05:21 +0000368 if (pos == NULL) {
369 if (closefd) {
370 close(self->fd);
371 self->fd = -1;
372 }
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000373 goto error;
Antoine Pitrou735e3b12010-10-31 13:05:21 +0000374 }
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000375 Py_DECREF(pos);
376 }
Antoine Pitrou7fb111b2009-03-04 11:14:01 +0000377
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000378 goto done;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000379
380 error:
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000381 ret = -1;
Guido van Rossum53807da2007-04-10 19:01:47 +0000382
Guido van Rossuma9e20242007-03-08 00:43:48 +0000383 done:
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000384 Py_CLEAR(stringobj);
385 return ret;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000386}
387
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000388static int
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000389fileio_traverse(fileio *self, visitproc visit, void *arg)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000390{
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000391 Py_VISIT(self->dict);
392 return 0;
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000393}
394
395static int
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000396fileio_clear(fileio *self)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000397{
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000398 Py_CLEAR(self->dict);
399 return 0;
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000400}
401
Guido van Rossuma9e20242007-03-08 00:43:48 +0000402static void
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000403fileio_dealloc(fileio *self)
Guido van Rossuma9e20242007-03-08 00:43:48 +0000404{
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000405 if (_PyIOBase_finalize((PyObject *) self) < 0)
406 return;
407 _PyObject_GC_UNTRACK(self);
408 if (self->weakreflist != NULL)
409 PyObject_ClearWeakRefs((PyObject *) self);
410 Py_CLEAR(self->dict);
411 Py_TYPE(self)->tp_free((PyObject *)self);
Guido van Rossuma9e20242007-03-08 00:43:48 +0000412}
413
414static PyObject *
415err_closed(void)
416{
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000417 PyErr_SetString(PyExc_ValueError, "I/O operation on closed file");
418 return NULL;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000419}
420
421static PyObject *
Guido van Rossum53807da2007-04-10 19:01:47 +0000422err_mode(char *action)
423{
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000424 PyErr_Format(PyExc_ValueError, "File not open for %s", action);
425 return NULL;
Guido van Rossum53807da2007-04-10 19:01:47 +0000426}
427
428static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000429fileio_fileno(fileio *self)
Guido van Rossuma9e20242007-03-08 00:43:48 +0000430{
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000431 if (self->fd < 0)
432 return err_closed();
433 return PyLong_FromLong((long) self->fd);
Guido van Rossuma9e20242007-03-08 00:43:48 +0000434}
435
436static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000437fileio_readable(fileio *self)
Guido van Rossuma9e20242007-03-08 00:43:48 +0000438{
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000439 if (self->fd < 0)
440 return err_closed();
441 return PyBool_FromLong((long) self->readable);
Guido van Rossuma9e20242007-03-08 00:43:48 +0000442}
443
444static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000445fileio_writable(fileio *self)
Guido van Rossuma9e20242007-03-08 00:43:48 +0000446{
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000447 if (self->fd < 0)
448 return err_closed();
449 return PyBool_FromLong((long) self->writable);
Guido van Rossuma9e20242007-03-08 00:43:48 +0000450}
451
452static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000453fileio_seekable(fileio *self)
Guido van Rossuma9e20242007-03-08 00:43:48 +0000454{
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000455 if (self->fd < 0)
456 return err_closed();
457 if (self->seekable < 0) {
458 PyObject *pos = portable_lseek(self->fd, NULL, SEEK_CUR);
459 if (pos == NULL) {
460 PyErr_Clear();
461 self->seekable = 0;
462 } else {
463 Py_DECREF(pos);
464 self->seekable = 1;
465 }
466 }
467 return PyBool_FromLong((long) self->seekable);
Guido van Rossuma9e20242007-03-08 00:43:48 +0000468}
469
470static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000471fileio_readinto(fileio *self, PyObject *args)
Guido van Rossuma9e20242007-03-08 00:43:48 +0000472{
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000473 Py_buffer pbuf;
474 Py_ssize_t n;
Guido van Rossum53807da2007-04-10 19:01:47 +0000475
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000476 if (self->fd < 0)
477 return err_closed();
478 if (!self->readable)
479 return err_mode("reading");
Guido van Rossum53807da2007-04-10 19:01:47 +0000480
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000481 if (!PyArg_ParseTuple(args, "w*", &pbuf))
482 return NULL;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000483
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000484 if (_PyVerify_fd(self->fd)) {
485 Py_BEGIN_ALLOW_THREADS
486 errno = 0;
487 n = read(self->fd, pbuf.buf, pbuf.len);
488 Py_END_ALLOW_THREADS
489 } else
490 n = -1;
491 PyBuffer_Release(&pbuf);
492 if (n < 0) {
493 if (errno == EAGAIN)
494 Py_RETURN_NONE;
495 PyErr_SetFromErrno(PyExc_IOError);
496 return NULL;
497 }
Guido van Rossuma9e20242007-03-08 00:43:48 +0000498
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000499 return PyLong_FromSsize_t(n);
Guido van Rossuma9e20242007-03-08 00:43:48 +0000500}
501
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000502static size_t
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000503new_buffersize(fileio *self, size_t currentsize)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000504{
505#ifdef HAVE_FSTAT
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000506 off_t pos, end;
507 struct stat st;
508 if (fstat(self->fd, &st) == 0) {
509 end = st.st_size;
510 pos = lseek(self->fd, 0L, SEEK_CUR);
511 /* Files claiming a size smaller than SMALLCHUNK may
512 actually be streaming pseudo-files. In this case, we
513 apply the more aggressive algorithm below.
514 */
515 if (end >= SMALLCHUNK && end >= pos && pos >= 0) {
516 /* Add 1 so if the file were to grow we'd notice. */
517 return currentsize + end - pos + 1;
518 }
519 }
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000520#endif
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000521 if (currentsize > SMALLCHUNK) {
522 /* Keep doubling until we reach BIGCHUNK;
523 then keep adding BIGCHUNK. */
524 if (currentsize <= BIGCHUNK)
525 return currentsize + currentsize;
526 else
527 return currentsize + BIGCHUNK;
528 }
529 return currentsize + SMALLCHUNK;
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000530}
531
Guido van Rossum7165cb12007-07-10 06:54:34 +0000532static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000533fileio_readall(fileio *self)
Guido van Rossum7165cb12007-07-10 06:54:34 +0000534{
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000535 PyObject *result;
536 Py_ssize_t total = 0;
537 int n;
Guido van Rossum7165cb12007-07-10 06:54:34 +0000538
Victor Stinnerb79f28c2011-05-25 22:09:03 +0200539 if (self->fd < 0)
540 return err_closed();
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000541 if (!_PyVerify_fd(self->fd))
542 return PyErr_SetFromErrno(PyExc_IOError);
Kristján Valur Jónssona8abe862009-03-24 15:27:42 +0000543
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000544 result = PyBytes_FromStringAndSize(NULL, SMALLCHUNK);
545 if (result == NULL)
546 return NULL;
Guido van Rossum7165cb12007-07-10 06:54:34 +0000547
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000548 while (1) {
549 size_t newsize = new_buffersize(self, total);
550 if (newsize > PY_SSIZE_T_MAX || newsize <= 0) {
551 PyErr_SetString(PyExc_OverflowError,
552 "unbounded read returned more bytes "
553 "than a Python string can hold ");
554 Py_DECREF(result);
555 return NULL;
556 }
Christian Heimesa872de52008-12-05 08:26:55 +0000557
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000558 if (PyBytes_GET_SIZE(result) < (Py_ssize_t)newsize) {
559 if (_PyBytes_Resize(&result, newsize) < 0) {
560 if (total == 0) {
561 Py_DECREF(result);
562 return NULL;
563 }
564 PyErr_Clear();
565 break;
566 }
567 }
568 Py_BEGIN_ALLOW_THREADS
569 errno = 0;
570 n = read(self->fd,
571 PyBytes_AS_STRING(result) + total,
572 newsize - total);
573 Py_END_ALLOW_THREADS
574 if (n == 0)
575 break;
576 if (n < 0) {
577 if (total > 0)
578 break;
579 if (errno == EAGAIN) {
580 Py_DECREF(result);
581 Py_RETURN_NONE;
582 }
583 Py_DECREF(result);
584 PyErr_SetFromErrno(PyExc_IOError);
585 return NULL;
586 }
587 total += n;
588 }
Guido van Rossum7165cb12007-07-10 06:54:34 +0000589
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000590 if (PyBytes_GET_SIZE(result) > total) {
591 if (_PyBytes_Resize(&result, total) < 0) {
592 /* This should never happen, but just in case */
593 Py_DECREF(result);
594 return NULL;
595 }
596 }
597 return result;
Guido van Rossum7165cb12007-07-10 06:54:34 +0000598}
599
Guido van Rossuma9e20242007-03-08 00:43:48 +0000600static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000601fileio_read(fileio *self, PyObject *args)
Guido van Rossuma9e20242007-03-08 00:43:48 +0000602{
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000603 char *ptr;
604 Py_ssize_t n;
605 Py_ssize_t size = -1;
606 PyObject *bytes;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000607
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000608 if (self->fd < 0)
609 return err_closed();
610 if (!self->readable)
611 return err_mode("reading");
Guido van Rossuma9e20242007-03-08 00:43:48 +0000612
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000613 if (!PyArg_ParseTuple(args, "|O&", &_PyIO_ConvertSsize_t, &size))
614 return NULL;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000615
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000616 if (size < 0) {
617 return fileio_readall(self);
618 }
Guido van Rossumc2f93dc2007-05-24 00:50:02 +0000619
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000620 bytes = PyBytes_FromStringAndSize(NULL, size);
621 if (bytes == NULL)
622 return NULL;
623 ptr = PyBytes_AS_STRING(bytes);
Guido van Rossuma9e20242007-03-08 00:43:48 +0000624
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000625 if (_PyVerify_fd(self->fd)) {
626 Py_BEGIN_ALLOW_THREADS
627 errno = 0;
628 n = read(self->fd, ptr, size);
629 Py_END_ALLOW_THREADS
630 } else
631 n = -1;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000632
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000633 if (n < 0) {
634 Py_DECREF(bytes);
635 if (errno == EAGAIN)
636 Py_RETURN_NONE;
637 PyErr_SetFromErrno(PyExc_IOError);
638 return NULL;
639 }
Guido van Rossuma9e20242007-03-08 00:43:48 +0000640
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000641 if (n != size) {
642 if (_PyBytes_Resize(&bytes, n) < 0) {
643 Py_DECREF(bytes);
644 return NULL;
645 }
646 }
Guido van Rossuma9e20242007-03-08 00:43:48 +0000647
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000648 return (PyObject *) bytes;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000649}
650
651static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000652fileio_write(fileio *self, PyObject *args)
Guido van Rossuma9e20242007-03-08 00:43:48 +0000653{
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000654 Py_buffer pbuf;
655 Py_ssize_t n;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000656
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000657 if (self->fd < 0)
658 return err_closed();
659 if (!self->writable)
660 return err_mode("writing");
Guido van Rossum53807da2007-04-10 19:01:47 +0000661
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000662 if (!PyArg_ParseTuple(args, "y*", &pbuf))
663 return NULL;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000664
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000665 if (_PyVerify_fd(self->fd)) {
666 Py_BEGIN_ALLOW_THREADS
667 errno = 0;
668 n = write(self->fd, pbuf.buf, pbuf.len);
669 Py_END_ALLOW_THREADS
670 } else
671 n = -1;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000672
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000673 PyBuffer_Release(&pbuf);
Martin v. Löwis423be952008-08-13 15:53:07 +0000674
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000675 if (n < 0) {
676 if (errno == EAGAIN)
677 Py_RETURN_NONE;
678 PyErr_SetFromErrno(PyExc_IOError);
679 return NULL;
680 }
Guido van Rossuma9e20242007-03-08 00:43:48 +0000681
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000682 return PyLong_FromSsize_t(n);
Guido van Rossuma9e20242007-03-08 00:43:48 +0000683}
684
Guido van Rossum53807da2007-04-10 19:01:47 +0000685/* XXX Windows support below is likely incomplete */
686
Guido van Rossum53807da2007-04-10 19:01:47 +0000687/* Cribbed from posix_lseek() */
688static PyObject *
689portable_lseek(int fd, PyObject *posobj, int whence)
690{
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000691 Py_off_t pos, res;
Guido van Rossum53807da2007-04-10 19:01:47 +0000692
693#ifdef SEEK_SET
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000694 /* Turn 0, 1, 2 into SEEK_{SET,CUR,END} */
695 switch (whence) {
Guido van Rossum53807da2007-04-10 19:01:47 +0000696#if SEEK_SET != 0
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000697 case 0: whence = SEEK_SET; break;
Guido van Rossum53807da2007-04-10 19:01:47 +0000698#endif
699#if SEEK_CUR != 1
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000700 case 1: whence = SEEK_CUR; break;
Guido van Rossum53807da2007-04-10 19:01:47 +0000701#endif
Antoine Pitrou4f7945f2009-01-20 11:42:11 +0000702#if SEEK_END != 2
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000703 case 2: whence = SEEK_END; break;
Guido van Rossum53807da2007-04-10 19:01:47 +0000704#endif
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000705 }
Guido van Rossum53807da2007-04-10 19:01:47 +0000706#endif /* SEEK_SET */
707
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000708 if (posobj == NULL)
709 pos = 0;
710 else {
711 if(PyFloat_Check(posobj)) {
712 PyErr_SetString(PyExc_TypeError, "an integer is required");
713 return NULL;
714 }
Alexandre Vassalotti77250f42008-05-06 19:48:38 +0000715#if defined(HAVE_LARGEFILE_SUPPORT)
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000716 pos = PyLong_AsLongLong(posobj);
Guido van Rossum53807da2007-04-10 19:01:47 +0000717#else
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000718 pos = PyLong_AsLong(posobj);
Guido van Rossum53807da2007-04-10 19:01:47 +0000719#endif
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000720 if (PyErr_Occurred())
721 return NULL;
722 }
Guido van Rossum53807da2007-04-10 19:01:47 +0000723
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000724 if (_PyVerify_fd(fd)) {
725 Py_BEGIN_ALLOW_THREADS
Guido van Rossum53807da2007-04-10 19:01:47 +0000726#if defined(MS_WIN64) || defined(MS_WINDOWS)
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000727 res = _lseeki64(fd, pos, whence);
Guido van Rossum53807da2007-04-10 19:01:47 +0000728#else
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000729 res = lseek(fd, pos, whence);
Guido van Rossum53807da2007-04-10 19:01:47 +0000730#endif
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000731 Py_END_ALLOW_THREADS
732 } else
733 res = -1;
734 if (res < 0)
735 return PyErr_SetFromErrno(PyExc_IOError);
Guido van Rossum53807da2007-04-10 19:01:47 +0000736
Alexandre Vassalotti77250f42008-05-06 19:48:38 +0000737#if defined(HAVE_LARGEFILE_SUPPORT)
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000738 return PyLong_FromLongLong(res);
Alexandre Vassalotti77250f42008-05-06 19:48:38 +0000739#else
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000740 return PyLong_FromLong(res);
Guido van Rossum53807da2007-04-10 19:01:47 +0000741#endif
742}
743
Guido van Rossuma9e20242007-03-08 00:43:48 +0000744static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000745fileio_seek(fileio *self, PyObject *args)
Guido van Rossuma9e20242007-03-08 00:43:48 +0000746{
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000747 PyObject *posobj;
748 int whence = 0;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000749
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000750 if (self->fd < 0)
751 return err_closed();
Guido van Rossuma9e20242007-03-08 00:43:48 +0000752
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000753 if (!PyArg_ParseTuple(args, "O|i", &posobj, &whence))
754 return NULL;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000755
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000756 return portable_lseek(self->fd, posobj, whence);
Guido van Rossuma9e20242007-03-08 00:43:48 +0000757}
758
759static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000760fileio_tell(fileio *self, PyObject *args)
Guido van Rossuma9e20242007-03-08 00:43:48 +0000761{
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000762 if (self->fd < 0)
763 return err_closed();
Guido van Rossuma9e20242007-03-08 00:43:48 +0000764
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000765 return portable_lseek(self->fd, NULL, 1);
Guido van Rossuma9e20242007-03-08 00:43:48 +0000766}
767
Thomas Hellerc6a55ee2007-07-11 12:45:46 +0000768#ifdef HAVE_FTRUNCATE
Guido van Rossuma9e20242007-03-08 00:43:48 +0000769static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000770fileio_truncate(fileio *self, PyObject *args)
Guido van Rossuma9e20242007-03-08 00:43:48 +0000771{
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000772 PyObject *posobj = NULL; /* the new size wanted by the user */
Antoine Pitrou66f9fea2010-01-31 23:20:26 +0000773#ifndef MS_WINDOWS
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000774 Py_off_t pos;
Antoine Pitrou66f9fea2010-01-31 23:20:26 +0000775#endif
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000776 int ret;
777 int fd;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000778
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000779 fd = self->fd;
780 if (fd < 0)
781 return err_closed();
782 if (!self->writable)
783 return err_mode("writing");
Guido van Rossuma9e20242007-03-08 00:43:48 +0000784
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000785 if (!PyArg_ParseTuple(args, "|O", &posobj))
786 return NULL;
Guido van Rossum53807da2007-04-10 19:01:47 +0000787
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000788 if (posobj == Py_None || posobj == NULL) {
789 /* Get the current position. */
790 posobj = portable_lseek(fd, NULL, 1);
791 if (posobj == NULL)
792 return NULL;
793 }
794 else {
795 Py_INCREF(posobj);
796 }
Guido van Rossum53807da2007-04-10 19:01:47 +0000797
Thomas Hellerfdeee3a2007-07-12 11:21:36 +0000798#ifdef MS_WINDOWS
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000799 /* MS _chsize doesn't work if newsize doesn't fit in 32 bits,
800 so don't even try using it. */
801 {
802 PyObject *oldposobj, *tempposobj;
803 HANDLE hFile;
Antoine Pitrou66f9fea2010-01-31 23:20:26 +0000804
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000805 /* we save the file pointer position */
806 oldposobj = portable_lseek(fd, NULL, 1);
807 if (oldposobj == NULL) {
808 Py_DECREF(posobj);
809 return NULL;
810 }
Thomas Hellerfdeee3a2007-07-12 11:21:36 +0000811
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000812 /* we then move to the truncation position */
813 tempposobj = portable_lseek(fd, posobj, 0);
814 if (tempposobj == NULL) {
815 Py_DECREF(oldposobj);
816 Py_DECREF(posobj);
817 return NULL;
818 }
819 Py_DECREF(tempposobj);
Antoine Pitrou66f9fea2010-01-31 23:20:26 +0000820
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000821 /* Truncate. Note that this may grow the file! */
822 Py_BEGIN_ALLOW_THREADS
823 errno = 0;
824 hFile = (HANDLE)_get_osfhandle(fd);
825 ret = hFile == (HANDLE)-1; /* testing for INVALID_HANDLE value */
826 if (ret == 0) {
827 ret = SetEndOfFile(hFile) == 0;
828 if (ret)
829 errno = EACCES;
830 }
831 Py_END_ALLOW_THREADS
832
833 /* we restore the file pointer position in any case */
834 tempposobj = portable_lseek(fd, oldposobj, 0);
835 Py_DECREF(oldposobj);
836 if (tempposobj == NULL) {
837 Py_DECREF(posobj);
838 return NULL;
839 }
840 Py_DECREF(tempposobj);
841 }
Thomas Hellerfdeee3a2007-07-12 11:21:36 +0000842#else
Antoine Pitrou66f9fea2010-01-31 23:20:26 +0000843
844#if defined(HAVE_LARGEFILE_SUPPORT)
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000845 pos = PyLong_AsLongLong(posobj);
Antoine Pitrou66f9fea2010-01-31 23:20:26 +0000846#else
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000847 pos = PyLong_AsLong(posobj);
Antoine Pitrou66f9fea2010-01-31 23:20:26 +0000848#endif
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000849 if (PyErr_Occurred()){
850 Py_DECREF(posobj);
851 return NULL;
852 }
Antoine Pitrou66f9fea2010-01-31 23:20:26 +0000853
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000854 Py_BEGIN_ALLOW_THREADS
855 errno = 0;
856 ret = ftruncate(fd, pos);
857 Py_END_ALLOW_THREADS
Antoine Pitrou66f9fea2010-01-31 23:20:26 +0000858
Thomas Hellerfdeee3a2007-07-12 11:21:36 +0000859#endif /* !MS_WINDOWS */
Guido van Rossuma9e20242007-03-08 00:43:48 +0000860
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000861 if (ret != 0) {
862 Py_DECREF(posobj);
863 PyErr_SetFromErrno(PyExc_IOError);
864 return NULL;
865 }
Guido van Rossuma9e20242007-03-08 00:43:48 +0000866
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000867 return posobj;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000868}
Antoine Pitrou66f9fea2010-01-31 23:20:26 +0000869#endif /* HAVE_FTRUNCATE */
Guido van Rossum53807da2007-04-10 19:01:47 +0000870
871static char *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000872mode_string(fileio *self)
Guido van Rossum53807da2007-04-10 19:01:47 +0000873{
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000874 if (self->readable) {
875 if (self->writable)
876 return "rb+";
877 else
878 return "rb";
879 }
880 else
881 return "wb";
Guido van Rossum53807da2007-04-10 19:01:47 +0000882}
Guido van Rossuma9e20242007-03-08 00:43:48 +0000883
884static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000885fileio_repr(fileio *self)
Guido van Rossuma9e20242007-03-08 00:43:48 +0000886{
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000887 PyObject *nameobj, *res;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000888
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000889 if (self->fd < 0)
890 return PyUnicode_FromFormat("<_io.FileIO [closed]>");
Antoine Pitrou716c4442009-05-23 19:04:03 +0000891
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000892 nameobj = PyObject_GetAttrString((PyObject *) self, "name");
893 if (nameobj == NULL) {
894 if (PyErr_ExceptionMatches(PyExc_AttributeError))
895 PyErr_Clear();
896 else
897 return NULL;
898 res = PyUnicode_FromFormat("<_io.FileIO fd=%d mode='%s'>",
899 self->fd, mode_string(self));
900 }
901 else {
902 res = PyUnicode_FromFormat("<_io.FileIO name=%R mode='%s'>",
903 nameobj, mode_string(self));
904 Py_DECREF(nameobj);
905 }
906 return res;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000907}
908
909static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000910fileio_isatty(fileio *self)
Guido van Rossuma9e20242007-03-08 00:43:48 +0000911{
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000912 long res;
Guido van Rossum53807da2007-04-10 19:01:47 +0000913
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000914 if (self->fd < 0)
915 return err_closed();
916 Py_BEGIN_ALLOW_THREADS
917 res = isatty(self->fd);
918 Py_END_ALLOW_THREADS
919 return PyBool_FromLong(res);
Guido van Rossuma9e20242007-03-08 00:43:48 +0000920}
921
Guido van Rossuma9e20242007-03-08 00:43:48 +0000922
923PyDoc_STRVAR(fileio_doc,
924"file(name: str[, mode: str]) -> file IO object\n"
925"\n"
926"Open a file. The mode can be 'r', 'w' or 'a' for reading (default),\n"
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000927"writing or appending. The file will be created if it doesn't exist\n"
Guido van Rossuma9e20242007-03-08 00:43:48 +0000928"when opened for writing or appending; it will be truncated when\n"
929"opened for writing. Add a '+' to the mode to allow simultaneous\n"
930"reading and writing.");
931
932PyDoc_STRVAR(read_doc,
933"read(size: int) -> bytes. read at most size bytes, returned as bytes.\n"
934"\n"
935"Only makes one system call, so less data may be returned than requested\n"
Guido van Rossum7165cb12007-07-10 06:54:34 +0000936"In non-blocking mode, returns None if no data is available.\n"
937"On end-of-file, returns ''.");
938
939PyDoc_STRVAR(readall_doc,
940"readall() -> bytes. read all data from the file, returned as bytes.\n"
941"\n"
942"In non-blocking mode, returns as much as is immediately available,\n"
943"or None if no data is available. On end-of-file, returns ''.");
Guido van Rossuma9e20242007-03-08 00:43:48 +0000944
945PyDoc_STRVAR(write_doc,
946"write(b: bytes) -> int. Write bytes b to file, return number written.\n"
947"\n"
948"Only makes one system call, so not all of the data may be written.\n"
949"The number of bytes actually written is returned.");
950
951PyDoc_STRVAR(fileno_doc,
952"fileno() -> int. \"file descriptor\".\n"
953"\n"
954"This is needed for lower-level file interfaces, such the fcntl module.");
955
956PyDoc_STRVAR(seek_doc,
957"seek(offset: int[, whence: int]) -> None. Move to new file position.\n"
958"\n"
959"Argument offset is a byte count. Optional argument whence defaults to\n"
960"0 (offset from start of file, offset should be >= 0); other values are 1\n"
961"(move relative to current position, positive or negative), and 2 (move\n"
962"relative to end of file, usually negative, although many platforms allow\n"
963"seeking beyond the end of a file)."
964"\n"
965"Note that not all file objects are seekable.");
966
Thomas Hellerc6a55ee2007-07-11 12:45:46 +0000967#ifdef HAVE_FTRUNCATE
Guido van Rossuma9e20242007-03-08 00:43:48 +0000968PyDoc_STRVAR(truncate_doc,
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000969"truncate([size: int]) -> None. Truncate the file to at most size bytes.\n"
Guido van Rossuma9e20242007-03-08 00:43:48 +0000970"\n"
Alexandre Vassalotti77250f42008-05-06 19:48:38 +0000971"Size defaults to the current file position, as returned by tell()."
972"The current file position is changed to the value of size.");
Thomas Hellerc6a55ee2007-07-11 12:45:46 +0000973#endif
Guido van Rossuma9e20242007-03-08 00:43:48 +0000974
975PyDoc_STRVAR(tell_doc,
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000976"tell() -> int. Current file position");
Guido van Rossuma9e20242007-03-08 00:43:48 +0000977
978PyDoc_STRVAR(readinto_doc,
Benjamin Peterson9a8082f2009-03-05 00:55:56 +0000979"readinto() -> Same as RawIOBase.readinto().");
Guido van Rossuma9e20242007-03-08 00:43:48 +0000980
981PyDoc_STRVAR(close_doc,
982"close() -> None. Close the file.\n"
983"\n"
984"A closed file cannot be used for further I/O operations. close() may be\n"
985"called more than once without error. Changes the fileno to -1.");
986
987PyDoc_STRVAR(isatty_doc,
988"isatty() -> bool. True if the file is connected to a tty device.");
989
Guido van Rossuma9e20242007-03-08 00:43:48 +0000990PyDoc_STRVAR(seekable_doc,
991"seekable() -> bool. True if file supports random-access.");
992
993PyDoc_STRVAR(readable_doc,
994"readable() -> bool. True if file was opened in a read mode.");
995
996PyDoc_STRVAR(writable_doc,
997"writable() -> bool. True if file was opened in a write mode.");
998
999static PyMethodDef fileio_methods[] = {
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +00001000 {"read", (PyCFunction)fileio_read, METH_VARARGS, read_doc},
1001 {"readall", (PyCFunction)fileio_readall, METH_NOARGS, readall_doc},
1002 {"readinto", (PyCFunction)fileio_readinto, METH_VARARGS, readinto_doc},
1003 {"write", (PyCFunction)fileio_write, METH_VARARGS, write_doc},
1004 {"seek", (PyCFunction)fileio_seek, METH_VARARGS, seek_doc},
1005 {"tell", (PyCFunction)fileio_tell, METH_VARARGS, tell_doc},
Thomas Hellerc6a55ee2007-07-11 12:45:46 +00001006#ifdef HAVE_FTRUNCATE
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +00001007 {"truncate", (PyCFunction)fileio_truncate, METH_VARARGS, truncate_doc},
Thomas Hellerc6a55ee2007-07-11 12:45:46 +00001008#endif
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +00001009 {"close", (PyCFunction)fileio_close, METH_NOARGS, close_doc},
1010 {"seekable", (PyCFunction)fileio_seekable, METH_NOARGS, seekable_doc},
1011 {"readable", (PyCFunction)fileio_readable, METH_NOARGS, readable_doc},
1012 {"writable", (PyCFunction)fileio_writable, METH_NOARGS, writable_doc},
1013 {"fileno", (PyCFunction)fileio_fileno, METH_NOARGS, fileno_doc},
1014 {"isatty", (PyCFunction)fileio_isatty, METH_NOARGS, isatty_doc},
1015 {NULL, NULL} /* sentinel */
Guido van Rossuma9e20242007-03-08 00:43:48 +00001016};
1017
Guido van Rossum53807da2007-04-10 19:01:47 +00001018/* 'closed' and 'mode' are attributes for backwards compatibility reasons. */
1019
Guido van Rossumb0428152007-04-08 17:44:42 +00001020static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +00001021get_closed(fileio *self, void *closure)
Guido van Rossumb0428152007-04-08 17:44:42 +00001022{
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +00001023 return PyBool_FromLong((long)(self->fd < 0));
Guido van Rossum53807da2007-04-10 19:01:47 +00001024}
1025
1026static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +00001027get_closefd(fileio *self, void *closure)
Christian Heimesecc42a22008-11-05 19:30:32 +00001028{
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +00001029 return PyBool_FromLong((long)(self->closefd));
Christian Heimesecc42a22008-11-05 19:30:32 +00001030}
1031
1032static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +00001033get_mode(fileio *self, void *closure)
Guido van Rossum53807da2007-04-10 19:01:47 +00001034{
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +00001035 return PyUnicode_FromString(mode_string(self));
Guido van Rossumb0428152007-04-08 17:44:42 +00001036}
1037
1038static PyGetSetDef fileio_getsetlist[] = {
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +00001039 {"closed", (getter)get_closed, NULL, "True if the file is closed"},
1040 {"closefd", (getter)get_closefd, NULL,
1041 "True if the file descriptor will be closed"},
1042 {"mode", (getter)get_mode, NULL, "String giving the file mode"},
1043 {NULL},
Guido van Rossumb0428152007-04-08 17:44:42 +00001044};
1045
Guido van Rossuma9e20242007-03-08 00:43:48 +00001046PyTypeObject PyFileIO_Type = {
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +00001047 PyVarObject_HEAD_INIT(NULL, 0)
1048 "_io.FileIO",
1049 sizeof(fileio),
1050 0,
1051 (destructor)fileio_dealloc, /* tp_dealloc */
1052 0, /* tp_print */
1053 0, /* tp_getattr */
1054 0, /* tp_setattr */
1055 0, /* tp_reserved */
1056 (reprfunc)fileio_repr, /* tp_repr */
1057 0, /* tp_as_number */
1058 0, /* tp_as_sequence */
1059 0, /* tp_as_mapping */
1060 0, /* tp_hash */
1061 0, /* tp_call */
1062 0, /* tp_str */
1063 PyObject_GenericGetAttr, /* tp_getattro */
1064 0, /* tp_setattro */
1065 0, /* tp_as_buffer */
1066 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE
1067 | Py_TPFLAGS_HAVE_GC, /* tp_flags */
1068 fileio_doc, /* tp_doc */
1069 (traverseproc)fileio_traverse, /* tp_traverse */
1070 (inquiry)fileio_clear, /* tp_clear */
1071 0, /* tp_richcompare */
1072 offsetof(fileio, weakreflist), /* tp_weaklistoffset */
1073 0, /* tp_iter */
1074 0, /* tp_iternext */
1075 fileio_methods, /* tp_methods */
1076 0, /* tp_members */
1077 fileio_getsetlist, /* tp_getset */
1078 0, /* tp_base */
1079 0, /* tp_dict */
1080 0, /* tp_descr_get */
1081 0, /* tp_descr_set */
1082 offsetof(fileio, dict), /* tp_dictoffset */
1083 fileio_init, /* tp_init */
1084 PyType_GenericAlloc, /* tp_alloc */
1085 fileio_new, /* tp_new */
1086 PyObject_GC_Del, /* tp_free */
Guido van Rossuma9e20242007-03-08 00:43:48 +00001087};