blob: b3b9e44c29d530e201cdf1d57616249f37115e52 [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
46#if SIZEOF_INT < 4
47#define BIGCHUNK (512 * 32)
48#else
49#define BIGCHUNK (512 * 1024)
50#endif
51
Guido van Rossuma9e20242007-03-08 00:43:48 +000052typedef struct {
Antoine Pitrouae4b4722010-05-05 16:31:07 +000053 PyObject_HEAD
54 int fd;
55 unsigned int readable : 1;
56 unsigned int writable : 1;
57 signed int seekable : 2; /* -1 means unknown */
58 unsigned int closefd : 1;
Antoine Pitroue033e062010-10-29 10:38:18 +000059 unsigned int deallocating: 1;
Antoine Pitrouae4b4722010-05-05 16:31:07 +000060 PyObject *weakreflist;
61 PyObject *dict;
Benjamin Peterson680bf1a2009-06-12 02:07:12 +000062} fileio;
Guido van Rossuma9e20242007-03-08 00:43:48 +000063
Collin Winteraf334382007-03-08 21:46:15 +000064PyTypeObject PyFileIO_Type;
65
Guido van Rossuma9e20242007-03-08 00:43:48 +000066#define PyFileIO_Check(op) (PyObject_TypeCheck((op), &PyFileIO_Type))
67
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +000068int
69_PyFileIO_closed(PyObject *self)
70{
Antoine Pitrouae4b4722010-05-05 16:31:07 +000071 return ((fileio *)self)->fd < 0;
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +000072}
Antoine Pitrou08838b62009-01-21 00:55:13 +000073
Antoine Pitroue033e062010-10-29 10:38:18 +000074/* Because this can call arbitrary code, it shouldn't be called when
75 the refcount is 0 (that is, not directly from tp_dealloc unless
76 the refcount has been temporarily re-incremented). */
77static PyObject *
78fileio_dealloc_warn(fileio *self, PyObject *source)
79{
80 if (self->fd >= 0 && self->closefd) {
81 PyObject *exc, *val, *tb;
82 PyErr_Fetch(&exc, &val, &tb);
83 if (PyErr_WarnFormat(PyExc_ResourceWarning, 1,
84 "unclosed file %R", source)) {
85 /* Spurious errors can appear at shutdown */
86 if (PyErr_ExceptionMatches(PyExc_Warning))
87 PyErr_WriteUnraisable((PyObject *) self);
88 }
89 PyErr_Restore(exc, val, tb);
90 }
91 Py_RETURN_NONE;
92}
93
Antoine Pitrou7fb111b2009-03-04 11:14:01 +000094static PyObject *
95portable_lseek(int fd, PyObject *posobj, int whence);
96
Antoine Pitroua28fcfd2009-03-13 23:42:55 +000097static PyObject *portable_lseek(int fd, PyObject *posobj, int whence);
98
Kristján Valur Jónsson19288c22008-12-18 17:15:54 +000099/* Returns 0 on success, -1 with exception set on failure. */
Neal Norwitz88b44da2007-08-12 17:23:54 +0000100static int
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000101internal_close(fileio *self)
Guido van Rossuma9e20242007-03-08 00:43:48 +0000102{
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000103 int err = 0;
104 int save_errno = 0;
105 if (self->fd >= 0) {
106 int fd = self->fd;
107 self->fd = -1;
108 /* fd is accessible and someone else may have closed it */
109 if (_PyVerify_fd(fd)) {
110 Py_BEGIN_ALLOW_THREADS
111 err = close(fd);
112 if (err < 0)
113 save_errno = errno;
114 Py_END_ALLOW_THREADS
115 } else {
116 save_errno = errno;
117 err = -1;
118 }
119 }
120 if (err < 0) {
121 errno = save_errno;
122 PyErr_SetFromErrno(PyExc_IOError);
123 return -1;
124 }
125 return 0;
Neal Norwitz88b44da2007-08-12 17:23:54 +0000126}
127
128static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000129fileio_close(fileio *self)
Neal Norwitz88b44da2007-08-12 17:23:54 +0000130{
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000131 if (!self->closefd) {
132 self->fd = -1;
133 Py_RETURN_NONE;
134 }
Antoine Pitroue033e062010-10-29 10:38:18 +0000135 if (self->deallocating) {
136 PyObject *r = fileio_dealloc_warn(self, (PyObject *) self);
137 if (r)
138 Py_DECREF(r);
139 else
140 PyErr_Clear();
141 }
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000142 errno = internal_close(self);
143 if (errno < 0)
144 return NULL;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000145
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000146 return PyObject_CallMethod((PyObject*)&PyRawIOBase_Type,
147 "close", "O", self);
Guido van Rossuma9e20242007-03-08 00:43:48 +0000148}
149
150static PyObject *
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000151fileio_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
Guido van Rossuma9e20242007-03-08 00:43:48 +0000152{
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000153 fileio *self;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000154
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000155 assert(type != NULL && type->tp_alloc != NULL);
Guido van Rossuma9e20242007-03-08 00:43:48 +0000156
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000157 self = (fileio *) type->tp_alloc(type, 0);
158 if (self != NULL) {
159 self->fd = -1;
160 self->readable = 0;
161 self->writable = 0;
162 self->seekable = -1;
163 self->closefd = 1;
164 self->weakreflist = NULL;
165 }
Guido van Rossuma9e20242007-03-08 00:43:48 +0000166
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000167 return (PyObject *) self;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000168}
169
170/* On Unix, open will succeed for directories.
171 In Python, there should be no file objects referring to
172 directories, so we need a check. */
173
174static int
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000175dircheck(fileio* self, const char *name)
Guido van Rossuma9e20242007-03-08 00:43:48 +0000176{
177#if defined(HAVE_FSTAT) && defined(S_IFDIR) && defined(EISDIR)
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000178 struct stat buf;
179 if (self->fd < 0)
180 return 0;
181 if (fstat(self->fd, &buf) == 0 && S_ISDIR(buf.st_mode)) {
182 char *msg = strerror(EISDIR);
183 PyObject *exc;
184 if (internal_close(self))
185 return -1;
Guido van Rossum53807da2007-04-10 19:01:47 +0000186
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000187 exc = PyObject_CallFunction(PyExc_IOError, "(iss)",
188 EISDIR, msg, name);
189 PyErr_SetObject(PyExc_IOError, exc);
190 Py_XDECREF(exc);
191 return -1;
192 }
Guido van Rossuma9e20242007-03-08 00:43:48 +0000193#endif
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000194 return 0;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000195}
196
Benjamin Peterson806d4022009-01-19 15:11:51 +0000197static int
198check_fd(int fd)
199{
200#if defined(HAVE_FSTAT)
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000201 struct stat buf;
202 if (!_PyVerify_fd(fd) || (fstat(fd, &buf) < 0 && errno == EBADF)) {
203 PyObject *exc;
204 char *msg = strerror(EBADF);
205 exc = PyObject_CallFunction(PyExc_OSError, "(is)",
206 EBADF, msg);
207 PyErr_SetObject(PyExc_OSError, exc);
208 Py_XDECREF(exc);
209 return -1;
210 }
Benjamin Peterson806d4022009-01-19 15:11:51 +0000211#endif
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000212 return 0;
Benjamin Peterson806d4022009-01-19 15:11:51 +0000213}
214
Guido van Rossuma9e20242007-03-08 00:43:48 +0000215
216static int
217fileio_init(PyObject *oself, PyObject *args, PyObject *kwds)
218{
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000219 fileio *self = (fileio *) oself;
220 static char *kwlist[] = {"file", "mode", "closefd", NULL};
221 const char *name = NULL;
222 PyObject *nameobj, *stringobj = NULL;
223 char *mode = "r";
224 char *s;
Thomas Helleraf2be262007-07-12 11:03:13 +0000225#ifdef MS_WINDOWS
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000226 Py_UNICODE *widename = NULL;
Thomas Helleraf2be262007-07-12 11:03:13 +0000227#endif
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000228 int ret = 0;
229 int rwa = 0, plus = 0, append = 0;
230 int flags = 0;
231 int fd = -1;
232 int closefd = 1;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000233
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000234 assert(PyFileIO_Check(oself));
235 if (self->fd >= 0) {
236 /* Have to close the existing file first. */
237 if (internal_close(self) < 0)
238 return -1;
239 }
Guido van Rossuma9e20242007-03-08 00:43:48 +0000240
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000241 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|si:fileio",
242 kwlist, &nameobj, &mode, &closefd))
243 return -1;
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000244
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000245 if (PyFloat_Check(nameobj)) {
246 PyErr_SetString(PyExc_TypeError,
247 "integer argument expected, got float");
248 return -1;
249 }
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000250
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000251 fd = PyLong_AsLong(nameobj);
252 if (fd < 0) {
253 if (!PyErr_Occurred()) {
254 PyErr_SetString(PyExc_ValueError,
255 "Negative filedescriptor");
256 return -1;
257 }
258 PyErr_Clear();
259 }
Guido van Rossumb0428152007-04-08 17:44:42 +0000260
Hirokazu Yamamoto8223c242009-05-17 04:21:53 +0000261#ifdef MS_WINDOWS
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000262 if (PyUnicode_Check(nameobj))
263 widename = PyUnicode_AS_UNICODE(nameobj);
264 if (widename == NULL)
Guido van Rossuma9e20242007-03-08 00:43:48 +0000265#endif
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000266 if (fd < 0)
267 {
268 if (PyBytes_Check(nameobj) || PyByteArray_Check(nameobj)) {
269 Py_ssize_t namelen;
270 if (PyObject_AsCharBuffer(nameobj, &name, &namelen) < 0)
271 return -1;
272 }
273 else {
274 PyObject *u = PyUnicode_FromObject(nameobj);
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000275
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000276 if (u == NULL)
277 return -1;
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000278
Victor Stinnerae6265f2010-05-15 16:27:27 +0000279 stringobj = PyUnicode_EncodeFSDefault(u);
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000280 Py_DECREF(u);
281 if (stringobj == NULL)
282 return -1;
283 if (!PyBytes_Check(stringobj)) {
284 PyErr_SetString(PyExc_TypeError,
285 "encoder failed to return bytes");
286 goto error;
287 }
288 name = PyBytes_AS_STRING(stringobj);
289 }
290 }
Guido van Rossuma9e20242007-03-08 00:43:48 +0000291
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000292 s = mode;
293 while (*s) {
294 switch (*s++) {
295 case 'r':
296 if (rwa) {
297 bad_mode:
298 PyErr_SetString(PyExc_ValueError,
Georg Brandl28928ae2010-10-21 13:45:52 +0000299 "Must have exactly one of read/write/append "
300 "mode and at most one plus");
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000301 goto error;
302 }
303 rwa = 1;
304 self->readable = 1;
305 break;
306 case 'w':
307 if (rwa)
308 goto bad_mode;
309 rwa = 1;
310 self->writable = 1;
311 flags |= O_CREAT | O_TRUNC;
312 break;
313 case 'a':
314 if (rwa)
315 goto bad_mode;
316 rwa = 1;
317 self->writable = 1;
318 flags |= O_CREAT;
319 append = 1;
320 break;
321 case 'b':
322 break;
323 case '+':
324 if (plus)
325 goto bad_mode;
326 self->readable = self->writable = 1;
327 plus = 1;
328 break;
329 default:
330 PyErr_Format(PyExc_ValueError,
331 "invalid mode: %.200s", mode);
332 goto error;
333 }
334 }
Guido van Rossuma9e20242007-03-08 00:43:48 +0000335
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000336 if (!rwa)
337 goto bad_mode;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000338
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000339 if (self->readable && self->writable)
340 flags |= O_RDWR;
341 else if (self->readable)
342 flags |= O_RDONLY;
343 else
344 flags |= O_WRONLY;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000345
346#ifdef O_BINARY
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000347 flags |= O_BINARY;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000348#endif
349
Walter Dörwald0e411482007-06-06 16:55:38 +0000350#ifdef O_APPEND
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000351 if (append)
352 flags |= O_APPEND;
Walter Dörwald0e411482007-06-06 16:55:38 +0000353#endif
354
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000355 if (fd >= 0) {
356 if (check_fd(fd))
357 goto error;
358 self->fd = fd;
359 self->closefd = closefd;
360 }
361 else {
362 self->closefd = 1;
363 if (!closefd) {
364 PyErr_SetString(PyExc_ValueError,
365 "Cannot use closefd=False with file name");
366 goto error;
367 }
Guido van Rossum2dced8b2007-10-30 17:27:30 +0000368
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000369 Py_BEGIN_ALLOW_THREADS
370 errno = 0;
Thomas Helleraf2be262007-07-12 11:03:13 +0000371#ifdef MS_WINDOWS
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000372 if (widename != NULL)
373 self->fd = _wopen(widename, flags, 0666);
374 else
Thomas Helleraf2be262007-07-12 11:03:13 +0000375#endif
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000376 self->fd = open(name, flags, 0666);
377 Py_END_ALLOW_THREADS
378 if (self->fd < 0) {
Christian Heimes0b489542007-10-31 19:20:48 +0000379#ifdef MS_WINDOWS
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000380 if (widename != NULL)
381 PyErr_SetFromErrnoWithUnicodeFilename(PyExc_IOError, widename);
382 else
Christian Heimes0b489542007-10-31 19:20:48 +0000383#endif
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000384 PyErr_SetFromErrnoWithFilename(PyExc_IOError, name);
385 goto error;
386 }
Benjamin Peterson430d4692010-10-30 23:13:57 +0000387 if (dircheck(self, name) < 0)
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000388 goto error;
389 }
Guido van Rossuma9e20242007-03-08 00:43:48 +0000390
Victor Stinner89e34362011-01-07 18:47:22 +0000391#if defined(MS_WINDOWS) || defined(__CYGWIN__)
392 /* don't translate newlines (\r\n <=> \n) */
393 _setmode(self->fd, O_BINARY);
394#endif
395
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000396 if (PyObject_SetAttrString((PyObject *)self, "name", nameobj) < 0)
397 goto error;
Antoine Pitrou08838b62009-01-21 00:55:13 +0000398
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000399 if (append) {
400 /* For consistent behaviour, we explicitly seek to the
401 end of file (otherwise, it might be done only on the
402 first write()). */
403 PyObject *pos = portable_lseek(self->fd, NULL, 2);
Antoine Pitrou8d2b51b2010-10-30 16:19:14 +0000404 if (pos == NULL) {
405 if (closefd) {
406 close(self->fd);
407 self->fd = -1;
408 }
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000409 goto error;
Antoine Pitrou8d2b51b2010-10-30 16:19:14 +0000410 }
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000411 Py_DECREF(pos);
412 }
Antoine Pitrou7fb111b2009-03-04 11:14:01 +0000413
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000414 goto done;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000415
416 error:
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000417 ret = -1;
Benjamin Petersonbbb04122010-10-30 23:16:28 +0000418 if (self->fd >= 0)
419 internal_close(self);
Guido van Rossum53807da2007-04-10 19:01:47 +0000420
Guido van Rossuma9e20242007-03-08 00:43:48 +0000421 done:
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000422 Py_CLEAR(stringobj);
423 return ret;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000424}
425
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000426static int
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000427fileio_traverse(fileio *self, visitproc visit, void *arg)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000428{
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000429 Py_VISIT(self->dict);
430 return 0;
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000431}
432
433static int
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000434fileio_clear(fileio *self)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000435{
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000436 Py_CLEAR(self->dict);
437 return 0;
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000438}
439
Guido van Rossuma9e20242007-03-08 00:43:48 +0000440static void
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000441fileio_dealloc(fileio *self)
Guido van Rossuma9e20242007-03-08 00:43:48 +0000442{
Antoine Pitroue033e062010-10-29 10:38:18 +0000443 self->deallocating = 1;
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000444 if (_PyIOBase_finalize((PyObject *) self) < 0)
445 return;
446 _PyObject_GC_UNTRACK(self);
447 if (self->weakreflist != NULL)
448 PyObject_ClearWeakRefs((PyObject *) self);
449 Py_CLEAR(self->dict);
450 Py_TYPE(self)->tp_free((PyObject *)self);
Guido van Rossuma9e20242007-03-08 00:43:48 +0000451}
452
453static PyObject *
454err_closed(void)
455{
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000456 PyErr_SetString(PyExc_ValueError, "I/O operation on closed file");
457 return NULL;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000458}
459
460static PyObject *
Guido van Rossum53807da2007-04-10 19:01:47 +0000461err_mode(char *action)
462{
Antoine Pitrou0d739d72010-09-05 23:01:12 +0000463 PyErr_Format(IO_STATE->unsupported_operation,
464 "File not open for %s", action);
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000465 return NULL;
Guido van Rossum53807da2007-04-10 19:01:47 +0000466}
467
468static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000469fileio_fileno(fileio *self)
Guido van Rossuma9e20242007-03-08 00:43:48 +0000470{
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000471 if (self->fd < 0)
472 return err_closed();
473 return PyLong_FromLong((long) self->fd);
Guido van Rossuma9e20242007-03-08 00:43:48 +0000474}
475
476static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000477fileio_readable(fileio *self)
Guido van Rossuma9e20242007-03-08 00:43:48 +0000478{
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000479 if (self->fd < 0)
480 return err_closed();
481 return PyBool_FromLong((long) self->readable);
Guido van Rossuma9e20242007-03-08 00:43:48 +0000482}
483
484static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000485fileio_writable(fileio *self)
Guido van Rossuma9e20242007-03-08 00:43:48 +0000486{
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000487 if (self->fd < 0)
488 return err_closed();
489 return PyBool_FromLong((long) self->writable);
Guido van Rossuma9e20242007-03-08 00:43:48 +0000490}
491
492static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000493fileio_seekable(fileio *self)
Guido van Rossuma9e20242007-03-08 00:43:48 +0000494{
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000495 if (self->fd < 0)
496 return err_closed();
497 if (self->seekable < 0) {
498 PyObject *pos = portable_lseek(self->fd, NULL, SEEK_CUR);
499 if (pos == NULL) {
500 PyErr_Clear();
501 self->seekable = 0;
502 } else {
503 Py_DECREF(pos);
504 self->seekable = 1;
505 }
506 }
507 return PyBool_FromLong((long) self->seekable);
Guido van Rossuma9e20242007-03-08 00:43:48 +0000508}
509
510static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000511fileio_readinto(fileio *self, PyObject *args)
Guido van Rossuma9e20242007-03-08 00:43:48 +0000512{
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000513 Py_buffer pbuf;
Victor Stinnere6edec22011-01-04 00:29:35 +0000514 Py_ssize_t n, len;
Guido van Rossum53807da2007-04-10 19:01:47 +0000515
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000516 if (self->fd < 0)
517 return err_closed();
518 if (!self->readable)
519 return err_mode("reading");
Guido van Rossum53807da2007-04-10 19:01:47 +0000520
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000521 if (!PyArg_ParseTuple(args, "w*", &pbuf))
522 return NULL;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000523
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000524 if (_PyVerify_fd(self->fd)) {
Victor Stinnere6edec22011-01-04 00:29:35 +0000525 len = pbuf.len;
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000526 Py_BEGIN_ALLOW_THREADS
527 errno = 0;
Victor Stinnere6edec22011-01-04 00:29:35 +0000528#if defined(MS_WIN64) || defined(MS_WINDOWS)
529 if (len > INT_MAX)
530 len = INT_MAX;
531 n = read(self->fd, pbuf.buf, (int)len);
532#else
Victor Stinner72344792011-01-11 00:04:12 +0000533 n = read(self->fd, pbuf.buf, len);
Victor Stinnere6edec22011-01-04 00:29:35 +0000534#endif
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000535 Py_END_ALLOW_THREADS
536 } else
537 n = -1;
538 PyBuffer_Release(&pbuf);
539 if (n < 0) {
540 if (errno == EAGAIN)
541 Py_RETURN_NONE;
542 PyErr_SetFromErrno(PyExc_IOError);
543 return NULL;
544 }
Guido van Rossuma9e20242007-03-08 00:43:48 +0000545
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000546 return PyLong_FromSsize_t(n);
Guido van Rossuma9e20242007-03-08 00:43:48 +0000547}
548
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000549static size_t
Victor Stinnere9d44ccb2011-05-26 00:16:44 +0200550new_buffersize(fileio *self, size_t currentsize
551#ifdef HAVE_FSTAT
552 , off_t pos, off_t end
553#endif
554 )
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000555{
556#ifdef HAVE_FSTAT
Victor Stinnere9d44ccb2011-05-26 00:16:44 +0200557 if (end != (off_t)-1) {
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000558 /* Files claiming a size smaller than SMALLCHUNK may
559 actually be streaming pseudo-files. In this case, we
560 apply the more aggressive algorithm below.
561 */
562 if (end >= SMALLCHUNK && end >= pos && pos >= 0) {
563 /* Add 1 so if the file were to grow we'd notice. */
564 return currentsize + end - pos + 1;
565 }
566 }
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000567#endif
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000568 if (currentsize > SMALLCHUNK) {
569 /* Keep doubling until we reach BIGCHUNK;
570 then keep adding BIGCHUNK. */
571 if (currentsize <= BIGCHUNK)
572 return currentsize + currentsize;
573 else
574 return currentsize + BIGCHUNK;
575 }
576 return currentsize + SMALLCHUNK;
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000577}
578
Guido van Rossum7165cb12007-07-10 06:54:34 +0000579static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000580fileio_readall(fileio *self)
Guido van Rossum7165cb12007-07-10 06:54:34 +0000581{
Victor Stinnere9d44ccb2011-05-26 00:16:44 +0200582#ifdef HAVE_FSTAT
583 struct stat st;
584 off_t pos, end;
585#endif
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000586 PyObject *result;
587 Py_ssize_t total = 0;
588 int n;
Victor Stinnere9d44ccb2011-05-26 00:16:44 +0200589 size_t newsize;
Guido van Rossum7165cb12007-07-10 06:54:34 +0000590
Victor Stinnerb79f28c2011-05-25 22:09:03 +0200591 if (self->fd < 0)
592 return err_closed();
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000593 if (!_PyVerify_fd(self->fd))
594 return PyErr_SetFromErrno(PyExc_IOError);
Kristján Valur Jónssona8abe862009-03-24 15:27:42 +0000595
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000596 result = PyBytes_FromStringAndSize(NULL, SMALLCHUNK);
597 if (result == NULL)
598 return NULL;
Guido van Rossum7165cb12007-07-10 06:54:34 +0000599
Victor Stinnere9d44ccb2011-05-26 00:16:44 +0200600#ifdef HAVE_FSTAT
601#if defined(MS_WIN64) || defined(MS_WINDOWS)
602 pos = _lseeki64(self->fd, 0L, SEEK_CUR);
603#else
604 pos = lseek(self->fd, 0L, SEEK_CUR);
605#endif
606 if (fstat(self->fd, &st) == 0)
607 end = st.st_size;
608 else
609 end = (off_t)-1;
610#endif
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000611 while (1) {
Victor Stinnere9d44ccb2011-05-26 00:16:44 +0200612#ifdef HAVE_FSTAT
613 newsize = new_buffersize(self, total, pos, end);
614#else
615 newsize = new_buffersize(self, total);
616#endif
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000617 if (newsize > PY_SSIZE_T_MAX || newsize <= 0) {
618 PyErr_SetString(PyExc_OverflowError,
619 "unbounded read returned more bytes "
620 "than a Python string can hold ");
621 Py_DECREF(result);
622 return NULL;
623 }
Christian Heimesa872de52008-12-05 08:26:55 +0000624
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000625 if (PyBytes_GET_SIZE(result) < (Py_ssize_t)newsize) {
626 if (_PyBytes_Resize(&result, newsize) < 0) {
627 if (total == 0) {
628 Py_DECREF(result);
629 return NULL;
630 }
631 PyErr_Clear();
632 break;
633 }
634 }
635 Py_BEGIN_ALLOW_THREADS
636 errno = 0;
637 n = read(self->fd,
638 PyBytes_AS_STRING(result) + total,
639 newsize - total);
640 Py_END_ALLOW_THREADS
641 if (n == 0)
642 break;
643 if (n < 0) {
644 if (total > 0)
645 break;
646 if (errno == EAGAIN) {
647 Py_DECREF(result);
648 Py_RETURN_NONE;
649 }
650 Py_DECREF(result);
651 PyErr_SetFromErrno(PyExc_IOError);
652 return NULL;
653 }
654 total += n;
Victor Stinnere9d44ccb2011-05-26 00:16:44 +0200655#ifdef HAVE_FSTAT
656 pos += n;
657#endif
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000658 }
Guido van Rossum7165cb12007-07-10 06:54:34 +0000659
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000660 if (PyBytes_GET_SIZE(result) > total) {
661 if (_PyBytes_Resize(&result, total) < 0) {
662 /* This should never happen, but just in case */
663 Py_DECREF(result);
664 return NULL;
665 }
666 }
667 return result;
Guido van Rossum7165cb12007-07-10 06:54:34 +0000668}
669
Guido van Rossuma9e20242007-03-08 00:43:48 +0000670static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000671fileio_read(fileio *self, PyObject *args)
Guido van Rossuma9e20242007-03-08 00:43:48 +0000672{
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000673 char *ptr;
674 Py_ssize_t n;
675 Py_ssize_t size = -1;
676 PyObject *bytes;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000677
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000678 if (self->fd < 0)
679 return err_closed();
680 if (!self->readable)
681 return err_mode("reading");
Guido van Rossuma9e20242007-03-08 00:43:48 +0000682
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000683 if (!PyArg_ParseTuple(args, "|O&", &_PyIO_ConvertSsize_t, &size))
684 return NULL;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000685
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000686 if (size < 0) {
687 return fileio_readall(self);
688 }
Guido van Rossumc2f93dc2007-05-24 00:50:02 +0000689
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000690 bytes = PyBytes_FromStringAndSize(NULL, size);
691 if (bytes == NULL)
692 return NULL;
693 ptr = PyBytes_AS_STRING(bytes);
Guido van Rossuma9e20242007-03-08 00:43:48 +0000694
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000695 if (_PyVerify_fd(self->fd)) {
696 Py_BEGIN_ALLOW_THREADS
697 errno = 0;
698 n = read(self->fd, ptr, size);
699 Py_END_ALLOW_THREADS
700 } else
701 n = -1;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000702
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000703 if (n < 0) {
704 Py_DECREF(bytes);
705 if (errno == EAGAIN)
706 Py_RETURN_NONE;
707 PyErr_SetFromErrno(PyExc_IOError);
708 return NULL;
709 }
Guido van Rossuma9e20242007-03-08 00:43:48 +0000710
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000711 if (n != size) {
712 if (_PyBytes_Resize(&bytes, n) < 0) {
713 Py_DECREF(bytes);
714 return NULL;
715 }
716 }
Guido van Rossuma9e20242007-03-08 00:43:48 +0000717
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000718 return (PyObject *) bytes;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000719}
720
721static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000722fileio_write(fileio *self, PyObject *args)
Guido van Rossuma9e20242007-03-08 00:43:48 +0000723{
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000724 Py_buffer pbuf;
Victor Stinnere6edec22011-01-04 00:29:35 +0000725 Py_ssize_t n, len;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000726
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000727 if (self->fd < 0)
728 return err_closed();
729 if (!self->writable)
730 return err_mode("writing");
Guido van Rossum53807da2007-04-10 19:01:47 +0000731
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000732 if (!PyArg_ParseTuple(args, "y*", &pbuf))
733 return NULL;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000734
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000735 if (_PyVerify_fd(self->fd)) {
736 Py_BEGIN_ALLOW_THREADS
737 errno = 0;
Victor Stinnere6edec22011-01-04 00:29:35 +0000738 len = pbuf.len;
739#if defined(MS_WIN64) || defined(MS_WINDOWS)
Victor Stinnere0daff12011-03-20 23:36:35 +0100740 if (len > 32767 && isatty(self->fd)) {
741 /* Issue #11395: the Windows console returns an error (12: not
742 enough space error) on writing into stdout if stdout mode is
743 binary and the length is greater than 66,000 bytes (or less,
744 depending on heap usage). */
745 len = 32767;
746 }
747 else if (len > INT_MAX)
Victor Stinnere6edec22011-01-04 00:29:35 +0000748 len = INT_MAX;
749 n = write(self->fd, pbuf.buf, (int)len);
750#else
Victor Stinner72344792011-01-11 00:04:12 +0000751 n = write(self->fd, pbuf.buf, len);
Victor Stinnere6edec22011-01-04 00:29:35 +0000752#endif
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000753 Py_END_ALLOW_THREADS
754 } else
755 n = -1;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000756
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000757 PyBuffer_Release(&pbuf);
Martin v. Löwis423be952008-08-13 15:53:07 +0000758
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000759 if (n < 0) {
760 if (errno == EAGAIN)
761 Py_RETURN_NONE;
762 PyErr_SetFromErrno(PyExc_IOError);
763 return NULL;
764 }
Guido van Rossuma9e20242007-03-08 00:43:48 +0000765
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000766 return PyLong_FromSsize_t(n);
Guido van Rossuma9e20242007-03-08 00:43:48 +0000767}
768
Guido van Rossum53807da2007-04-10 19:01:47 +0000769/* XXX Windows support below is likely incomplete */
770
Guido van Rossum53807da2007-04-10 19:01:47 +0000771/* Cribbed from posix_lseek() */
772static PyObject *
773portable_lseek(int fd, PyObject *posobj, int whence)
774{
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000775 Py_off_t pos, res;
Guido van Rossum53807da2007-04-10 19:01:47 +0000776
777#ifdef SEEK_SET
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000778 /* Turn 0, 1, 2 into SEEK_{SET,CUR,END} */
779 switch (whence) {
Guido van Rossum53807da2007-04-10 19:01:47 +0000780#if SEEK_SET != 0
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000781 case 0: whence = SEEK_SET; break;
Guido van Rossum53807da2007-04-10 19:01:47 +0000782#endif
783#if SEEK_CUR != 1
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000784 case 1: whence = SEEK_CUR; break;
Guido van Rossum53807da2007-04-10 19:01:47 +0000785#endif
Antoine Pitrou4f7945f2009-01-20 11:42:11 +0000786#if SEEK_END != 2
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000787 case 2: whence = SEEK_END; break;
Guido van Rossum53807da2007-04-10 19:01:47 +0000788#endif
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000789 }
Guido van Rossum53807da2007-04-10 19:01:47 +0000790#endif /* SEEK_SET */
791
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000792 if (posobj == NULL)
793 pos = 0;
794 else {
795 if(PyFloat_Check(posobj)) {
796 PyErr_SetString(PyExc_TypeError, "an integer is required");
797 return NULL;
798 }
Alexandre Vassalotti77250f42008-05-06 19:48:38 +0000799#if defined(HAVE_LARGEFILE_SUPPORT)
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000800 pos = PyLong_AsLongLong(posobj);
Guido van Rossum53807da2007-04-10 19:01:47 +0000801#else
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000802 pos = PyLong_AsLong(posobj);
Guido van Rossum53807da2007-04-10 19:01:47 +0000803#endif
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000804 if (PyErr_Occurred())
805 return NULL;
806 }
Guido van Rossum53807da2007-04-10 19:01:47 +0000807
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000808 if (_PyVerify_fd(fd)) {
809 Py_BEGIN_ALLOW_THREADS
Guido van Rossum53807da2007-04-10 19:01:47 +0000810#if defined(MS_WIN64) || defined(MS_WINDOWS)
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000811 res = _lseeki64(fd, pos, whence);
Guido van Rossum53807da2007-04-10 19:01:47 +0000812#else
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000813 res = lseek(fd, pos, whence);
Guido van Rossum53807da2007-04-10 19:01:47 +0000814#endif
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000815 Py_END_ALLOW_THREADS
816 } else
817 res = -1;
818 if (res < 0)
819 return PyErr_SetFromErrno(PyExc_IOError);
Guido van Rossum53807da2007-04-10 19:01:47 +0000820
Alexandre Vassalotti77250f42008-05-06 19:48:38 +0000821#if defined(HAVE_LARGEFILE_SUPPORT)
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000822 return PyLong_FromLongLong(res);
Alexandre Vassalotti77250f42008-05-06 19:48:38 +0000823#else
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000824 return PyLong_FromLong(res);
Guido van Rossum53807da2007-04-10 19:01:47 +0000825#endif
826}
827
Guido van Rossuma9e20242007-03-08 00:43:48 +0000828static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000829fileio_seek(fileio *self, PyObject *args)
Guido van Rossuma9e20242007-03-08 00:43:48 +0000830{
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000831 PyObject *posobj;
832 int whence = 0;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000833
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000834 if (self->fd < 0)
835 return err_closed();
Guido van Rossuma9e20242007-03-08 00:43:48 +0000836
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000837 if (!PyArg_ParseTuple(args, "O|i", &posobj, &whence))
838 return NULL;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000839
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000840 return portable_lseek(self->fd, posobj, whence);
Guido van Rossuma9e20242007-03-08 00:43:48 +0000841}
842
843static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000844fileio_tell(fileio *self, PyObject *args)
Guido van Rossuma9e20242007-03-08 00:43:48 +0000845{
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000846 if (self->fd < 0)
847 return err_closed();
Guido van Rossuma9e20242007-03-08 00:43:48 +0000848
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000849 return portable_lseek(self->fd, NULL, 1);
Guido van Rossuma9e20242007-03-08 00:43:48 +0000850}
851
Thomas Hellerc6a55ee2007-07-11 12:45:46 +0000852#ifdef HAVE_FTRUNCATE
Guido van Rossuma9e20242007-03-08 00:43:48 +0000853static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000854fileio_truncate(fileio *self, PyObject *args)
Guido van Rossuma9e20242007-03-08 00:43:48 +0000855{
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000856 PyObject *posobj = NULL; /* the new size wanted by the user */
Antoine Pitrou905a2ff2010-01-31 22:47:27 +0000857#ifndef MS_WINDOWS
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000858 Py_off_t pos;
Antoine Pitrou905a2ff2010-01-31 22:47:27 +0000859#endif
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000860 int ret;
861 int fd;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000862
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000863 fd = self->fd;
864 if (fd < 0)
865 return err_closed();
866 if (!self->writable)
867 return err_mode("writing");
Guido van Rossuma9e20242007-03-08 00:43:48 +0000868
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000869 if (!PyArg_ParseTuple(args, "|O", &posobj))
870 return NULL;
Guido van Rossum53807da2007-04-10 19:01:47 +0000871
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000872 if (posobj == Py_None || posobj == NULL) {
873 /* Get the current position. */
874 posobj = portable_lseek(fd, NULL, 1);
875 if (posobj == NULL)
876 return NULL;
877 }
878 else {
879 Py_INCREF(posobj);
880 }
Guido van Rossum53807da2007-04-10 19:01:47 +0000881
Thomas Hellerfdeee3a2007-07-12 11:21:36 +0000882#ifdef MS_WINDOWS
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000883 /* MS _chsize doesn't work if newsize doesn't fit in 32 bits,
884 so don't even try using it. */
885 {
886 PyObject *oldposobj, *tempposobj;
887 HANDLE hFile;
Antoine Pitrou905a2ff2010-01-31 22:47:27 +0000888
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000889 /* we save the file pointer position */
890 oldposobj = portable_lseek(fd, NULL, 1);
891 if (oldposobj == NULL) {
892 Py_DECREF(posobj);
893 return NULL;
894 }
Thomas Hellerfdeee3a2007-07-12 11:21:36 +0000895
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000896 /* we then move to the truncation position */
897 tempposobj = portable_lseek(fd, posobj, 0);
898 if (tempposobj == NULL) {
899 Py_DECREF(oldposobj);
900 Py_DECREF(posobj);
901 return NULL;
902 }
903 Py_DECREF(tempposobj);
Antoine Pitrou905a2ff2010-01-31 22:47:27 +0000904
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000905 /* Truncate. Note that this may grow the file! */
906 Py_BEGIN_ALLOW_THREADS
907 errno = 0;
908 hFile = (HANDLE)_get_osfhandle(fd);
909 ret = hFile == (HANDLE)-1; /* testing for INVALID_HANDLE value */
910 if (ret == 0) {
911 ret = SetEndOfFile(hFile) == 0;
912 if (ret)
913 errno = EACCES;
914 }
915 Py_END_ALLOW_THREADS
916
917 /* we restore the file pointer position in any case */
918 tempposobj = portable_lseek(fd, oldposobj, 0);
919 Py_DECREF(oldposobj);
920 if (tempposobj == NULL) {
921 Py_DECREF(posobj);
922 return NULL;
923 }
924 Py_DECREF(tempposobj);
925 }
Thomas Hellerfdeee3a2007-07-12 11:21:36 +0000926#else
Antoine Pitrou905a2ff2010-01-31 22:47:27 +0000927
928#if defined(HAVE_LARGEFILE_SUPPORT)
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000929 pos = PyLong_AsLongLong(posobj);
Antoine Pitrou905a2ff2010-01-31 22:47:27 +0000930#else
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000931 pos = PyLong_AsLong(posobj);
Antoine Pitrou905a2ff2010-01-31 22:47:27 +0000932#endif
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000933 if (PyErr_Occurred()){
934 Py_DECREF(posobj);
935 return NULL;
936 }
Antoine Pitrou905a2ff2010-01-31 22:47:27 +0000937
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000938 Py_BEGIN_ALLOW_THREADS
939 errno = 0;
940 ret = ftruncate(fd, pos);
941 Py_END_ALLOW_THREADS
Antoine Pitrou905a2ff2010-01-31 22:47:27 +0000942
Thomas Hellerfdeee3a2007-07-12 11:21:36 +0000943#endif /* !MS_WINDOWS */
Guido van Rossuma9e20242007-03-08 00:43:48 +0000944
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000945 if (ret != 0) {
946 Py_DECREF(posobj);
947 PyErr_SetFromErrno(PyExc_IOError);
948 return NULL;
949 }
Guido van Rossuma9e20242007-03-08 00:43:48 +0000950
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000951 return posobj;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000952}
Antoine Pitrou905a2ff2010-01-31 22:47:27 +0000953#endif /* HAVE_FTRUNCATE */
Guido van Rossum53807da2007-04-10 19:01:47 +0000954
955static char *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000956mode_string(fileio *self)
Guido van Rossum53807da2007-04-10 19:01:47 +0000957{
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000958 if (self->readable) {
959 if (self->writable)
960 return "rb+";
961 else
962 return "rb";
963 }
964 else
965 return "wb";
Guido van Rossum53807da2007-04-10 19:01:47 +0000966}
Guido van Rossuma9e20242007-03-08 00:43:48 +0000967
968static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000969fileio_repr(fileio *self)
Guido van Rossuma9e20242007-03-08 00:43:48 +0000970{
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000971 PyObject *nameobj, *res;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000972
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000973 if (self->fd < 0)
974 return PyUnicode_FromFormat("<_io.FileIO [closed]>");
Antoine Pitrou716c4442009-05-23 19:04:03 +0000975
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000976 nameobj = PyObject_GetAttrString((PyObject *) self, "name");
977 if (nameobj == NULL) {
978 if (PyErr_ExceptionMatches(PyExc_AttributeError))
979 PyErr_Clear();
980 else
981 return NULL;
982 res = PyUnicode_FromFormat("<_io.FileIO fd=%d mode='%s'>",
983 self->fd, mode_string(self));
984 }
985 else {
986 res = PyUnicode_FromFormat("<_io.FileIO name=%R mode='%s'>",
987 nameobj, mode_string(self));
988 Py_DECREF(nameobj);
989 }
990 return res;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000991}
992
993static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000994fileio_isatty(fileio *self)
Guido van Rossuma9e20242007-03-08 00:43:48 +0000995{
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000996 long res;
Guido van Rossum53807da2007-04-10 19:01:47 +0000997
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000998 if (self->fd < 0)
999 return err_closed();
1000 Py_BEGIN_ALLOW_THREADS
1001 res = isatty(self->fd);
1002 Py_END_ALLOW_THREADS
1003 return PyBool_FromLong(res);
Guido van Rossuma9e20242007-03-08 00:43:48 +00001004}
1005
Antoine Pitrou243757e2010-11-05 21:15:39 +00001006static PyObject *
1007fileio_getstate(fileio *self)
1008{
1009 PyErr_Format(PyExc_TypeError,
1010 "cannot serialize '%s' object", Py_TYPE(self)->tp_name);
1011 return NULL;
1012}
1013
Guido van Rossuma9e20242007-03-08 00:43:48 +00001014
1015PyDoc_STRVAR(fileio_doc,
1016"file(name: str[, mode: str]) -> file IO object\n"
1017"\n"
1018"Open a file. The mode can be 'r', 'w' or 'a' for reading (default),\n"
Antoine Pitrouae4b4722010-05-05 16:31:07 +00001019"writing or appending. The file will be created if it doesn't exist\n"
Guido van Rossuma9e20242007-03-08 00:43:48 +00001020"when opened for writing or appending; it will be truncated when\n"
1021"opened for writing. Add a '+' to the mode to allow simultaneous\n"
1022"reading and writing.");
1023
1024PyDoc_STRVAR(read_doc,
1025"read(size: int) -> bytes. read at most size bytes, returned as bytes.\n"
1026"\n"
1027"Only makes one system call, so less data may be returned than requested\n"
Guido van Rossum7165cb12007-07-10 06:54:34 +00001028"In non-blocking mode, returns None if no data is available.\n"
1029"On end-of-file, returns ''.");
1030
1031PyDoc_STRVAR(readall_doc,
1032"readall() -> bytes. read all data from the file, returned as bytes.\n"
1033"\n"
1034"In non-blocking mode, returns as much as is immediately available,\n"
1035"or None if no data is available. On end-of-file, returns ''.");
Guido van Rossuma9e20242007-03-08 00:43:48 +00001036
1037PyDoc_STRVAR(write_doc,
1038"write(b: bytes) -> int. Write bytes b to file, return number written.\n"
1039"\n"
1040"Only makes one system call, so not all of the data may be written.\n"
1041"The number of bytes actually written is returned.");
1042
1043PyDoc_STRVAR(fileno_doc,
1044"fileno() -> int. \"file descriptor\".\n"
1045"\n"
1046"This is needed for lower-level file interfaces, such the fcntl module.");
1047
1048PyDoc_STRVAR(seek_doc,
1049"seek(offset: int[, whence: int]) -> None. Move to new file position.\n"
1050"\n"
1051"Argument offset is a byte count. Optional argument whence defaults to\n"
1052"0 (offset from start of file, offset should be >= 0); other values are 1\n"
1053"(move relative to current position, positive or negative), and 2 (move\n"
1054"relative to end of file, usually negative, although many platforms allow\n"
1055"seeking beyond the end of a file)."
1056"\n"
1057"Note that not all file objects are seekable.");
1058
Thomas Hellerc6a55ee2007-07-11 12:45:46 +00001059#ifdef HAVE_FTRUNCATE
Guido van Rossuma9e20242007-03-08 00:43:48 +00001060PyDoc_STRVAR(truncate_doc,
Antoine Pitrouae4b4722010-05-05 16:31:07 +00001061"truncate([size: int]) -> None. Truncate the file to at most size bytes.\n"
Guido van Rossuma9e20242007-03-08 00:43:48 +00001062"\n"
Alexandre Vassalotti77250f42008-05-06 19:48:38 +00001063"Size defaults to the current file position, as returned by tell()."
1064"The current file position is changed to the value of size.");
Thomas Hellerc6a55ee2007-07-11 12:45:46 +00001065#endif
Guido van Rossuma9e20242007-03-08 00:43:48 +00001066
1067PyDoc_STRVAR(tell_doc,
Antoine Pitrouae4b4722010-05-05 16:31:07 +00001068"tell() -> int. Current file position");
Guido van Rossuma9e20242007-03-08 00:43:48 +00001069
1070PyDoc_STRVAR(readinto_doc,
Benjamin Peterson9a8082f2009-03-05 00:55:56 +00001071"readinto() -> Same as RawIOBase.readinto().");
Guido van Rossuma9e20242007-03-08 00:43:48 +00001072
1073PyDoc_STRVAR(close_doc,
1074"close() -> None. Close the file.\n"
1075"\n"
1076"A closed file cannot be used for further I/O operations. close() may be\n"
1077"called more than once without error. Changes the fileno to -1.");
1078
1079PyDoc_STRVAR(isatty_doc,
1080"isatty() -> bool. True if the file is connected to a tty device.");
1081
Guido van Rossuma9e20242007-03-08 00:43:48 +00001082PyDoc_STRVAR(seekable_doc,
1083"seekable() -> bool. True if file supports random-access.");
1084
1085PyDoc_STRVAR(readable_doc,
1086"readable() -> bool. True if file was opened in a read mode.");
1087
1088PyDoc_STRVAR(writable_doc,
1089"writable() -> bool. True if file was opened in a write mode.");
1090
1091static PyMethodDef fileio_methods[] = {
Antoine Pitrouae4b4722010-05-05 16:31:07 +00001092 {"read", (PyCFunction)fileio_read, METH_VARARGS, read_doc},
1093 {"readall", (PyCFunction)fileio_readall, METH_NOARGS, readall_doc},
1094 {"readinto", (PyCFunction)fileio_readinto, METH_VARARGS, readinto_doc},
1095 {"write", (PyCFunction)fileio_write, METH_VARARGS, write_doc},
1096 {"seek", (PyCFunction)fileio_seek, METH_VARARGS, seek_doc},
1097 {"tell", (PyCFunction)fileio_tell, METH_VARARGS, tell_doc},
Thomas Hellerc6a55ee2007-07-11 12:45:46 +00001098#ifdef HAVE_FTRUNCATE
Antoine Pitrouae4b4722010-05-05 16:31:07 +00001099 {"truncate", (PyCFunction)fileio_truncate, METH_VARARGS, truncate_doc},
Thomas Hellerc6a55ee2007-07-11 12:45:46 +00001100#endif
Antoine Pitrouae4b4722010-05-05 16:31:07 +00001101 {"close", (PyCFunction)fileio_close, METH_NOARGS, close_doc},
1102 {"seekable", (PyCFunction)fileio_seekable, METH_NOARGS, seekable_doc},
1103 {"readable", (PyCFunction)fileio_readable, METH_NOARGS, readable_doc},
1104 {"writable", (PyCFunction)fileio_writable, METH_NOARGS, writable_doc},
1105 {"fileno", (PyCFunction)fileio_fileno, METH_NOARGS, fileno_doc},
1106 {"isatty", (PyCFunction)fileio_isatty, METH_NOARGS, isatty_doc},
Antoine Pitroue033e062010-10-29 10:38:18 +00001107 {"_dealloc_warn", (PyCFunction)fileio_dealloc_warn, METH_O, NULL},
Antoine Pitrou243757e2010-11-05 21:15:39 +00001108 {"__getstate__", (PyCFunction)fileio_getstate, METH_NOARGS, NULL},
Antoine Pitrouae4b4722010-05-05 16:31:07 +00001109 {NULL, NULL} /* sentinel */
Guido van Rossuma9e20242007-03-08 00:43:48 +00001110};
1111
Guido van Rossum53807da2007-04-10 19:01:47 +00001112/* 'closed' and 'mode' are attributes for backwards compatibility reasons. */
1113
Guido van Rossumb0428152007-04-08 17:44:42 +00001114static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +00001115get_closed(fileio *self, void *closure)
Guido van Rossumb0428152007-04-08 17:44:42 +00001116{
Antoine Pitrouae4b4722010-05-05 16:31:07 +00001117 return PyBool_FromLong((long)(self->fd < 0));
Guido van Rossum53807da2007-04-10 19:01:47 +00001118}
1119
1120static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +00001121get_closefd(fileio *self, void *closure)
Christian Heimesecc42a22008-11-05 19:30:32 +00001122{
Antoine Pitrouae4b4722010-05-05 16:31:07 +00001123 return PyBool_FromLong((long)(self->closefd));
Christian Heimesecc42a22008-11-05 19:30:32 +00001124}
1125
1126static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +00001127get_mode(fileio *self, void *closure)
Guido van Rossum53807da2007-04-10 19:01:47 +00001128{
Antoine Pitrouae4b4722010-05-05 16:31:07 +00001129 return PyUnicode_FromString(mode_string(self));
Guido van Rossumb0428152007-04-08 17:44:42 +00001130}
1131
1132static PyGetSetDef fileio_getsetlist[] = {
Antoine Pitrouae4b4722010-05-05 16:31:07 +00001133 {"closed", (getter)get_closed, NULL, "True if the file is closed"},
1134 {"closefd", (getter)get_closefd, NULL,
1135 "True if the file descriptor will be closed"},
1136 {"mode", (getter)get_mode, NULL, "String giving the file mode"},
1137 {NULL},
Guido van Rossumb0428152007-04-08 17:44:42 +00001138};
1139
Guido van Rossuma9e20242007-03-08 00:43:48 +00001140PyTypeObject PyFileIO_Type = {
Antoine Pitrouae4b4722010-05-05 16:31:07 +00001141 PyVarObject_HEAD_INIT(NULL, 0)
1142 "_io.FileIO",
1143 sizeof(fileio),
1144 0,
1145 (destructor)fileio_dealloc, /* tp_dealloc */
1146 0, /* tp_print */
1147 0, /* tp_getattr */
1148 0, /* tp_setattr */
1149 0, /* tp_reserved */
1150 (reprfunc)fileio_repr, /* tp_repr */
1151 0, /* tp_as_number */
1152 0, /* tp_as_sequence */
1153 0, /* tp_as_mapping */
1154 0, /* tp_hash */
1155 0, /* tp_call */
1156 0, /* tp_str */
1157 PyObject_GenericGetAttr, /* tp_getattro */
1158 0, /* tp_setattro */
1159 0, /* tp_as_buffer */
1160 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE
1161 | Py_TPFLAGS_HAVE_GC, /* tp_flags */
1162 fileio_doc, /* tp_doc */
1163 (traverseproc)fileio_traverse, /* tp_traverse */
1164 (inquiry)fileio_clear, /* tp_clear */
1165 0, /* tp_richcompare */
1166 offsetof(fileio, weakreflist), /* tp_weaklistoffset */
1167 0, /* tp_iter */
1168 0, /* tp_iternext */
1169 fileio_methods, /* tp_methods */
1170 0, /* tp_members */
1171 fileio_getsetlist, /* tp_getset */
1172 0, /* tp_base */
1173 0, /* tp_dict */
1174 0, /* tp_descr_get */
1175 0, /* tp_descr_set */
1176 offsetof(fileio, dict), /* tp_dictoffset */
1177 fileio_init, /* tp_init */
1178 PyType_GenericAlloc, /* tp_alloc */
1179 fileio_new, /* tp_new */
1180 PyObject_GC_Del, /* tp_free */
Guido van Rossuma9e20242007-03-08 00:43:48 +00001181};