blob: dc5945504da89cbbc3f46a306f370ac9bf4e5ffe [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{
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200131 _Py_identifier(close);
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000132 if (!self->closefd) {
133 self->fd = -1;
134 Py_RETURN_NONE;
135 }
Antoine Pitroue033e062010-10-29 10:38:18 +0000136 if (self->deallocating) {
137 PyObject *r = fileio_dealloc_warn(self, (PyObject *) self);
138 if (r)
139 Py_DECREF(r);
140 else
141 PyErr_Clear();
142 }
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000143 errno = internal_close(self);
144 if (errno < 0)
145 return NULL;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000146
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200147 return _PyObject_CallMethodId((PyObject*)&PyRawIOBase_Type,
148 &PyId_close, "O", self);
Guido van Rossuma9e20242007-03-08 00:43:48 +0000149}
150
151static PyObject *
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000152fileio_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
Guido van Rossuma9e20242007-03-08 00:43:48 +0000153{
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000154 fileio *self;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000155
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000156 assert(type != NULL && type->tp_alloc != NULL);
Guido van Rossuma9e20242007-03-08 00:43:48 +0000157
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000158 self = (fileio *) type->tp_alloc(type, 0);
159 if (self != NULL) {
160 self->fd = -1;
161 self->readable = 0;
162 self->writable = 0;
163 self->seekable = -1;
164 self->closefd = 1;
165 self->weakreflist = NULL;
166 }
Guido van Rossuma9e20242007-03-08 00:43:48 +0000167
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000168 return (PyObject *) self;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000169}
170
171/* On Unix, open will succeed for directories.
172 In Python, there should be no file objects referring to
173 directories, so we need a check. */
174
175static int
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000176dircheck(fileio* self, const char *name)
Guido van Rossuma9e20242007-03-08 00:43:48 +0000177{
178#if defined(HAVE_FSTAT) && defined(S_IFDIR) && defined(EISDIR)
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000179 struct stat buf;
180 if (self->fd < 0)
181 return 0;
182 if (fstat(self->fd, &buf) == 0 && S_ISDIR(buf.st_mode)) {
183 char *msg = strerror(EISDIR);
184 PyObject *exc;
185 if (internal_close(self))
186 return -1;
Guido van Rossum53807da2007-04-10 19:01:47 +0000187
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000188 exc = PyObject_CallFunction(PyExc_IOError, "(iss)",
189 EISDIR, msg, name);
190 PyErr_SetObject(PyExc_IOError, exc);
191 Py_XDECREF(exc);
192 return -1;
193 }
Guido van Rossuma9e20242007-03-08 00:43:48 +0000194#endif
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000195 return 0;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000196}
197
Benjamin Peterson806d4022009-01-19 15:11:51 +0000198static int
199check_fd(int fd)
200{
201#if defined(HAVE_FSTAT)
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000202 struct stat buf;
203 if (!_PyVerify_fd(fd) || (fstat(fd, &buf) < 0 && errno == EBADF)) {
204 PyObject *exc;
205 char *msg = strerror(EBADF);
206 exc = PyObject_CallFunction(PyExc_OSError, "(is)",
207 EBADF, msg);
208 PyErr_SetObject(PyExc_OSError, exc);
209 Py_XDECREF(exc);
210 return -1;
211 }
Benjamin Peterson806d4022009-01-19 15:11:51 +0000212#endif
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000213 return 0;
Benjamin Peterson806d4022009-01-19 15:11:51 +0000214}
215
Guido van Rossuma9e20242007-03-08 00:43:48 +0000216
217static int
218fileio_init(PyObject *oself, PyObject *args, PyObject *kwds)
219{
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000220 fileio *self = (fileio *) oself;
221 static char *kwlist[] = {"file", "mode", "closefd", NULL};
222 const char *name = NULL;
223 PyObject *nameobj, *stringobj = NULL;
224 char *mode = "r";
225 char *s;
Thomas Helleraf2be262007-07-12 11:03:13 +0000226#ifdef MS_WINDOWS
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000227 Py_UNICODE *widename = NULL;
Thomas Helleraf2be262007-07-12 11:03:13 +0000228#endif
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000229 int ret = 0;
230 int rwa = 0, plus = 0, append = 0;
231 int flags = 0;
232 int fd = -1;
233 int closefd = 1;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000234
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000235 assert(PyFileIO_Check(oself));
236 if (self->fd >= 0) {
237 /* Have to close the existing file first. */
238 if (internal_close(self) < 0)
239 return -1;
240 }
Guido van Rossuma9e20242007-03-08 00:43:48 +0000241
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000242 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|si:fileio",
243 kwlist, &nameobj, &mode, &closefd))
244 return -1;
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000245
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000246 if (PyFloat_Check(nameobj)) {
247 PyErr_SetString(PyExc_TypeError,
248 "integer argument expected, got float");
249 return -1;
250 }
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000251
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000252 fd = PyLong_AsLong(nameobj);
253 if (fd < 0) {
254 if (!PyErr_Occurred()) {
255 PyErr_SetString(PyExc_ValueError,
256 "Negative filedescriptor");
257 return -1;
258 }
259 PyErr_Clear();
260 }
Guido van Rossumb0428152007-04-08 17:44:42 +0000261
Hirokazu Yamamoto8223c242009-05-17 04:21:53 +0000262#ifdef MS_WINDOWS
Victor Stinnerfe9a8612011-09-29 23:19:04 +0200263 if (PyUnicode_Check(nameobj)) {
264 widename = PyUnicode_AsUnicode(nameobj);
265 if (widename == NULL)
266 return -1;
267 } else
Guido van Rossuma9e20242007-03-08 00:43:48 +0000268#endif
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000269 if (fd < 0)
270 {
271 if (PyBytes_Check(nameobj) || PyByteArray_Check(nameobj)) {
272 Py_ssize_t namelen;
273 if (PyObject_AsCharBuffer(nameobj, &name, &namelen) < 0)
274 return -1;
275 }
276 else {
277 PyObject *u = PyUnicode_FromObject(nameobj);
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000278
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000279 if (u == NULL)
280 return -1;
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000281
Victor Stinnerae6265f2010-05-15 16:27:27 +0000282 stringobj = PyUnicode_EncodeFSDefault(u);
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000283 Py_DECREF(u);
284 if (stringobj == NULL)
285 return -1;
286 if (!PyBytes_Check(stringobj)) {
287 PyErr_SetString(PyExc_TypeError,
288 "encoder failed to return bytes");
289 goto error;
290 }
291 name = PyBytes_AS_STRING(stringobj);
292 }
293 }
Guido van Rossuma9e20242007-03-08 00:43:48 +0000294
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000295 s = mode;
296 while (*s) {
297 switch (*s++) {
298 case 'r':
299 if (rwa) {
300 bad_mode:
301 PyErr_SetString(PyExc_ValueError,
Georg Brandl28928ae2010-10-21 13:45:52 +0000302 "Must have exactly one of read/write/append "
303 "mode and at most one plus");
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000304 goto error;
305 }
306 rwa = 1;
307 self->readable = 1;
308 break;
309 case 'w':
310 if (rwa)
311 goto bad_mode;
312 rwa = 1;
313 self->writable = 1;
314 flags |= O_CREAT | O_TRUNC;
315 break;
316 case 'a':
317 if (rwa)
318 goto bad_mode;
319 rwa = 1;
320 self->writable = 1;
321 flags |= O_CREAT;
322 append = 1;
323 break;
324 case 'b':
325 break;
326 case '+':
327 if (plus)
328 goto bad_mode;
329 self->readable = self->writable = 1;
330 plus = 1;
331 break;
332 default:
333 PyErr_Format(PyExc_ValueError,
334 "invalid mode: %.200s", mode);
335 goto error;
336 }
337 }
Guido van Rossuma9e20242007-03-08 00:43:48 +0000338
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000339 if (!rwa)
340 goto bad_mode;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000341
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000342 if (self->readable && self->writable)
343 flags |= O_RDWR;
344 else if (self->readable)
345 flags |= O_RDONLY;
346 else
347 flags |= O_WRONLY;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000348
349#ifdef O_BINARY
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000350 flags |= O_BINARY;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000351#endif
352
Walter Dörwald0e411482007-06-06 16:55:38 +0000353#ifdef O_APPEND
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000354 if (append)
355 flags |= O_APPEND;
Walter Dörwald0e411482007-06-06 16:55:38 +0000356#endif
357
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000358 if (fd >= 0) {
359 if (check_fd(fd))
360 goto error;
361 self->fd = fd;
362 self->closefd = closefd;
363 }
364 else {
365 self->closefd = 1;
366 if (!closefd) {
367 PyErr_SetString(PyExc_ValueError,
368 "Cannot use closefd=False with file name");
369 goto error;
370 }
Guido van Rossum2dced8b2007-10-30 17:27:30 +0000371
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000372 Py_BEGIN_ALLOW_THREADS
373 errno = 0;
Thomas Helleraf2be262007-07-12 11:03:13 +0000374#ifdef MS_WINDOWS
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000375 if (widename != NULL)
376 self->fd = _wopen(widename, flags, 0666);
377 else
Thomas Helleraf2be262007-07-12 11:03:13 +0000378#endif
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000379 self->fd = open(name, flags, 0666);
380 Py_END_ALLOW_THREADS
381 if (self->fd < 0) {
Christian Heimes0b489542007-10-31 19:20:48 +0000382#ifdef MS_WINDOWS
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000383 if (widename != NULL)
Victor Stinnerfe9a8612011-09-29 23:19:04 +0200384 PyErr_SetFromErrnoWithFilenameObject(PyExc_IOError, nameobj);
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000385 else
Christian Heimes0b489542007-10-31 19:20:48 +0000386#endif
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000387 PyErr_SetFromErrnoWithFilename(PyExc_IOError, name);
388 goto error;
389 }
Benjamin Peterson430d4692010-10-30 23:13:57 +0000390 if (dircheck(self, name) < 0)
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000391 goto error;
392 }
Guido van Rossuma9e20242007-03-08 00:43:48 +0000393
Victor Stinner89e34362011-01-07 18:47:22 +0000394#if defined(MS_WINDOWS) || defined(__CYGWIN__)
395 /* don't translate newlines (\r\n <=> \n) */
396 _setmode(self->fd, O_BINARY);
397#endif
398
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000399 if (PyObject_SetAttrString((PyObject *)self, "name", nameobj) < 0)
400 goto error;
Antoine Pitrou08838b62009-01-21 00:55:13 +0000401
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000402 if (append) {
403 /* For consistent behaviour, we explicitly seek to the
404 end of file (otherwise, it might be done only on the
405 first write()). */
406 PyObject *pos = portable_lseek(self->fd, NULL, 2);
Antoine Pitrou8d2b51b2010-10-30 16:19:14 +0000407 if (pos == NULL) {
408 if (closefd) {
409 close(self->fd);
410 self->fd = -1;
411 }
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000412 goto error;
Antoine Pitrou8d2b51b2010-10-30 16:19:14 +0000413 }
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000414 Py_DECREF(pos);
415 }
Antoine Pitrou7fb111b2009-03-04 11:14:01 +0000416
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000417 goto done;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000418
419 error:
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000420 ret = -1;
Benjamin Petersonbbb04122010-10-30 23:16:28 +0000421 if (self->fd >= 0)
422 internal_close(self);
Guido van Rossum53807da2007-04-10 19:01:47 +0000423
Guido van Rossuma9e20242007-03-08 00:43:48 +0000424 done:
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000425 Py_CLEAR(stringobj);
426 return ret;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000427}
428
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000429static int
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000430fileio_traverse(fileio *self, visitproc visit, void *arg)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000431{
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000432 Py_VISIT(self->dict);
433 return 0;
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000434}
435
436static int
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000437fileio_clear(fileio *self)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000438{
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000439 Py_CLEAR(self->dict);
440 return 0;
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000441}
442
Guido van Rossuma9e20242007-03-08 00:43:48 +0000443static void
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000444fileio_dealloc(fileio *self)
Guido van Rossuma9e20242007-03-08 00:43:48 +0000445{
Antoine Pitroue033e062010-10-29 10:38:18 +0000446 self->deallocating = 1;
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000447 if (_PyIOBase_finalize((PyObject *) self) < 0)
448 return;
449 _PyObject_GC_UNTRACK(self);
450 if (self->weakreflist != NULL)
451 PyObject_ClearWeakRefs((PyObject *) self);
452 Py_CLEAR(self->dict);
453 Py_TYPE(self)->tp_free((PyObject *)self);
Guido van Rossuma9e20242007-03-08 00:43:48 +0000454}
455
456static PyObject *
457err_closed(void)
458{
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000459 PyErr_SetString(PyExc_ValueError, "I/O operation on closed file");
460 return NULL;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000461}
462
463static PyObject *
Guido van Rossum53807da2007-04-10 19:01:47 +0000464err_mode(char *action)
465{
Antoine Pitrou0d739d72010-09-05 23:01:12 +0000466 PyErr_Format(IO_STATE->unsupported_operation,
467 "File not open for %s", action);
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000468 return NULL;
Guido van Rossum53807da2007-04-10 19:01:47 +0000469}
470
471static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000472fileio_fileno(fileio *self)
Guido van Rossuma9e20242007-03-08 00:43:48 +0000473{
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000474 if (self->fd < 0)
475 return err_closed();
476 return PyLong_FromLong((long) self->fd);
Guido van Rossuma9e20242007-03-08 00:43:48 +0000477}
478
479static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000480fileio_readable(fileio *self)
Guido van Rossuma9e20242007-03-08 00:43:48 +0000481{
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000482 if (self->fd < 0)
483 return err_closed();
484 return PyBool_FromLong((long) self->readable);
Guido van Rossuma9e20242007-03-08 00:43:48 +0000485}
486
487static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000488fileio_writable(fileio *self)
Guido van Rossuma9e20242007-03-08 00:43:48 +0000489{
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000490 if (self->fd < 0)
491 return err_closed();
492 return PyBool_FromLong((long) self->writable);
Guido van Rossuma9e20242007-03-08 00:43:48 +0000493}
494
495static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000496fileio_seekable(fileio *self)
Guido van Rossuma9e20242007-03-08 00:43:48 +0000497{
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000498 if (self->fd < 0)
499 return err_closed();
500 if (self->seekable < 0) {
501 PyObject *pos = portable_lseek(self->fd, NULL, SEEK_CUR);
502 if (pos == NULL) {
503 PyErr_Clear();
504 self->seekable = 0;
505 } else {
506 Py_DECREF(pos);
507 self->seekable = 1;
508 }
509 }
510 return PyBool_FromLong((long) self->seekable);
Guido van Rossuma9e20242007-03-08 00:43:48 +0000511}
512
513static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000514fileio_readinto(fileio *self, PyObject *args)
Guido van Rossuma9e20242007-03-08 00:43:48 +0000515{
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000516 Py_buffer pbuf;
Victor Stinnere6edec22011-01-04 00:29:35 +0000517 Py_ssize_t n, len;
Guido van Rossum53807da2007-04-10 19:01:47 +0000518
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000519 if (self->fd < 0)
520 return err_closed();
521 if (!self->readable)
522 return err_mode("reading");
Guido van Rossum53807da2007-04-10 19:01:47 +0000523
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000524 if (!PyArg_ParseTuple(args, "w*", &pbuf))
525 return NULL;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000526
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000527 if (_PyVerify_fd(self->fd)) {
Victor Stinnere6edec22011-01-04 00:29:35 +0000528 len = pbuf.len;
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000529 Py_BEGIN_ALLOW_THREADS
530 errno = 0;
Victor Stinnere6edec22011-01-04 00:29:35 +0000531#if defined(MS_WIN64) || defined(MS_WINDOWS)
532 if (len > INT_MAX)
533 len = INT_MAX;
534 n = read(self->fd, pbuf.buf, (int)len);
535#else
Victor Stinner72344792011-01-11 00:04:12 +0000536 n = read(self->fd, pbuf.buf, len);
Victor Stinnere6edec22011-01-04 00:29:35 +0000537#endif
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000538 Py_END_ALLOW_THREADS
539 } else
540 n = -1;
541 PyBuffer_Release(&pbuf);
542 if (n < 0) {
543 if (errno == EAGAIN)
544 Py_RETURN_NONE;
545 PyErr_SetFromErrno(PyExc_IOError);
546 return NULL;
547 }
Guido van Rossuma9e20242007-03-08 00:43:48 +0000548
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000549 return PyLong_FromSsize_t(n);
Guido van Rossuma9e20242007-03-08 00:43:48 +0000550}
551
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000552static size_t
Victor Stinnere9d44ccb2011-05-26 00:16:44 +0200553new_buffersize(fileio *self, size_t currentsize
554#ifdef HAVE_FSTAT
Victor Stinnera2a64772011-10-11 22:45:02 +0200555 , Py_off_t pos, Py_off_t end
Victor Stinnere9d44ccb2011-05-26 00:16:44 +0200556#endif
557 )
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000558{
559#ifdef HAVE_FSTAT
Victor Stinnera2a64772011-10-11 22:45:02 +0200560 if (end != (Py_off_t)-1) {
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000561 /* Files claiming a size smaller than SMALLCHUNK may
562 actually be streaming pseudo-files. In this case, we
563 apply the more aggressive algorithm below.
564 */
565 if (end >= SMALLCHUNK && end >= pos && pos >= 0) {
566 /* Add 1 so if the file were to grow we'd notice. */
567 return currentsize + end - pos + 1;
568 }
569 }
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000570#endif
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000571 if (currentsize > SMALLCHUNK) {
572 /* Keep doubling until we reach BIGCHUNK;
573 then keep adding BIGCHUNK. */
574 if (currentsize <= BIGCHUNK)
575 return currentsize + currentsize;
576 else
577 return currentsize + BIGCHUNK;
578 }
579 return currentsize + SMALLCHUNK;
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000580}
581
Guido van Rossum7165cb12007-07-10 06:54:34 +0000582static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000583fileio_readall(fileio *self)
Guido van Rossum7165cb12007-07-10 06:54:34 +0000584{
Victor Stinnere9d44ccb2011-05-26 00:16:44 +0200585#ifdef HAVE_FSTAT
586 struct stat st;
Victor Stinnera2a64772011-10-11 22:45:02 +0200587 Py_off_t pos, end;
Victor Stinnere9d44ccb2011-05-26 00:16:44 +0200588#endif
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000589 PyObject *result;
590 Py_ssize_t total = 0;
591 int n;
Victor Stinnere9d44ccb2011-05-26 00:16:44 +0200592 size_t newsize;
Guido van Rossum7165cb12007-07-10 06:54:34 +0000593
Victor Stinnerb79f28c2011-05-25 22:09:03 +0200594 if (self->fd < 0)
595 return err_closed();
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000596 if (!_PyVerify_fd(self->fd))
597 return PyErr_SetFromErrno(PyExc_IOError);
Kristján Valur Jónssona8abe862009-03-24 15:27:42 +0000598
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000599 result = PyBytes_FromStringAndSize(NULL, SMALLCHUNK);
600 if (result == NULL)
601 return NULL;
Guido van Rossum7165cb12007-07-10 06:54:34 +0000602
Victor Stinnere9d44ccb2011-05-26 00:16:44 +0200603#ifdef HAVE_FSTAT
604#if defined(MS_WIN64) || defined(MS_WINDOWS)
605 pos = _lseeki64(self->fd, 0L, SEEK_CUR);
606#else
607 pos = lseek(self->fd, 0L, SEEK_CUR);
608#endif
609 if (fstat(self->fd, &st) == 0)
610 end = st.st_size;
611 else
Victor Stinnera2a64772011-10-11 22:45:02 +0200612 end = (Py_off_t)-1;
Victor Stinnere9d44ccb2011-05-26 00:16:44 +0200613#endif
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000614 while (1) {
Victor Stinnere9d44ccb2011-05-26 00:16:44 +0200615#ifdef HAVE_FSTAT
616 newsize = new_buffersize(self, total, pos, end);
617#else
618 newsize = new_buffersize(self, total);
619#endif
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000620 if (newsize > PY_SSIZE_T_MAX || newsize <= 0) {
621 PyErr_SetString(PyExc_OverflowError,
622 "unbounded read returned more bytes "
623 "than a Python string can hold ");
624 Py_DECREF(result);
625 return NULL;
626 }
Christian Heimesa872de52008-12-05 08:26:55 +0000627
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000628 if (PyBytes_GET_SIZE(result) < (Py_ssize_t)newsize) {
629 if (_PyBytes_Resize(&result, newsize) < 0) {
630 if (total == 0) {
631 Py_DECREF(result);
632 return NULL;
633 }
634 PyErr_Clear();
635 break;
636 }
637 }
638 Py_BEGIN_ALLOW_THREADS
639 errno = 0;
640 n = read(self->fd,
641 PyBytes_AS_STRING(result) + total,
642 newsize - total);
643 Py_END_ALLOW_THREADS
644 if (n == 0)
645 break;
646 if (n < 0) {
647 if (total > 0)
648 break;
649 if (errno == EAGAIN) {
650 Py_DECREF(result);
651 Py_RETURN_NONE;
652 }
653 Py_DECREF(result);
654 PyErr_SetFromErrno(PyExc_IOError);
655 return NULL;
656 }
657 total += n;
Victor Stinnere9d44ccb2011-05-26 00:16:44 +0200658#ifdef HAVE_FSTAT
659 pos += n;
660#endif
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000661 }
Guido van Rossum7165cb12007-07-10 06:54:34 +0000662
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000663 if (PyBytes_GET_SIZE(result) > total) {
664 if (_PyBytes_Resize(&result, total) < 0) {
665 /* This should never happen, but just in case */
666 Py_DECREF(result);
667 return NULL;
668 }
669 }
670 return result;
Guido van Rossum7165cb12007-07-10 06:54:34 +0000671}
672
Guido van Rossuma9e20242007-03-08 00:43:48 +0000673static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000674fileio_read(fileio *self, PyObject *args)
Guido van Rossuma9e20242007-03-08 00:43:48 +0000675{
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000676 char *ptr;
677 Py_ssize_t n;
678 Py_ssize_t size = -1;
679 PyObject *bytes;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000680
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000681 if (self->fd < 0)
682 return err_closed();
683 if (!self->readable)
684 return err_mode("reading");
Guido van Rossuma9e20242007-03-08 00:43:48 +0000685
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000686 if (!PyArg_ParseTuple(args, "|O&", &_PyIO_ConvertSsize_t, &size))
687 return NULL;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000688
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000689 if (size < 0) {
690 return fileio_readall(self);
691 }
Guido van Rossumc2f93dc2007-05-24 00:50:02 +0000692
Victor Stinnerc655a722011-07-05 11:31:49 +0200693#if defined(MS_WIN64) || defined(MS_WINDOWS)
694 if (size > INT_MAX)
695 size = INT_MAX;
696#endif
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000697 bytes = PyBytes_FromStringAndSize(NULL, size);
698 if (bytes == NULL)
699 return NULL;
700 ptr = PyBytes_AS_STRING(bytes);
Guido van Rossuma9e20242007-03-08 00:43:48 +0000701
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000702 if (_PyVerify_fd(self->fd)) {
703 Py_BEGIN_ALLOW_THREADS
704 errno = 0;
Victor Stinnerc655a722011-07-05 11:31:49 +0200705#if defined(MS_WIN64) || defined(MS_WINDOWS)
706 n = read(self->fd, ptr, (int)size);
707#else
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000708 n = read(self->fd, ptr, size);
Victor Stinnerc655a722011-07-05 11:31:49 +0200709#endif
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000710 Py_END_ALLOW_THREADS
711 } else
712 n = -1;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000713
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000714 if (n < 0) {
715 Py_DECREF(bytes);
716 if (errno == EAGAIN)
717 Py_RETURN_NONE;
718 PyErr_SetFromErrno(PyExc_IOError);
719 return NULL;
720 }
Guido van Rossuma9e20242007-03-08 00:43:48 +0000721
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000722 if (n != size) {
723 if (_PyBytes_Resize(&bytes, n) < 0) {
724 Py_DECREF(bytes);
725 return NULL;
726 }
727 }
Guido van Rossuma9e20242007-03-08 00:43:48 +0000728
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000729 return (PyObject *) bytes;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000730}
731
732static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000733fileio_write(fileio *self, PyObject *args)
Guido van Rossuma9e20242007-03-08 00:43:48 +0000734{
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000735 Py_buffer pbuf;
Victor Stinnere6edec22011-01-04 00:29:35 +0000736 Py_ssize_t n, len;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000737
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000738 if (self->fd < 0)
739 return err_closed();
740 if (!self->writable)
741 return err_mode("writing");
Guido van Rossum53807da2007-04-10 19:01:47 +0000742
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000743 if (!PyArg_ParseTuple(args, "y*", &pbuf))
744 return NULL;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000745
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000746 if (_PyVerify_fd(self->fd)) {
747 Py_BEGIN_ALLOW_THREADS
748 errno = 0;
Victor Stinnere6edec22011-01-04 00:29:35 +0000749 len = pbuf.len;
750#if defined(MS_WIN64) || defined(MS_WINDOWS)
Victor Stinnere0daff12011-03-20 23:36:35 +0100751 if (len > 32767 && isatty(self->fd)) {
752 /* Issue #11395: the Windows console returns an error (12: not
753 enough space error) on writing into stdout if stdout mode is
754 binary and the length is greater than 66,000 bytes (or less,
755 depending on heap usage). */
756 len = 32767;
757 }
758 else if (len > INT_MAX)
Victor Stinnere6edec22011-01-04 00:29:35 +0000759 len = INT_MAX;
760 n = write(self->fd, pbuf.buf, (int)len);
761#else
Victor Stinner72344792011-01-11 00:04:12 +0000762 n = write(self->fd, pbuf.buf, len);
Victor Stinnere6edec22011-01-04 00:29:35 +0000763#endif
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000764 Py_END_ALLOW_THREADS
765 } else
766 n = -1;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000767
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000768 PyBuffer_Release(&pbuf);
Martin v. Löwis423be952008-08-13 15:53:07 +0000769
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000770 if (n < 0) {
771 if (errno == EAGAIN)
772 Py_RETURN_NONE;
773 PyErr_SetFromErrno(PyExc_IOError);
774 return NULL;
775 }
Guido van Rossuma9e20242007-03-08 00:43:48 +0000776
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000777 return PyLong_FromSsize_t(n);
Guido van Rossuma9e20242007-03-08 00:43:48 +0000778}
779
Guido van Rossum53807da2007-04-10 19:01:47 +0000780/* XXX Windows support below is likely incomplete */
781
Guido van Rossum53807da2007-04-10 19:01:47 +0000782/* Cribbed from posix_lseek() */
783static PyObject *
784portable_lseek(int fd, PyObject *posobj, int whence)
785{
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000786 Py_off_t pos, res;
Guido van Rossum53807da2007-04-10 19:01:47 +0000787
788#ifdef SEEK_SET
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000789 /* Turn 0, 1, 2 into SEEK_{SET,CUR,END} */
790 switch (whence) {
Guido van Rossum53807da2007-04-10 19:01:47 +0000791#if SEEK_SET != 0
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000792 case 0: whence = SEEK_SET; break;
Guido van Rossum53807da2007-04-10 19:01:47 +0000793#endif
794#if SEEK_CUR != 1
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000795 case 1: whence = SEEK_CUR; break;
Guido van Rossum53807da2007-04-10 19:01:47 +0000796#endif
Antoine Pitrou4f7945f2009-01-20 11:42:11 +0000797#if SEEK_END != 2
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000798 case 2: whence = SEEK_END; break;
Guido van Rossum53807da2007-04-10 19:01:47 +0000799#endif
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000800 }
Guido van Rossum53807da2007-04-10 19:01:47 +0000801#endif /* SEEK_SET */
802
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000803 if (posobj == NULL)
804 pos = 0;
805 else {
806 if(PyFloat_Check(posobj)) {
807 PyErr_SetString(PyExc_TypeError, "an integer is required");
808 return NULL;
809 }
Alexandre Vassalotti77250f42008-05-06 19:48:38 +0000810#if defined(HAVE_LARGEFILE_SUPPORT)
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000811 pos = PyLong_AsLongLong(posobj);
Guido van Rossum53807da2007-04-10 19:01:47 +0000812#else
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000813 pos = PyLong_AsLong(posobj);
Guido van Rossum53807da2007-04-10 19:01:47 +0000814#endif
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000815 if (PyErr_Occurred())
816 return NULL;
817 }
Guido van Rossum53807da2007-04-10 19:01:47 +0000818
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000819 if (_PyVerify_fd(fd)) {
820 Py_BEGIN_ALLOW_THREADS
Guido van Rossum53807da2007-04-10 19:01:47 +0000821#if defined(MS_WIN64) || defined(MS_WINDOWS)
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000822 res = _lseeki64(fd, pos, whence);
Guido van Rossum53807da2007-04-10 19:01:47 +0000823#else
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000824 res = lseek(fd, pos, whence);
Guido van Rossum53807da2007-04-10 19:01:47 +0000825#endif
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000826 Py_END_ALLOW_THREADS
827 } else
828 res = -1;
829 if (res < 0)
830 return PyErr_SetFromErrno(PyExc_IOError);
Guido van Rossum53807da2007-04-10 19:01:47 +0000831
Alexandre Vassalotti77250f42008-05-06 19:48:38 +0000832#if defined(HAVE_LARGEFILE_SUPPORT)
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000833 return PyLong_FromLongLong(res);
Alexandre Vassalotti77250f42008-05-06 19:48:38 +0000834#else
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000835 return PyLong_FromLong(res);
Guido van Rossum53807da2007-04-10 19:01:47 +0000836#endif
837}
838
Guido van Rossuma9e20242007-03-08 00:43:48 +0000839static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000840fileio_seek(fileio *self, PyObject *args)
Guido van Rossuma9e20242007-03-08 00:43:48 +0000841{
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000842 PyObject *posobj;
843 int whence = 0;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000844
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000845 if (self->fd < 0)
846 return err_closed();
Guido van Rossuma9e20242007-03-08 00:43:48 +0000847
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000848 if (!PyArg_ParseTuple(args, "O|i", &posobj, &whence))
849 return NULL;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000850
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000851 return portable_lseek(self->fd, posobj, whence);
Guido van Rossuma9e20242007-03-08 00:43:48 +0000852}
853
854static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000855fileio_tell(fileio *self, PyObject *args)
Guido van Rossuma9e20242007-03-08 00:43:48 +0000856{
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000857 if (self->fd < 0)
858 return err_closed();
Guido van Rossuma9e20242007-03-08 00:43:48 +0000859
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000860 return portable_lseek(self->fd, NULL, 1);
Guido van Rossuma9e20242007-03-08 00:43:48 +0000861}
862
Thomas Hellerc6a55ee2007-07-11 12:45:46 +0000863#ifdef HAVE_FTRUNCATE
Guido van Rossuma9e20242007-03-08 00:43:48 +0000864static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000865fileio_truncate(fileio *self, PyObject *args)
Guido van Rossuma9e20242007-03-08 00:43:48 +0000866{
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000867 PyObject *posobj = NULL; /* the new size wanted by the user */
Antoine Pitrou905a2ff2010-01-31 22:47:27 +0000868#ifndef MS_WINDOWS
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000869 Py_off_t pos;
Antoine Pitrou905a2ff2010-01-31 22:47:27 +0000870#endif
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000871 int ret;
872 int fd;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000873
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000874 fd = self->fd;
875 if (fd < 0)
876 return err_closed();
877 if (!self->writable)
878 return err_mode("writing");
Guido van Rossuma9e20242007-03-08 00:43:48 +0000879
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000880 if (!PyArg_ParseTuple(args, "|O", &posobj))
881 return NULL;
Guido van Rossum53807da2007-04-10 19:01:47 +0000882
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000883 if (posobj == Py_None || posobj == NULL) {
884 /* Get the current position. */
885 posobj = portable_lseek(fd, NULL, 1);
886 if (posobj == NULL)
887 return NULL;
888 }
889 else {
890 Py_INCREF(posobj);
891 }
Guido van Rossum53807da2007-04-10 19:01:47 +0000892
Thomas Hellerfdeee3a2007-07-12 11:21:36 +0000893#ifdef MS_WINDOWS
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000894 /* MS _chsize doesn't work if newsize doesn't fit in 32 bits,
895 so don't even try using it. */
896 {
897 PyObject *oldposobj, *tempposobj;
898 HANDLE hFile;
Antoine Pitrou905a2ff2010-01-31 22:47:27 +0000899
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000900 /* we save the file pointer position */
901 oldposobj = portable_lseek(fd, NULL, 1);
902 if (oldposobj == NULL) {
903 Py_DECREF(posobj);
904 return NULL;
905 }
Thomas Hellerfdeee3a2007-07-12 11:21:36 +0000906
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000907 /* we then move to the truncation position */
908 tempposobj = portable_lseek(fd, posobj, 0);
909 if (tempposobj == NULL) {
910 Py_DECREF(oldposobj);
911 Py_DECREF(posobj);
912 return NULL;
913 }
914 Py_DECREF(tempposobj);
Antoine Pitrou905a2ff2010-01-31 22:47:27 +0000915
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000916 /* Truncate. Note that this may grow the file! */
917 Py_BEGIN_ALLOW_THREADS
918 errno = 0;
919 hFile = (HANDLE)_get_osfhandle(fd);
920 ret = hFile == (HANDLE)-1; /* testing for INVALID_HANDLE value */
921 if (ret == 0) {
922 ret = SetEndOfFile(hFile) == 0;
923 if (ret)
924 errno = EACCES;
925 }
926 Py_END_ALLOW_THREADS
927
928 /* we restore the file pointer position in any case */
929 tempposobj = portable_lseek(fd, oldposobj, 0);
930 Py_DECREF(oldposobj);
931 if (tempposobj == NULL) {
932 Py_DECREF(posobj);
933 return NULL;
934 }
935 Py_DECREF(tempposobj);
936 }
Thomas Hellerfdeee3a2007-07-12 11:21:36 +0000937#else
Antoine Pitrou905a2ff2010-01-31 22:47:27 +0000938
939#if defined(HAVE_LARGEFILE_SUPPORT)
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000940 pos = PyLong_AsLongLong(posobj);
Antoine Pitrou905a2ff2010-01-31 22:47:27 +0000941#else
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000942 pos = PyLong_AsLong(posobj);
Antoine Pitrou905a2ff2010-01-31 22:47:27 +0000943#endif
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000944 if (PyErr_Occurred()){
945 Py_DECREF(posobj);
946 return NULL;
947 }
Antoine Pitrou905a2ff2010-01-31 22:47:27 +0000948
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000949 Py_BEGIN_ALLOW_THREADS
950 errno = 0;
951 ret = ftruncate(fd, pos);
952 Py_END_ALLOW_THREADS
Antoine Pitrou905a2ff2010-01-31 22:47:27 +0000953
Thomas Hellerfdeee3a2007-07-12 11:21:36 +0000954#endif /* !MS_WINDOWS */
Guido van Rossuma9e20242007-03-08 00:43:48 +0000955
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000956 if (ret != 0) {
957 Py_DECREF(posobj);
958 PyErr_SetFromErrno(PyExc_IOError);
959 return NULL;
960 }
Guido van Rossuma9e20242007-03-08 00:43:48 +0000961
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000962 return posobj;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000963}
Antoine Pitrou905a2ff2010-01-31 22:47:27 +0000964#endif /* HAVE_FTRUNCATE */
Guido van Rossum53807da2007-04-10 19:01:47 +0000965
966static char *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000967mode_string(fileio *self)
Guido van Rossum53807da2007-04-10 19:01:47 +0000968{
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000969 if (self->readable) {
970 if (self->writable)
971 return "rb+";
972 else
973 return "rb";
974 }
975 else
976 return "wb";
Guido van Rossum53807da2007-04-10 19:01:47 +0000977}
Guido van Rossuma9e20242007-03-08 00:43:48 +0000978
979static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000980fileio_repr(fileio *self)
Guido van Rossuma9e20242007-03-08 00:43:48 +0000981{
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000982 PyObject *nameobj, *res;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000983
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000984 if (self->fd < 0)
985 return PyUnicode_FromFormat("<_io.FileIO [closed]>");
Antoine Pitrou716c4442009-05-23 19:04:03 +0000986
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000987 nameobj = PyObject_GetAttrString((PyObject *) self, "name");
988 if (nameobj == NULL) {
989 if (PyErr_ExceptionMatches(PyExc_AttributeError))
990 PyErr_Clear();
991 else
992 return NULL;
993 res = PyUnicode_FromFormat("<_io.FileIO fd=%d mode='%s'>",
994 self->fd, mode_string(self));
995 }
996 else {
997 res = PyUnicode_FromFormat("<_io.FileIO name=%R mode='%s'>",
998 nameobj, mode_string(self));
999 Py_DECREF(nameobj);
1000 }
1001 return res;
Guido van Rossuma9e20242007-03-08 00:43:48 +00001002}
1003
1004static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +00001005fileio_isatty(fileio *self)
Guido van Rossuma9e20242007-03-08 00:43:48 +00001006{
Antoine Pitrouae4b4722010-05-05 16:31:07 +00001007 long res;
Guido van Rossum53807da2007-04-10 19:01:47 +00001008
Antoine Pitrouae4b4722010-05-05 16:31:07 +00001009 if (self->fd < 0)
1010 return err_closed();
1011 Py_BEGIN_ALLOW_THREADS
1012 res = isatty(self->fd);
1013 Py_END_ALLOW_THREADS
1014 return PyBool_FromLong(res);
Guido van Rossuma9e20242007-03-08 00:43:48 +00001015}
1016
Antoine Pitrou243757e2010-11-05 21:15:39 +00001017static PyObject *
1018fileio_getstate(fileio *self)
1019{
1020 PyErr_Format(PyExc_TypeError,
1021 "cannot serialize '%s' object", Py_TYPE(self)->tp_name);
1022 return NULL;
1023}
1024
Guido van Rossuma9e20242007-03-08 00:43:48 +00001025
1026PyDoc_STRVAR(fileio_doc,
1027"file(name: str[, mode: str]) -> file IO object\n"
1028"\n"
1029"Open a file. The mode can be 'r', 'w' or 'a' for reading (default),\n"
Antoine Pitrouae4b4722010-05-05 16:31:07 +00001030"writing or appending. The file will be created if it doesn't exist\n"
Guido van Rossuma9e20242007-03-08 00:43:48 +00001031"when opened for writing or appending; it will be truncated when\n"
1032"opened for writing. Add a '+' to the mode to allow simultaneous\n"
1033"reading and writing.");
1034
1035PyDoc_STRVAR(read_doc,
1036"read(size: int) -> bytes. read at most size bytes, returned as bytes.\n"
1037"\n"
1038"Only makes one system call, so less data may be returned than requested\n"
Guido van Rossum7165cb12007-07-10 06:54:34 +00001039"In non-blocking mode, returns None if no data is available.\n"
1040"On end-of-file, returns ''.");
1041
1042PyDoc_STRVAR(readall_doc,
1043"readall() -> bytes. read all data from the file, returned as bytes.\n"
1044"\n"
1045"In non-blocking mode, returns as much as is immediately available,\n"
1046"or None if no data is available. On end-of-file, returns ''.");
Guido van Rossuma9e20242007-03-08 00:43:48 +00001047
1048PyDoc_STRVAR(write_doc,
1049"write(b: bytes) -> int. Write bytes b to file, return number written.\n"
1050"\n"
1051"Only makes one system call, so not all of the data may be written.\n"
1052"The number of bytes actually written is returned.");
1053
1054PyDoc_STRVAR(fileno_doc,
1055"fileno() -> int. \"file descriptor\".\n"
1056"\n"
1057"This is needed for lower-level file interfaces, such the fcntl module.");
1058
1059PyDoc_STRVAR(seek_doc,
1060"seek(offset: int[, whence: int]) -> None. Move to new file position.\n"
1061"\n"
1062"Argument offset is a byte count. Optional argument whence defaults to\n"
1063"0 (offset from start of file, offset should be >= 0); other values are 1\n"
1064"(move relative to current position, positive or negative), and 2 (move\n"
1065"relative to end of file, usually negative, although many platforms allow\n"
1066"seeking beyond the end of a file)."
1067"\n"
1068"Note that not all file objects are seekable.");
1069
Thomas Hellerc6a55ee2007-07-11 12:45:46 +00001070#ifdef HAVE_FTRUNCATE
Guido van Rossuma9e20242007-03-08 00:43:48 +00001071PyDoc_STRVAR(truncate_doc,
Antoine Pitrouae4b4722010-05-05 16:31:07 +00001072"truncate([size: int]) -> None. Truncate the file to at most size bytes.\n"
Guido van Rossuma9e20242007-03-08 00:43:48 +00001073"\n"
Alexandre Vassalotti77250f42008-05-06 19:48:38 +00001074"Size defaults to the current file position, as returned by tell()."
1075"The current file position is changed to the value of size.");
Thomas Hellerc6a55ee2007-07-11 12:45:46 +00001076#endif
Guido van Rossuma9e20242007-03-08 00:43:48 +00001077
1078PyDoc_STRVAR(tell_doc,
Antoine Pitrouae4b4722010-05-05 16:31:07 +00001079"tell() -> int. Current file position");
Guido van Rossuma9e20242007-03-08 00:43:48 +00001080
1081PyDoc_STRVAR(readinto_doc,
Benjamin Peterson9a8082f2009-03-05 00:55:56 +00001082"readinto() -> Same as RawIOBase.readinto().");
Guido van Rossuma9e20242007-03-08 00:43:48 +00001083
1084PyDoc_STRVAR(close_doc,
1085"close() -> None. Close the file.\n"
1086"\n"
1087"A closed file cannot be used for further I/O operations. close() may be\n"
1088"called more than once without error. Changes the fileno to -1.");
1089
1090PyDoc_STRVAR(isatty_doc,
1091"isatty() -> bool. True if the file is connected to a tty device.");
1092
Guido van Rossuma9e20242007-03-08 00:43:48 +00001093PyDoc_STRVAR(seekable_doc,
1094"seekable() -> bool. True if file supports random-access.");
1095
1096PyDoc_STRVAR(readable_doc,
1097"readable() -> bool. True if file was opened in a read mode.");
1098
1099PyDoc_STRVAR(writable_doc,
1100"writable() -> bool. True if file was opened in a write mode.");
1101
1102static PyMethodDef fileio_methods[] = {
Antoine Pitrouae4b4722010-05-05 16:31:07 +00001103 {"read", (PyCFunction)fileio_read, METH_VARARGS, read_doc},
1104 {"readall", (PyCFunction)fileio_readall, METH_NOARGS, readall_doc},
1105 {"readinto", (PyCFunction)fileio_readinto, METH_VARARGS, readinto_doc},
1106 {"write", (PyCFunction)fileio_write, METH_VARARGS, write_doc},
1107 {"seek", (PyCFunction)fileio_seek, METH_VARARGS, seek_doc},
1108 {"tell", (PyCFunction)fileio_tell, METH_VARARGS, tell_doc},
Thomas Hellerc6a55ee2007-07-11 12:45:46 +00001109#ifdef HAVE_FTRUNCATE
Antoine Pitrouae4b4722010-05-05 16:31:07 +00001110 {"truncate", (PyCFunction)fileio_truncate, METH_VARARGS, truncate_doc},
Thomas Hellerc6a55ee2007-07-11 12:45:46 +00001111#endif
Antoine Pitrouae4b4722010-05-05 16:31:07 +00001112 {"close", (PyCFunction)fileio_close, METH_NOARGS, close_doc},
1113 {"seekable", (PyCFunction)fileio_seekable, METH_NOARGS, seekable_doc},
1114 {"readable", (PyCFunction)fileio_readable, METH_NOARGS, readable_doc},
1115 {"writable", (PyCFunction)fileio_writable, METH_NOARGS, writable_doc},
1116 {"fileno", (PyCFunction)fileio_fileno, METH_NOARGS, fileno_doc},
1117 {"isatty", (PyCFunction)fileio_isatty, METH_NOARGS, isatty_doc},
Antoine Pitroue033e062010-10-29 10:38:18 +00001118 {"_dealloc_warn", (PyCFunction)fileio_dealloc_warn, METH_O, NULL},
Antoine Pitrou243757e2010-11-05 21:15:39 +00001119 {"__getstate__", (PyCFunction)fileio_getstate, METH_NOARGS, NULL},
Antoine Pitrouae4b4722010-05-05 16:31:07 +00001120 {NULL, NULL} /* sentinel */
Guido van Rossuma9e20242007-03-08 00:43:48 +00001121};
1122
Guido van Rossum53807da2007-04-10 19:01:47 +00001123/* 'closed' and 'mode' are attributes for backwards compatibility reasons. */
1124
Guido van Rossumb0428152007-04-08 17:44:42 +00001125static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +00001126get_closed(fileio *self, void *closure)
Guido van Rossumb0428152007-04-08 17:44:42 +00001127{
Antoine Pitrouae4b4722010-05-05 16:31:07 +00001128 return PyBool_FromLong((long)(self->fd < 0));
Guido van Rossum53807da2007-04-10 19:01:47 +00001129}
1130
1131static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +00001132get_closefd(fileio *self, void *closure)
Christian Heimesecc42a22008-11-05 19:30:32 +00001133{
Antoine Pitrouae4b4722010-05-05 16:31:07 +00001134 return PyBool_FromLong((long)(self->closefd));
Christian Heimesecc42a22008-11-05 19:30:32 +00001135}
1136
1137static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +00001138get_mode(fileio *self, void *closure)
Guido van Rossum53807da2007-04-10 19:01:47 +00001139{
Antoine Pitrouae4b4722010-05-05 16:31:07 +00001140 return PyUnicode_FromString(mode_string(self));
Guido van Rossumb0428152007-04-08 17:44:42 +00001141}
1142
1143static PyGetSetDef fileio_getsetlist[] = {
Antoine Pitrouae4b4722010-05-05 16:31:07 +00001144 {"closed", (getter)get_closed, NULL, "True if the file is closed"},
1145 {"closefd", (getter)get_closefd, NULL,
1146 "True if the file descriptor will be closed"},
1147 {"mode", (getter)get_mode, NULL, "String giving the file mode"},
1148 {NULL},
Guido van Rossumb0428152007-04-08 17:44:42 +00001149};
1150
Guido van Rossuma9e20242007-03-08 00:43:48 +00001151PyTypeObject PyFileIO_Type = {
Antoine Pitrouae4b4722010-05-05 16:31:07 +00001152 PyVarObject_HEAD_INIT(NULL, 0)
1153 "_io.FileIO",
1154 sizeof(fileio),
1155 0,
1156 (destructor)fileio_dealloc, /* tp_dealloc */
1157 0, /* tp_print */
1158 0, /* tp_getattr */
1159 0, /* tp_setattr */
1160 0, /* tp_reserved */
1161 (reprfunc)fileio_repr, /* tp_repr */
1162 0, /* tp_as_number */
1163 0, /* tp_as_sequence */
1164 0, /* tp_as_mapping */
1165 0, /* tp_hash */
1166 0, /* tp_call */
1167 0, /* tp_str */
1168 PyObject_GenericGetAttr, /* tp_getattro */
1169 0, /* tp_setattro */
1170 0, /* tp_as_buffer */
1171 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE
1172 | Py_TPFLAGS_HAVE_GC, /* tp_flags */
1173 fileio_doc, /* tp_doc */
1174 (traverseproc)fileio_traverse, /* tp_traverse */
1175 (inquiry)fileio_clear, /* tp_clear */
1176 0, /* tp_richcompare */
1177 offsetof(fileio, weakreflist), /* tp_weaklistoffset */
1178 0, /* tp_iter */
1179 0, /* tp_iternext */
1180 fileio_methods, /* tp_methods */
1181 0, /* tp_members */
1182 fileio_getsetlist, /* tp_getset */
1183 0, /* tp_base */
1184 0, /* tp_dict */
1185 0, /* tp_descr_get */
1186 0, /* tp_descr_set */
1187 offsetof(fileio, dict), /* tp_dictoffset */
1188 fileio_init, /* tp_init */
1189 PyType_GenericAlloc, /* tp_alloc */
1190 fileio_new, /* tp_new */
1191 PyObject_GC_Del, /* tp_free */
Guido van Rossuma9e20242007-03-08 00:43:48 +00001192};