blob: acb0097968f3a6bc9092350233b8dc929fbf8a29 [file] [log] [blame]
Guido van Rossuma9e20242007-03-08 00:43:48 +00001/* Author: Daniel Stutzbach */
2
3#define PY_SSIZE_T_CLEAN
4#include "Python.h"
Antoine Pitroue033e062010-10-29 10:38:18 +00005#include "structmember.h"
Benjamin Peterson2614cda2010-03-21 22:36:19 +00006#ifdef HAVE_SYS_TYPES_H
Guido van Rossuma9e20242007-03-08 00:43:48 +00007#include <sys/types.h>
Benjamin Peterson2614cda2010-03-21 22:36:19 +00008#endif
9#ifdef HAVE_SYS_STAT_H
Guido van Rossuma9e20242007-03-08 00:43:48 +000010#include <sys/stat.h>
Benjamin Peterson2614cda2010-03-21 22:36:19 +000011#endif
12#ifdef HAVE_FCNTL_H
Guido van Rossuma9e20242007-03-08 00:43:48 +000013#include <fcntl.h>
Benjamin Peterson2614cda2010-03-21 22:36:19 +000014#endif
Guido van Rossuma9e20242007-03-08 00:43:48 +000015#include <stddef.h> /* For offsetof */
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +000016#include "_iomodule.h"
Guido van Rossuma9e20242007-03-08 00:43:48 +000017
18/*
19 * Known likely problems:
20 *
21 * - Files larger then 2**32-1
22 * - Files with unicode filenames
23 * - Passing numbers greater than 2**32-1 when an integer is expected
24 * - Making it work on Windows and other oddball platforms
25 *
26 * To Do:
27 *
28 * - autoconfify header file inclusion
Guido van Rossuma9e20242007-03-08 00:43:48 +000029 */
30
31#ifdef MS_WINDOWS
32/* can simulate truncate with Win32 API functions; see file_truncate */
Thomas Hellerfdeee3a2007-07-12 11:21:36 +000033#define HAVE_FTRUNCATE
Guido van Rossuma9e20242007-03-08 00:43:48 +000034#define WIN32_LEAN_AND_MEAN
35#include <windows.h>
36#endif
37
Christian Heimesa872de52008-12-05 08:26:55 +000038#if BUFSIZ < (8*1024)
39#define SMALLCHUNK (8*1024)
40#elif (BUFSIZ >= (2 << 25))
41#error "unreasonable BUFSIZ > 64MB defined"
42#else
43#define SMALLCHUNK BUFSIZ
44#endif
45
Guido van Rossuma9e20242007-03-08 00:43:48 +000046typedef struct {
Antoine Pitrouae4b4722010-05-05 16:31:07 +000047 PyObject_HEAD
48 int fd;
49 unsigned int readable : 1;
50 unsigned int writable : 1;
51 signed int seekable : 2; /* -1 means unknown */
52 unsigned int closefd : 1;
Antoine Pitroue033e062010-10-29 10:38:18 +000053 unsigned int deallocating: 1;
Antoine Pitrouae4b4722010-05-05 16:31:07 +000054 PyObject *weakreflist;
55 PyObject *dict;
Benjamin Peterson680bf1a2009-06-12 02:07:12 +000056} fileio;
Guido van Rossuma9e20242007-03-08 00:43:48 +000057
Collin Winteraf334382007-03-08 21:46:15 +000058PyTypeObject PyFileIO_Type;
59
Guido van Rossuma9e20242007-03-08 00:43:48 +000060#define PyFileIO_Check(op) (PyObject_TypeCheck((op), &PyFileIO_Type))
61
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +000062int
63_PyFileIO_closed(PyObject *self)
64{
Antoine Pitrouae4b4722010-05-05 16:31:07 +000065 return ((fileio *)self)->fd < 0;
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +000066}
Antoine Pitrou08838b62009-01-21 00:55:13 +000067
Antoine Pitroue033e062010-10-29 10:38:18 +000068/* Because this can call arbitrary code, it shouldn't be called when
69 the refcount is 0 (that is, not directly from tp_dealloc unless
70 the refcount has been temporarily re-incremented). */
71static PyObject *
72fileio_dealloc_warn(fileio *self, PyObject *source)
73{
74 if (self->fd >= 0 && self->closefd) {
75 PyObject *exc, *val, *tb;
76 PyErr_Fetch(&exc, &val, &tb);
77 if (PyErr_WarnFormat(PyExc_ResourceWarning, 1,
78 "unclosed file %R", source)) {
79 /* Spurious errors can appear at shutdown */
80 if (PyErr_ExceptionMatches(PyExc_Warning))
81 PyErr_WriteUnraisable((PyObject *) self);
82 }
83 PyErr_Restore(exc, val, tb);
84 }
85 Py_RETURN_NONE;
86}
87
Antoine Pitrou7fb111b2009-03-04 11:14:01 +000088static PyObject *
89portable_lseek(int fd, PyObject *posobj, int whence);
90
Antoine Pitroua28fcfd2009-03-13 23:42:55 +000091static PyObject *portable_lseek(int fd, PyObject *posobj, int whence);
92
Kristján Valur Jónsson19288c22008-12-18 17:15:54 +000093/* Returns 0 on success, -1 with exception set on failure. */
Neal Norwitz88b44da2007-08-12 17:23:54 +000094static int
Benjamin Peterson680bf1a2009-06-12 02:07:12 +000095internal_close(fileio *self)
Guido van Rossuma9e20242007-03-08 00:43:48 +000096{
Antoine Pitrouae4b4722010-05-05 16:31:07 +000097 int err = 0;
98 int save_errno = 0;
99 if (self->fd >= 0) {
100 int fd = self->fd;
101 self->fd = -1;
102 /* fd is accessible and someone else may have closed it */
103 if (_PyVerify_fd(fd)) {
104 Py_BEGIN_ALLOW_THREADS
105 err = close(fd);
106 if (err < 0)
107 save_errno = errno;
108 Py_END_ALLOW_THREADS
109 } else {
110 save_errno = errno;
111 err = -1;
112 }
113 }
114 if (err < 0) {
115 errno = save_errno;
116 PyErr_SetFromErrno(PyExc_IOError);
117 return -1;
118 }
119 return 0;
Neal Norwitz88b44da2007-08-12 17:23:54 +0000120}
121
122static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000123fileio_close(fileio *self)
Neal Norwitz88b44da2007-08-12 17:23:54 +0000124{
Martin v. Löwisbd928fe2011-10-14 10:20:37 +0200125 _Py_IDENTIFIER(close);
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000126 if (!self->closefd) {
127 self->fd = -1;
128 Py_RETURN_NONE;
129 }
Antoine Pitroue033e062010-10-29 10:38:18 +0000130 if (self->deallocating) {
131 PyObject *r = fileio_dealloc_warn(self, (PyObject *) self);
132 if (r)
133 Py_DECREF(r);
134 else
135 PyErr_Clear();
136 }
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000137 errno = internal_close(self);
138 if (errno < 0)
139 return NULL;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000140
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200141 return _PyObject_CallMethodId((PyObject*)&PyRawIOBase_Type,
142 &PyId_close, "O", self);
Guido van Rossuma9e20242007-03-08 00:43:48 +0000143}
144
145static PyObject *
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000146fileio_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
Guido van Rossuma9e20242007-03-08 00:43:48 +0000147{
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000148 fileio *self;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000149
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000150 assert(type != NULL && type->tp_alloc != NULL);
Guido van Rossuma9e20242007-03-08 00:43:48 +0000151
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000152 self = (fileio *) type->tp_alloc(type, 0);
153 if (self != NULL) {
154 self->fd = -1;
155 self->readable = 0;
156 self->writable = 0;
157 self->seekable = -1;
158 self->closefd = 1;
159 self->weakreflist = NULL;
160 }
Guido van Rossuma9e20242007-03-08 00:43:48 +0000161
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000162 return (PyObject *) self;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000163}
164
165/* On Unix, open will succeed for directories.
166 In Python, there should be no file objects referring to
167 directories, so we need a check. */
168
169static int
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000170dircheck(fileio* self, const char *name)
Guido van Rossuma9e20242007-03-08 00:43:48 +0000171{
172#if defined(HAVE_FSTAT) && defined(S_IFDIR) && defined(EISDIR)
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000173 struct stat buf;
174 if (self->fd < 0)
175 return 0;
176 if (fstat(self->fd, &buf) == 0 && S_ISDIR(buf.st_mode)) {
177 char *msg = strerror(EISDIR);
178 PyObject *exc;
179 if (internal_close(self))
180 return -1;
Guido van Rossum53807da2007-04-10 19:01:47 +0000181
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000182 exc = PyObject_CallFunction(PyExc_IOError, "(iss)",
183 EISDIR, msg, name);
184 PyErr_SetObject(PyExc_IOError, exc);
185 Py_XDECREF(exc);
186 return -1;
187 }
Guido van Rossuma9e20242007-03-08 00:43:48 +0000188#endif
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000189 return 0;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000190}
191
Benjamin Peterson806d4022009-01-19 15:11:51 +0000192static int
193check_fd(int fd)
194{
195#if defined(HAVE_FSTAT)
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000196 struct stat buf;
197 if (!_PyVerify_fd(fd) || (fstat(fd, &buf) < 0 && errno == EBADF)) {
198 PyObject *exc;
199 char *msg = strerror(EBADF);
200 exc = PyObject_CallFunction(PyExc_OSError, "(is)",
201 EBADF, msg);
202 PyErr_SetObject(PyExc_OSError, exc);
203 Py_XDECREF(exc);
204 return -1;
205 }
Benjamin Peterson806d4022009-01-19 15:11:51 +0000206#endif
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000207 return 0;
Benjamin Peterson806d4022009-01-19 15:11:51 +0000208}
209
Guido van Rossuma9e20242007-03-08 00:43:48 +0000210
211static int
212fileio_init(PyObject *oself, PyObject *args, PyObject *kwds)
213{
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000214 fileio *self = (fileio *) oself;
215 static char *kwlist[] = {"file", "mode", "closefd", NULL};
216 const char *name = NULL;
217 PyObject *nameobj, *stringobj = NULL;
218 char *mode = "r";
219 char *s;
Thomas Helleraf2be262007-07-12 11:03:13 +0000220#ifdef MS_WINDOWS
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000221 Py_UNICODE *widename = NULL;
Thomas Helleraf2be262007-07-12 11:03:13 +0000222#endif
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000223 int ret = 0;
224 int rwa = 0, plus = 0, append = 0;
225 int flags = 0;
226 int fd = -1;
227 int closefd = 1;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000228
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000229 assert(PyFileIO_Check(oself));
230 if (self->fd >= 0) {
231 /* Have to close the existing file first. */
232 if (internal_close(self) < 0)
233 return -1;
234 }
Guido van Rossuma9e20242007-03-08 00:43:48 +0000235
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000236 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|si:fileio",
237 kwlist, &nameobj, &mode, &closefd))
238 return -1;
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000239
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000240 if (PyFloat_Check(nameobj)) {
241 PyErr_SetString(PyExc_TypeError,
242 "integer argument expected, got float");
243 return -1;
244 }
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000245
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000246 fd = PyLong_AsLong(nameobj);
247 if (fd < 0) {
248 if (!PyErr_Occurred()) {
249 PyErr_SetString(PyExc_ValueError,
250 "Negative filedescriptor");
251 return -1;
252 }
253 PyErr_Clear();
254 }
Guido van Rossumb0428152007-04-08 17:44:42 +0000255
Hirokazu Yamamoto8223c242009-05-17 04:21:53 +0000256#ifdef MS_WINDOWS
Victor Stinnerfe9a8612011-09-29 23:19:04 +0200257 if (PyUnicode_Check(nameobj)) {
258 widename = PyUnicode_AsUnicode(nameobj);
259 if (widename == NULL)
260 return -1;
261 } else
Guido van Rossuma9e20242007-03-08 00:43:48 +0000262#endif
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000263 if (fd < 0)
264 {
265 if (PyBytes_Check(nameobj) || PyByteArray_Check(nameobj)) {
266 Py_ssize_t namelen;
267 if (PyObject_AsCharBuffer(nameobj, &name, &namelen) < 0)
268 return -1;
269 }
270 else {
271 PyObject *u = PyUnicode_FromObject(nameobj);
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000272
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000273 if (u == NULL)
274 return -1;
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000275
Victor Stinnerae6265f2010-05-15 16:27:27 +0000276 stringobj = PyUnicode_EncodeFSDefault(u);
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000277 Py_DECREF(u);
278 if (stringobj == NULL)
279 return -1;
280 if (!PyBytes_Check(stringobj)) {
281 PyErr_SetString(PyExc_TypeError,
282 "encoder failed to return bytes");
283 goto error;
284 }
285 name = PyBytes_AS_STRING(stringobj);
286 }
287 }
Guido van Rossuma9e20242007-03-08 00:43:48 +0000288
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000289 s = mode;
290 while (*s) {
291 switch (*s++) {
292 case 'r':
293 if (rwa) {
294 bad_mode:
295 PyErr_SetString(PyExc_ValueError,
Georg Brandl28928ae2010-10-21 13:45:52 +0000296 "Must have exactly one of read/write/append "
297 "mode and at most one plus");
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000298 goto error;
299 }
300 rwa = 1;
301 self->readable = 1;
302 break;
303 case 'w':
304 if (rwa)
305 goto bad_mode;
306 rwa = 1;
307 self->writable = 1;
308 flags |= O_CREAT | O_TRUNC;
309 break;
310 case 'a':
311 if (rwa)
312 goto bad_mode;
313 rwa = 1;
314 self->writable = 1;
315 flags |= O_CREAT;
316 append = 1;
317 break;
318 case 'b':
319 break;
320 case '+':
321 if (plus)
322 goto bad_mode;
323 self->readable = self->writable = 1;
324 plus = 1;
325 break;
326 default:
327 PyErr_Format(PyExc_ValueError,
328 "invalid mode: %.200s", mode);
329 goto error;
330 }
331 }
Guido van Rossuma9e20242007-03-08 00:43:48 +0000332
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000333 if (!rwa)
334 goto bad_mode;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000335
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000336 if (self->readable && self->writable)
337 flags |= O_RDWR;
338 else if (self->readable)
339 flags |= O_RDONLY;
340 else
341 flags |= O_WRONLY;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000342
343#ifdef O_BINARY
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000344 flags |= O_BINARY;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000345#endif
346
Walter Dörwald0e411482007-06-06 16:55:38 +0000347#ifdef O_APPEND
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000348 if (append)
349 flags |= O_APPEND;
Walter Dörwald0e411482007-06-06 16:55:38 +0000350#endif
351
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000352 if (fd >= 0) {
353 if (check_fd(fd))
354 goto error;
355 self->fd = fd;
356 self->closefd = closefd;
357 }
358 else {
359 self->closefd = 1;
360 if (!closefd) {
361 PyErr_SetString(PyExc_ValueError,
362 "Cannot use closefd=False with file name");
363 goto error;
364 }
Guido van Rossum2dced8b2007-10-30 17:27:30 +0000365
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000366 Py_BEGIN_ALLOW_THREADS
367 errno = 0;
Thomas Helleraf2be262007-07-12 11:03:13 +0000368#ifdef MS_WINDOWS
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000369 if (widename != NULL)
370 self->fd = _wopen(widename, flags, 0666);
371 else
Thomas Helleraf2be262007-07-12 11:03:13 +0000372#endif
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000373 self->fd = open(name, flags, 0666);
374 Py_END_ALLOW_THREADS
375 if (self->fd < 0) {
Christian Heimes0b489542007-10-31 19:20:48 +0000376#ifdef MS_WINDOWS
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000377 if (widename != NULL)
Victor Stinnerfe9a8612011-09-29 23:19:04 +0200378 PyErr_SetFromErrnoWithFilenameObject(PyExc_IOError, nameobj);
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000379 else
Christian Heimes0b489542007-10-31 19:20:48 +0000380#endif
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000381 PyErr_SetFromErrnoWithFilename(PyExc_IOError, name);
382 goto error;
383 }
Benjamin Peterson430d4692010-10-30 23:13:57 +0000384 if (dircheck(self, name) < 0)
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000385 goto error;
386 }
Guido van Rossuma9e20242007-03-08 00:43:48 +0000387
Victor Stinner89e34362011-01-07 18:47:22 +0000388#if defined(MS_WINDOWS) || defined(__CYGWIN__)
389 /* don't translate newlines (\r\n <=> \n) */
390 _setmode(self->fd, O_BINARY);
391#endif
392
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000393 if (PyObject_SetAttrString((PyObject *)self, "name", nameobj) < 0)
394 goto error;
Antoine Pitrou08838b62009-01-21 00:55:13 +0000395
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000396 if (append) {
397 /* For consistent behaviour, we explicitly seek to the
398 end of file (otherwise, it might be done only on the
399 first write()). */
400 PyObject *pos = portable_lseek(self->fd, NULL, 2);
Antoine Pitrou8d2b51b2010-10-30 16:19:14 +0000401 if (pos == NULL) {
402 if (closefd) {
403 close(self->fd);
404 self->fd = -1;
405 }
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000406 goto error;
Antoine Pitrou8d2b51b2010-10-30 16:19:14 +0000407 }
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000408 Py_DECREF(pos);
409 }
Antoine Pitrou7fb111b2009-03-04 11:14:01 +0000410
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000411 goto done;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000412
413 error:
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000414 ret = -1;
Benjamin Petersonbbb04122010-10-30 23:16:28 +0000415 if (self->fd >= 0)
416 internal_close(self);
Guido van Rossum53807da2007-04-10 19:01:47 +0000417
Guido van Rossuma9e20242007-03-08 00:43:48 +0000418 done:
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000419 Py_CLEAR(stringobj);
420 return ret;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000421}
422
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000423static int
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000424fileio_traverse(fileio *self, visitproc visit, void *arg)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000425{
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000426 Py_VISIT(self->dict);
427 return 0;
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000428}
429
430static int
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000431fileio_clear(fileio *self)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000432{
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000433 Py_CLEAR(self->dict);
434 return 0;
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000435}
436
Guido van Rossuma9e20242007-03-08 00:43:48 +0000437static void
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000438fileio_dealloc(fileio *self)
Guido van Rossuma9e20242007-03-08 00:43:48 +0000439{
Antoine Pitroue033e062010-10-29 10:38:18 +0000440 self->deallocating = 1;
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000441 if (_PyIOBase_finalize((PyObject *) self) < 0)
442 return;
443 _PyObject_GC_UNTRACK(self);
444 if (self->weakreflist != NULL)
445 PyObject_ClearWeakRefs((PyObject *) self);
446 Py_CLEAR(self->dict);
447 Py_TYPE(self)->tp_free((PyObject *)self);
Guido van Rossuma9e20242007-03-08 00:43:48 +0000448}
449
450static PyObject *
451err_closed(void)
452{
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000453 PyErr_SetString(PyExc_ValueError, "I/O operation on closed file");
454 return NULL;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000455}
456
457static PyObject *
Guido van Rossum53807da2007-04-10 19:01:47 +0000458err_mode(char *action)
459{
Antoine Pitrou0d739d72010-09-05 23:01:12 +0000460 PyErr_Format(IO_STATE->unsupported_operation,
461 "File not open for %s", action);
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000462 return NULL;
Guido van Rossum53807da2007-04-10 19:01:47 +0000463}
464
465static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000466fileio_fileno(fileio *self)
Guido van Rossuma9e20242007-03-08 00:43:48 +0000467{
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000468 if (self->fd < 0)
469 return err_closed();
470 return PyLong_FromLong((long) self->fd);
Guido van Rossuma9e20242007-03-08 00:43:48 +0000471}
472
473static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000474fileio_readable(fileio *self)
Guido van Rossuma9e20242007-03-08 00:43:48 +0000475{
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000476 if (self->fd < 0)
477 return err_closed();
478 return PyBool_FromLong((long) self->readable);
Guido van Rossuma9e20242007-03-08 00:43:48 +0000479}
480
481static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000482fileio_writable(fileio *self)
Guido van Rossuma9e20242007-03-08 00:43:48 +0000483{
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000484 if (self->fd < 0)
485 return err_closed();
486 return PyBool_FromLong((long) self->writable);
Guido van Rossuma9e20242007-03-08 00:43:48 +0000487}
488
489static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000490fileio_seekable(fileio *self)
Guido van Rossuma9e20242007-03-08 00:43:48 +0000491{
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000492 if (self->fd < 0)
493 return err_closed();
494 if (self->seekable < 0) {
495 PyObject *pos = portable_lseek(self->fd, NULL, SEEK_CUR);
496 if (pos == NULL) {
497 PyErr_Clear();
498 self->seekable = 0;
499 } else {
500 Py_DECREF(pos);
501 self->seekable = 1;
502 }
503 }
504 return PyBool_FromLong((long) self->seekable);
Guido van Rossuma9e20242007-03-08 00:43:48 +0000505}
506
507static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000508fileio_readinto(fileio *self, PyObject *args)
Guido van Rossuma9e20242007-03-08 00:43:48 +0000509{
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000510 Py_buffer pbuf;
Victor Stinnere6edec22011-01-04 00:29:35 +0000511 Py_ssize_t n, len;
Guido van Rossum53807da2007-04-10 19:01:47 +0000512
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000513 if (self->fd < 0)
514 return err_closed();
515 if (!self->readable)
516 return err_mode("reading");
Guido van Rossum53807da2007-04-10 19:01:47 +0000517
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000518 if (!PyArg_ParseTuple(args, "w*", &pbuf))
519 return NULL;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000520
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000521 if (_PyVerify_fd(self->fd)) {
Victor Stinnere6edec22011-01-04 00:29:35 +0000522 len = pbuf.len;
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000523 Py_BEGIN_ALLOW_THREADS
524 errno = 0;
Victor Stinnere6edec22011-01-04 00:29:35 +0000525#if defined(MS_WIN64) || defined(MS_WINDOWS)
526 if (len > INT_MAX)
527 len = INT_MAX;
528 n = read(self->fd, pbuf.buf, (int)len);
529#else
Victor Stinner72344792011-01-11 00:04:12 +0000530 n = read(self->fd, pbuf.buf, len);
Victor Stinnere6edec22011-01-04 00:29:35 +0000531#endif
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000532 Py_END_ALLOW_THREADS
533 } else
534 n = -1;
535 PyBuffer_Release(&pbuf);
536 if (n < 0) {
537 if (errno == EAGAIN)
538 Py_RETURN_NONE;
539 PyErr_SetFromErrno(PyExc_IOError);
540 return NULL;
541 }
Guido van Rossuma9e20242007-03-08 00:43:48 +0000542
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000543 return PyLong_FromSsize_t(n);
Guido van Rossuma9e20242007-03-08 00:43:48 +0000544}
545
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000546static size_t
Victor Stinnere9d44ccb2011-05-26 00:16:44 +0200547new_buffersize(fileio *self, size_t currentsize
548#ifdef HAVE_FSTAT
Victor Stinnera2a64772011-10-11 22:45:02 +0200549 , Py_off_t pos, Py_off_t end
Victor Stinnere9d44ccb2011-05-26 00:16:44 +0200550#endif
551 )
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000552{
553#ifdef HAVE_FSTAT
Victor Stinnera2a64772011-10-11 22:45:02 +0200554 if (end != (Py_off_t)-1) {
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000555 /* Files claiming a size smaller than SMALLCHUNK may
556 actually be streaming pseudo-files. In this case, we
557 apply the more aggressive algorithm below.
558 */
559 if (end >= SMALLCHUNK && end >= pos && pos >= 0) {
560 /* Add 1 so if the file were to grow we'd notice. */
Victor Stinnerc5af7732011-10-11 23:00:31 +0200561 Py_off_t bufsize = currentsize + end - pos + 1;
562 if (bufsize < PY_SSIZE_T_MAX)
563 return (size_t)bufsize;
564 else
565 return PY_SSIZE_T_MAX;
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000566 }
567 }
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000568#endif
Nadeem Vawdad41a98b2011-10-13 13:34:16 +0200569 /* Expand the buffer by an amount proportional to the current size,
570 giving us amortized linear-time behavior. Use a less-than-double
571 growth factor to avoid excessive allocation. */
572 return currentsize + (currentsize >> 3) + 6;
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000573}
574
Guido van Rossum7165cb12007-07-10 06:54:34 +0000575static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000576fileio_readall(fileio *self)
Guido van Rossum7165cb12007-07-10 06:54:34 +0000577{
Victor Stinnere9d44ccb2011-05-26 00:16:44 +0200578#ifdef HAVE_FSTAT
579 struct stat st;
Victor Stinnera2a64772011-10-11 22:45:02 +0200580 Py_off_t pos, end;
Victor Stinnere9d44ccb2011-05-26 00:16:44 +0200581#endif
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000582 PyObject *result;
583 Py_ssize_t total = 0;
584 int n;
Victor Stinnere9d44ccb2011-05-26 00:16:44 +0200585 size_t newsize;
Guido van Rossum7165cb12007-07-10 06:54:34 +0000586
Victor Stinnerb79f28c2011-05-25 22:09:03 +0200587 if (self->fd < 0)
588 return err_closed();
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000589 if (!_PyVerify_fd(self->fd))
590 return PyErr_SetFromErrno(PyExc_IOError);
Kristján Valur Jónssona8abe862009-03-24 15:27:42 +0000591
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000592 result = PyBytes_FromStringAndSize(NULL, SMALLCHUNK);
593 if (result == NULL)
594 return NULL;
Guido van Rossum7165cb12007-07-10 06:54:34 +0000595
Victor Stinnere9d44ccb2011-05-26 00:16:44 +0200596#ifdef HAVE_FSTAT
597#if defined(MS_WIN64) || defined(MS_WINDOWS)
598 pos = _lseeki64(self->fd, 0L, SEEK_CUR);
599#else
600 pos = lseek(self->fd, 0L, SEEK_CUR);
601#endif
602 if (fstat(self->fd, &st) == 0)
603 end = st.st_size;
604 else
Victor Stinnera2a64772011-10-11 22:45:02 +0200605 end = (Py_off_t)-1;
Victor Stinnere9d44ccb2011-05-26 00:16:44 +0200606#endif
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000607 while (1) {
Victor Stinnere9d44ccb2011-05-26 00:16:44 +0200608#ifdef HAVE_FSTAT
609 newsize = new_buffersize(self, total, pos, end);
610#else
611 newsize = new_buffersize(self, total);
612#endif
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000613 if (newsize > PY_SSIZE_T_MAX || newsize <= 0) {
614 PyErr_SetString(PyExc_OverflowError,
615 "unbounded read returned more bytes "
616 "than a Python string can hold ");
617 Py_DECREF(result);
618 return NULL;
619 }
Christian Heimesa872de52008-12-05 08:26:55 +0000620
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000621 if (PyBytes_GET_SIZE(result) < (Py_ssize_t)newsize) {
622 if (_PyBytes_Resize(&result, newsize) < 0) {
623 if (total == 0) {
624 Py_DECREF(result);
625 return NULL;
626 }
627 PyErr_Clear();
628 break;
629 }
630 }
631 Py_BEGIN_ALLOW_THREADS
632 errno = 0;
633 n = read(self->fd,
634 PyBytes_AS_STRING(result) + total,
635 newsize - total);
636 Py_END_ALLOW_THREADS
637 if (n == 0)
638 break;
639 if (n < 0) {
640 if (total > 0)
641 break;
642 if (errno == EAGAIN) {
643 Py_DECREF(result);
644 Py_RETURN_NONE;
645 }
646 Py_DECREF(result);
647 PyErr_SetFromErrno(PyExc_IOError);
648 return NULL;
649 }
650 total += n;
Victor Stinnere9d44ccb2011-05-26 00:16:44 +0200651#ifdef HAVE_FSTAT
652 pos += n;
653#endif
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000654 }
Guido van Rossum7165cb12007-07-10 06:54:34 +0000655
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000656 if (PyBytes_GET_SIZE(result) > total) {
657 if (_PyBytes_Resize(&result, total) < 0) {
658 /* This should never happen, but just in case */
659 Py_DECREF(result);
660 return NULL;
661 }
662 }
663 return result;
Guido van Rossum7165cb12007-07-10 06:54:34 +0000664}
665
Guido van Rossuma9e20242007-03-08 00:43:48 +0000666static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000667fileio_read(fileio *self, PyObject *args)
Guido van Rossuma9e20242007-03-08 00:43:48 +0000668{
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000669 char *ptr;
670 Py_ssize_t n;
671 Py_ssize_t size = -1;
672 PyObject *bytes;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000673
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000674 if (self->fd < 0)
675 return err_closed();
676 if (!self->readable)
677 return err_mode("reading");
Guido van Rossuma9e20242007-03-08 00:43:48 +0000678
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000679 if (!PyArg_ParseTuple(args, "|O&", &_PyIO_ConvertSsize_t, &size))
680 return NULL;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000681
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000682 if (size < 0) {
683 return fileio_readall(self);
684 }
Guido van Rossumc2f93dc2007-05-24 00:50:02 +0000685
Victor Stinnerc655a722011-07-05 11:31:49 +0200686#if defined(MS_WIN64) || defined(MS_WINDOWS)
687 if (size > INT_MAX)
688 size = INT_MAX;
689#endif
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;
Victor Stinnerc655a722011-07-05 11:31:49 +0200698#if defined(MS_WIN64) || defined(MS_WINDOWS)
699 n = read(self->fd, ptr, (int)size);
700#else
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000701 n = read(self->fd, ptr, size);
Victor Stinnerc655a722011-07-05 11:31:49 +0200702#endif
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000703 Py_END_ALLOW_THREADS
704 } else
705 n = -1;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000706
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000707 if (n < 0) {
708 Py_DECREF(bytes);
709 if (errno == EAGAIN)
710 Py_RETURN_NONE;
711 PyErr_SetFromErrno(PyExc_IOError);
712 return NULL;
713 }
Guido van Rossuma9e20242007-03-08 00:43:48 +0000714
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000715 if (n != size) {
716 if (_PyBytes_Resize(&bytes, n) < 0) {
717 Py_DECREF(bytes);
718 return NULL;
719 }
720 }
Guido van Rossuma9e20242007-03-08 00:43:48 +0000721
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000722 return (PyObject *) bytes;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000723}
724
725static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000726fileio_write(fileio *self, PyObject *args)
Guido van Rossuma9e20242007-03-08 00:43:48 +0000727{
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000728 Py_buffer pbuf;
Victor Stinnere6edec22011-01-04 00:29:35 +0000729 Py_ssize_t n, len;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000730
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000731 if (self->fd < 0)
732 return err_closed();
733 if (!self->writable)
734 return err_mode("writing");
Guido van Rossum53807da2007-04-10 19:01:47 +0000735
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000736 if (!PyArg_ParseTuple(args, "y*", &pbuf))
737 return NULL;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000738
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000739 if (_PyVerify_fd(self->fd)) {
740 Py_BEGIN_ALLOW_THREADS
741 errno = 0;
Victor Stinnere6edec22011-01-04 00:29:35 +0000742 len = pbuf.len;
743#if defined(MS_WIN64) || defined(MS_WINDOWS)
Victor Stinnere0daff12011-03-20 23:36:35 +0100744 if (len > 32767 && isatty(self->fd)) {
745 /* Issue #11395: the Windows console returns an error (12: not
746 enough space error) on writing into stdout if stdout mode is
747 binary and the length is greater than 66,000 bytes (or less,
748 depending on heap usage). */
749 len = 32767;
750 }
751 else if (len > INT_MAX)
Victor Stinnere6edec22011-01-04 00:29:35 +0000752 len = INT_MAX;
753 n = write(self->fd, pbuf.buf, (int)len);
754#else
Victor Stinner72344792011-01-11 00:04:12 +0000755 n = write(self->fd, pbuf.buf, len);
Victor Stinnere6edec22011-01-04 00:29:35 +0000756#endif
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000757 Py_END_ALLOW_THREADS
758 } else
759 n = -1;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000760
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000761 PyBuffer_Release(&pbuf);
Martin v. Löwis423be952008-08-13 15:53:07 +0000762
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000763 if (n < 0) {
764 if (errno == EAGAIN)
765 Py_RETURN_NONE;
766 PyErr_SetFromErrno(PyExc_IOError);
767 return NULL;
768 }
Guido van Rossuma9e20242007-03-08 00:43:48 +0000769
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000770 return PyLong_FromSsize_t(n);
Guido van Rossuma9e20242007-03-08 00:43:48 +0000771}
772
Guido van Rossum53807da2007-04-10 19:01:47 +0000773/* XXX Windows support below is likely incomplete */
774
Guido van Rossum53807da2007-04-10 19:01:47 +0000775/* Cribbed from posix_lseek() */
776static PyObject *
777portable_lseek(int fd, PyObject *posobj, int whence)
778{
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000779 Py_off_t pos, res;
Guido van Rossum53807da2007-04-10 19:01:47 +0000780
781#ifdef SEEK_SET
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000782 /* Turn 0, 1, 2 into SEEK_{SET,CUR,END} */
783 switch (whence) {
Guido van Rossum53807da2007-04-10 19:01:47 +0000784#if SEEK_SET != 0
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000785 case 0: whence = SEEK_SET; break;
Guido van Rossum53807da2007-04-10 19:01:47 +0000786#endif
787#if SEEK_CUR != 1
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000788 case 1: whence = SEEK_CUR; break;
Guido van Rossum53807da2007-04-10 19:01:47 +0000789#endif
Antoine Pitrou4f7945f2009-01-20 11:42:11 +0000790#if SEEK_END != 2
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000791 case 2: whence = SEEK_END; break;
Guido van Rossum53807da2007-04-10 19:01:47 +0000792#endif
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000793 }
Guido van Rossum53807da2007-04-10 19:01:47 +0000794#endif /* SEEK_SET */
795
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000796 if (posobj == NULL)
797 pos = 0;
798 else {
799 if(PyFloat_Check(posobj)) {
800 PyErr_SetString(PyExc_TypeError, "an integer is required");
801 return NULL;
802 }
Alexandre Vassalotti77250f42008-05-06 19:48:38 +0000803#if defined(HAVE_LARGEFILE_SUPPORT)
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000804 pos = PyLong_AsLongLong(posobj);
Guido van Rossum53807da2007-04-10 19:01:47 +0000805#else
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000806 pos = PyLong_AsLong(posobj);
Guido van Rossum53807da2007-04-10 19:01:47 +0000807#endif
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000808 if (PyErr_Occurred())
809 return NULL;
810 }
Guido van Rossum53807da2007-04-10 19:01:47 +0000811
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000812 if (_PyVerify_fd(fd)) {
813 Py_BEGIN_ALLOW_THREADS
Guido van Rossum53807da2007-04-10 19:01:47 +0000814#if defined(MS_WIN64) || defined(MS_WINDOWS)
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000815 res = _lseeki64(fd, pos, whence);
Guido van Rossum53807da2007-04-10 19:01:47 +0000816#else
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000817 res = lseek(fd, pos, whence);
Guido van Rossum53807da2007-04-10 19:01:47 +0000818#endif
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000819 Py_END_ALLOW_THREADS
820 } else
821 res = -1;
822 if (res < 0)
823 return PyErr_SetFromErrno(PyExc_IOError);
Guido van Rossum53807da2007-04-10 19:01:47 +0000824
Alexandre Vassalotti77250f42008-05-06 19:48:38 +0000825#if defined(HAVE_LARGEFILE_SUPPORT)
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000826 return PyLong_FromLongLong(res);
Alexandre Vassalotti77250f42008-05-06 19:48:38 +0000827#else
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000828 return PyLong_FromLong(res);
Guido van Rossum53807da2007-04-10 19:01:47 +0000829#endif
830}
831
Guido van Rossuma9e20242007-03-08 00:43:48 +0000832static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000833fileio_seek(fileio *self, PyObject *args)
Guido van Rossuma9e20242007-03-08 00:43:48 +0000834{
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000835 PyObject *posobj;
836 int whence = 0;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000837
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000838 if (self->fd < 0)
839 return err_closed();
Guido van Rossuma9e20242007-03-08 00:43:48 +0000840
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000841 if (!PyArg_ParseTuple(args, "O|i", &posobj, &whence))
842 return NULL;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000843
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000844 return portable_lseek(self->fd, posobj, whence);
Guido van Rossuma9e20242007-03-08 00:43:48 +0000845}
846
847static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000848fileio_tell(fileio *self, PyObject *args)
Guido van Rossuma9e20242007-03-08 00:43:48 +0000849{
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000850 if (self->fd < 0)
851 return err_closed();
Guido van Rossuma9e20242007-03-08 00:43:48 +0000852
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000853 return portable_lseek(self->fd, NULL, 1);
Guido van Rossuma9e20242007-03-08 00:43:48 +0000854}
855
Thomas Hellerc6a55ee2007-07-11 12:45:46 +0000856#ifdef HAVE_FTRUNCATE
Guido van Rossuma9e20242007-03-08 00:43:48 +0000857static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000858fileio_truncate(fileio *self, PyObject *args)
Guido van Rossuma9e20242007-03-08 00:43:48 +0000859{
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000860 PyObject *posobj = NULL; /* the new size wanted by the user */
Antoine Pitrou905a2ff2010-01-31 22:47:27 +0000861#ifndef MS_WINDOWS
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000862 Py_off_t pos;
Antoine Pitrou905a2ff2010-01-31 22:47:27 +0000863#endif
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000864 int ret;
865 int fd;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000866
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000867 fd = self->fd;
868 if (fd < 0)
869 return err_closed();
870 if (!self->writable)
871 return err_mode("writing");
Guido van Rossuma9e20242007-03-08 00:43:48 +0000872
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000873 if (!PyArg_ParseTuple(args, "|O", &posobj))
874 return NULL;
Guido van Rossum53807da2007-04-10 19:01:47 +0000875
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000876 if (posobj == Py_None || posobj == NULL) {
877 /* Get the current position. */
878 posobj = portable_lseek(fd, NULL, 1);
879 if (posobj == NULL)
880 return NULL;
881 }
882 else {
883 Py_INCREF(posobj);
884 }
Guido van Rossum53807da2007-04-10 19:01:47 +0000885
Thomas Hellerfdeee3a2007-07-12 11:21:36 +0000886#ifdef MS_WINDOWS
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000887 /* MS _chsize doesn't work if newsize doesn't fit in 32 bits,
888 so don't even try using it. */
889 {
890 PyObject *oldposobj, *tempposobj;
891 HANDLE hFile;
Antoine Pitrou905a2ff2010-01-31 22:47:27 +0000892
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000893 /* we save the file pointer position */
894 oldposobj = portable_lseek(fd, NULL, 1);
895 if (oldposobj == NULL) {
896 Py_DECREF(posobj);
897 return NULL;
898 }
Thomas Hellerfdeee3a2007-07-12 11:21:36 +0000899
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000900 /* we then move to the truncation position */
901 tempposobj = portable_lseek(fd, posobj, 0);
902 if (tempposobj == NULL) {
903 Py_DECREF(oldposobj);
904 Py_DECREF(posobj);
905 return NULL;
906 }
907 Py_DECREF(tempposobj);
Antoine Pitrou905a2ff2010-01-31 22:47:27 +0000908
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000909 /* Truncate. Note that this may grow the file! */
910 Py_BEGIN_ALLOW_THREADS
911 errno = 0;
912 hFile = (HANDLE)_get_osfhandle(fd);
913 ret = hFile == (HANDLE)-1; /* testing for INVALID_HANDLE value */
914 if (ret == 0) {
915 ret = SetEndOfFile(hFile) == 0;
916 if (ret)
917 errno = EACCES;
918 }
919 Py_END_ALLOW_THREADS
920
921 /* we restore the file pointer position in any case */
922 tempposobj = portable_lseek(fd, oldposobj, 0);
923 Py_DECREF(oldposobj);
924 if (tempposobj == NULL) {
925 Py_DECREF(posobj);
926 return NULL;
927 }
928 Py_DECREF(tempposobj);
929 }
Thomas Hellerfdeee3a2007-07-12 11:21:36 +0000930#else
Antoine Pitrou905a2ff2010-01-31 22:47:27 +0000931
932#if defined(HAVE_LARGEFILE_SUPPORT)
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000933 pos = PyLong_AsLongLong(posobj);
Antoine Pitrou905a2ff2010-01-31 22:47:27 +0000934#else
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000935 pos = PyLong_AsLong(posobj);
Antoine Pitrou905a2ff2010-01-31 22:47:27 +0000936#endif
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000937 if (PyErr_Occurred()){
938 Py_DECREF(posobj);
939 return NULL;
940 }
Antoine Pitrou905a2ff2010-01-31 22:47:27 +0000941
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000942 Py_BEGIN_ALLOW_THREADS
943 errno = 0;
944 ret = ftruncate(fd, pos);
945 Py_END_ALLOW_THREADS
Antoine Pitrou905a2ff2010-01-31 22:47:27 +0000946
Thomas Hellerfdeee3a2007-07-12 11:21:36 +0000947#endif /* !MS_WINDOWS */
Guido van Rossuma9e20242007-03-08 00:43:48 +0000948
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000949 if (ret != 0) {
950 Py_DECREF(posobj);
951 PyErr_SetFromErrno(PyExc_IOError);
952 return NULL;
953 }
Guido van Rossuma9e20242007-03-08 00:43:48 +0000954
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000955 return posobj;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000956}
Antoine Pitrou905a2ff2010-01-31 22:47:27 +0000957#endif /* HAVE_FTRUNCATE */
Guido van Rossum53807da2007-04-10 19:01:47 +0000958
959static char *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000960mode_string(fileio *self)
Guido van Rossum53807da2007-04-10 19:01:47 +0000961{
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000962 if (self->readable) {
963 if (self->writable)
964 return "rb+";
965 else
966 return "rb";
967 }
968 else
969 return "wb";
Guido van Rossum53807da2007-04-10 19:01:47 +0000970}
Guido van Rossuma9e20242007-03-08 00:43:48 +0000971
972static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000973fileio_repr(fileio *self)
Guido van Rossuma9e20242007-03-08 00:43:48 +0000974{
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000975 PyObject *nameobj, *res;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000976
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000977 if (self->fd < 0)
978 return PyUnicode_FromFormat("<_io.FileIO [closed]>");
Antoine Pitrou716c4442009-05-23 19:04:03 +0000979
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000980 nameobj = PyObject_GetAttrString((PyObject *) self, "name");
981 if (nameobj == NULL) {
982 if (PyErr_ExceptionMatches(PyExc_AttributeError))
983 PyErr_Clear();
984 else
985 return NULL;
986 res = PyUnicode_FromFormat("<_io.FileIO fd=%d mode='%s'>",
987 self->fd, mode_string(self));
988 }
989 else {
990 res = PyUnicode_FromFormat("<_io.FileIO name=%R mode='%s'>",
991 nameobj, mode_string(self));
992 Py_DECREF(nameobj);
993 }
994 return res;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000995}
996
997static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000998fileio_isatty(fileio *self)
Guido van Rossuma9e20242007-03-08 00:43:48 +0000999{
Antoine Pitrouae4b4722010-05-05 16:31:07 +00001000 long res;
Guido van Rossum53807da2007-04-10 19:01:47 +00001001
Antoine Pitrouae4b4722010-05-05 16:31:07 +00001002 if (self->fd < 0)
1003 return err_closed();
1004 Py_BEGIN_ALLOW_THREADS
1005 res = isatty(self->fd);
1006 Py_END_ALLOW_THREADS
1007 return PyBool_FromLong(res);
Guido van Rossuma9e20242007-03-08 00:43:48 +00001008}
1009
Antoine Pitrou243757e2010-11-05 21:15:39 +00001010static PyObject *
1011fileio_getstate(fileio *self)
1012{
1013 PyErr_Format(PyExc_TypeError,
1014 "cannot serialize '%s' object", Py_TYPE(self)->tp_name);
1015 return NULL;
1016}
1017
Guido van Rossuma9e20242007-03-08 00:43:48 +00001018
1019PyDoc_STRVAR(fileio_doc,
1020"file(name: str[, mode: str]) -> file IO object\n"
1021"\n"
1022"Open a file. The mode can be 'r', 'w' or 'a' for reading (default),\n"
Antoine Pitrouae4b4722010-05-05 16:31:07 +00001023"writing or appending. The file will be created if it doesn't exist\n"
Guido van Rossuma9e20242007-03-08 00:43:48 +00001024"when opened for writing or appending; it will be truncated when\n"
1025"opened for writing. Add a '+' to the mode to allow simultaneous\n"
1026"reading and writing.");
1027
1028PyDoc_STRVAR(read_doc,
1029"read(size: int) -> bytes. read at most size bytes, returned as bytes.\n"
1030"\n"
1031"Only makes one system call, so less data may be returned than requested\n"
Guido van Rossum7165cb12007-07-10 06:54:34 +00001032"In non-blocking mode, returns None if no data is available.\n"
1033"On end-of-file, returns ''.");
1034
1035PyDoc_STRVAR(readall_doc,
1036"readall() -> bytes. read all data from the file, returned as bytes.\n"
1037"\n"
1038"In non-blocking mode, returns as much as is immediately available,\n"
1039"or None if no data is available. On end-of-file, returns ''.");
Guido van Rossuma9e20242007-03-08 00:43:48 +00001040
1041PyDoc_STRVAR(write_doc,
1042"write(b: bytes) -> int. Write bytes b to file, return number written.\n"
1043"\n"
1044"Only makes one system call, so not all of the data may be written.\n"
1045"The number of bytes actually written is returned.");
1046
1047PyDoc_STRVAR(fileno_doc,
1048"fileno() -> int. \"file descriptor\".\n"
1049"\n"
1050"This is needed for lower-level file interfaces, such the fcntl module.");
1051
1052PyDoc_STRVAR(seek_doc,
1053"seek(offset: int[, whence: int]) -> None. Move to new file position.\n"
1054"\n"
1055"Argument offset is a byte count. Optional argument whence defaults to\n"
1056"0 (offset from start of file, offset should be >= 0); other values are 1\n"
1057"(move relative to current position, positive or negative), and 2 (move\n"
1058"relative to end of file, usually negative, although many platforms allow\n"
1059"seeking beyond the end of a file)."
1060"\n"
1061"Note that not all file objects are seekable.");
1062
Thomas Hellerc6a55ee2007-07-11 12:45:46 +00001063#ifdef HAVE_FTRUNCATE
Guido van Rossuma9e20242007-03-08 00:43:48 +00001064PyDoc_STRVAR(truncate_doc,
Antoine Pitrouae4b4722010-05-05 16:31:07 +00001065"truncate([size: int]) -> None. Truncate the file to at most size bytes.\n"
Guido van Rossuma9e20242007-03-08 00:43:48 +00001066"\n"
Alexandre Vassalotti77250f42008-05-06 19:48:38 +00001067"Size defaults to the current file position, as returned by tell()."
1068"The current file position is changed to the value of size.");
Thomas Hellerc6a55ee2007-07-11 12:45:46 +00001069#endif
Guido van Rossuma9e20242007-03-08 00:43:48 +00001070
1071PyDoc_STRVAR(tell_doc,
Antoine Pitrouae4b4722010-05-05 16:31:07 +00001072"tell() -> int. Current file position");
Guido van Rossuma9e20242007-03-08 00:43:48 +00001073
1074PyDoc_STRVAR(readinto_doc,
Benjamin Peterson9a8082f2009-03-05 00:55:56 +00001075"readinto() -> Same as RawIOBase.readinto().");
Guido van Rossuma9e20242007-03-08 00:43:48 +00001076
1077PyDoc_STRVAR(close_doc,
1078"close() -> None. Close the file.\n"
1079"\n"
1080"A closed file cannot be used for further I/O operations. close() may be\n"
1081"called more than once without error. Changes the fileno to -1.");
1082
1083PyDoc_STRVAR(isatty_doc,
1084"isatty() -> bool. True if the file is connected to a tty device.");
1085
Guido van Rossuma9e20242007-03-08 00:43:48 +00001086PyDoc_STRVAR(seekable_doc,
1087"seekable() -> bool. True if file supports random-access.");
1088
1089PyDoc_STRVAR(readable_doc,
1090"readable() -> bool. True if file was opened in a read mode.");
1091
1092PyDoc_STRVAR(writable_doc,
1093"writable() -> bool. True if file was opened in a write mode.");
1094
1095static PyMethodDef fileio_methods[] = {
Antoine Pitrouae4b4722010-05-05 16:31:07 +00001096 {"read", (PyCFunction)fileio_read, METH_VARARGS, read_doc},
1097 {"readall", (PyCFunction)fileio_readall, METH_NOARGS, readall_doc},
1098 {"readinto", (PyCFunction)fileio_readinto, METH_VARARGS, readinto_doc},
1099 {"write", (PyCFunction)fileio_write, METH_VARARGS, write_doc},
1100 {"seek", (PyCFunction)fileio_seek, METH_VARARGS, seek_doc},
1101 {"tell", (PyCFunction)fileio_tell, METH_VARARGS, tell_doc},
Thomas Hellerc6a55ee2007-07-11 12:45:46 +00001102#ifdef HAVE_FTRUNCATE
Antoine Pitrouae4b4722010-05-05 16:31:07 +00001103 {"truncate", (PyCFunction)fileio_truncate, METH_VARARGS, truncate_doc},
Thomas Hellerc6a55ee2007-07-11 12:45:46 +00001104#endif
Antoine Pitrouae4b4722010-05-05 16:31:07 +00001105 {"close", (PyCFunction)fileio_close, METH_NOARGS, close_doc},
1106 {"seekable", (PyCFunction)fileio_seekable, METH_NOARGS, seekable_doc},
1107 {"readable", (PyCFunction)fileio_readable, METH_NOARGS, readable_doc},
1108 {"writable", (PyCFunction)fileio_writable, METH_NOARGS, writable_doc},
1109 {"fileno", (PyCFunction)fileio_fileno, METH_NOARGS, fileno_doc},
1110 {"isatty", (PyCFunction)fileio_isatty, METH_NOARGS, isatty_doc},
Antoine Pitroue033e062010-10-29 10:38:18 +00001111 {"_dealloc_warn", (PyCFunction)fileio_dealloc_warn, METH_O, NULL},
Antoine Pitrou243757e2010-11-05 21:15:39 +00001112 {"__getstate__", (PyCFunction)fileio_getstate, METH_NOARGS, NULL},
Antoine Pitrouae4b4722010-05-05 16:31:07 +00001113 {NULL, NULL} /* sentinel */
Guido van Rossuma9e20242007-03-08 00:43:48 +00001114};
1115
Guido van Rossum53807da2007-04-10 19:01:47 +00001116/* 'closed' and 'mode' are attributes for backwards compatibility reasons. */
1117
Guido van Rossumb0428152007-04-08 17:44:42 +00001118static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +00001119get_closed(fileio *self, void *closure)
Guido van Rossumb0428152007-04-08 17:44:42 +00001120{
Antoine Pitrouae4b4722010-05-05 16:31:07 +00001121 return PyBool_FromLong((long)(self->fd < 0));
Guido van Rossum53807da2007-04-10 19:01:47 +00001122}
1123
1124static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +00001125get_closefd(fileio *self, void *closure)
Christian Heimesecc42a22008-11-05 19:30:32 +00001126{
Antoine Pitrouae4b4722010-05-05 16:31:07 +00001127 return PyBool_FromLong((long)(self->closefd));
Christian Heimesecc42a22008-11-05 19:30:32 +00001128}
1129
1130static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +00001131get_mode(fileio *self, void *closure)
Guido van Rossum53807da2007-04-10 19:01:47 +00001132{
Antoine Pitrouae4b4722010-05-05 16:31:07 +00001133 return PyUnicode_FromString(mode_string(self));
Guido van Rossumb0428152007-04-08 17:44:42 +00001134}
1135
1136static PyGetSetDef fileio_getsetlist[] = {
Antoine Pitrouae4b4722010-05-05 16:31:07 +00001137 {"closed", (getter)get_closed, NULL, "True if the file is closed"},
1138 {"closefd", (getter)get_closefd, NULL,
1139 "True if the file descriptor will be closed"},
1140 {"mode", (getter)get_mode, NULL, "String giving the file mode"},
1141 {NULL},
Guido van Rossumb0428152007-04-08 17:44:42 +00001142};
1143
Guido van Rossuma9e20242007-03-08 00:43:48 +00001144PyTypeObject PyFileIO_Type = {
Antoine Pitrouae4b4722010-05-05 16:31:07 +00001145 PyVarObject_HEAD_INIT(NULL, 0)
1146 "_io.FileIO",
1147 sizeof(fileio),
1148 0,
1149 (destructor)fileio_dealloc, /* tp_dealloc */
1150 0, /* tp_print */
1151 0, /* tp_getattr */
1152 0, /* tp_setattr */
1153 0, /* tp_reserved */
1154 (reprfunc)fileio_repr, /* tp_repr */
1155 0, /* tp_as_number */
1156 0, /* tp_as_sequence */
1157 0, /* tp_as_mapping */
1158 0, /* tp_hash */
1159 0, /* tp_call */
1160 0, /* tp_str */
1161 PyObject_GenericGetAttr, /* tp_getattro */
1162 0, /* tp_setattro */
1163 0, /* tp_as_buffer */
1164 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE
1165 | Py_TPFLAGS_HAVE_GC, /* tp_flags */
1166 fileio_doc, /* tp_doc */
1167 (traverseproc)fileio_traverse, /* tp_traverse */
1168 (inquiry)fileio_clear, /* tp_clear */
1169 0, /* tp_richcompare */
1170 offsetof(fileio, weakreflist), /* tp_weaklistoffset */
1171 0, /* tp_iter */
1172 0, /* tp_iternext */
1173 fileio_methods, /* tp_methods */
1174 0, /* tp_members */
1175 fileio_getsetlist, /* tp_getset */
1176 0, /* tp_base */
1177 0, /* tp_dict */
1178 0, /* tp_descr_get */
1179 0, /* tp_descr_set */
1180 offsetof(fileio, dict), /* tp_dictoffset */
1181 fileio_init, /* tp_init */
1182 PyType_GenericAlloc, /* tp_alloc */
1183 fileio_new, /* tp_new */
1184 PyObject_GC_Del, /* tp_free */
Guido van Rossuma9e20242007-03-08 00:43:48 +00001185};