blob: 2bf8933b57beb0af43c7d48ca24af2aedced91db [file] [log] [blame]
Guido van Rossuma9e20242007-03-08 00:43:48 +00001/* Author: Daniel Stutzbach */
2
3#define PY_SSIZE_T_CLEAN
4#include "Python.h"
Antoine Pitroue033e062010-10-29 10:38:18 +00005#include "structmember.h"
Benjamin Peterson2614cda2010-03-21 22:36:19 +00006#ifdef HAVE_SYS_TYPES_H
Guido van Rossuma9e20242007-03-08 00:43:48 +00007#include <sys/types.h>
Benjamin Peterson2614cda2010-03-21 22:36:19 +00008#endif
9#ifdef HAVE_SYS_STAT_H
Guido van Rossuma9e20242007-03-08 00:43:48 +000010#include <sys/stat.h>
Benjamin Peterson2614cda2010-03-21 22:36:19 +000011#endif
12#ifdef HAVE_FCNTL_H
Guido van Rossuma9e20242007-03-08 00:43:48 +000013#include <fcntl.h>
Benjamin Peterson2614cda2010-03-21 22:36:19 +000014#endif
Guido van Rossuma9e20242007-03-08 00:43:48 +000015#include <stddef.h> /* For offsetof */
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +000016#include "_iomodule.h"
Guido van Rossuma9e20242007-03-08 00:43:48 +000017
18/*
19 * Known likely problems:
20 *
21 * - Files larger then 2**32-1
22 * - Files with unicode filenames
23 * - Passing numbers greater than 2**32-1 when an integer is expected
24 * - Making it work on Windows and other oddball platforms
25 *
26 * To Do:
27 *
28 * - autoconfify header file inclusion
Guido van Rossuma9e20242007-03-08 00:43:48 +000029 */
30
31#ifdef MS_WINDOWS
32/* can simulate truncate with Win32 API functions; see file_truncate */
Thomas Hellerfdeee3a2007-07-12 11:21:36 +000033#define HAVE_FTRUNCATE
Guido van Rossuma9e20242007-03-08 00:43:48 +000034#define WIN32_LEAN_AND_MEAN
35#include <windows.h>
36#endif
37
Christian Heimesa872de52008-12-05 08:26:55 +000038#if BUFSIZ < (8*1024)
39#define SMALLCHUNK (8*1024)
40#elif (BUFSIZ >= (2 << 25))
41#error "unreasonable BUFSIZ > 64MB defined"
42#else
43#define SMALLCHUNK BUFSIZ
44#endif
45
46#if SIZEOF_INT < 4
47#define BIGCHUNK (512 * 32)
48#else
49#define BIGCHUNK (512 * 1024)
50#endif
51
Guido van Rossuma9e20242007-03-08 00:43:48 +000052typedef struct {
Antoine Pitrouae4b4722010-05-05 16:31:07 +000053 PyObject_HEAD
54 int fd;
55 unsigned int readable : 1;
56 unsigned int writable : 1;
57 signed int seekable : 2; /* -1 means unknown */
58 unsigned int closefd : 1;
Antoine Pitroue033e062010-10-29 10:38:18 +000059 unsigned int deallocating: 1;
Antoine Pitrouae4b4722010-05-05 16:31:07 +000060 PyObject *weakreflist;
61 PyObject *dict;
Benjamin Peterson680bf1a2009-06-12 02:07:12 +000062} fileio;
Guido van Rossuma9e20242007-03-08 00:43:48 +000063
Collin Winteraf334382007-03-08 21:46:15 +000064PyTypeObject PyFileIO_Type;
65
Guido van Rossuma9e20242007-03-08 00:43:48 +000066#define PyFileIO_Check(op) (PyObject_TypeCheck((op), &PyFileIO_Type))
67
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +000068int
69_PyFileIO_closed(PyObject *self)
70{
Antoine Pitrouae4b4722010-05-05 16:31:07 +000071 return ((fileio *)self)->fd < 0;
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +000072}
Antoine Pitrou08838b62009-01-21 00:55:13 +000073
Antoine Pitroue033e062010-10-29 10:38:18 +000074/* Because this can call arbitrary code, it shouldn't be called when
75 the refcount is 0 (that is, not directly from tp_dealloc unless
76 the refcount has been temporarily re-incremented). */
77static PyObject *
78fileio_dealloc_warn(fileio *self, PyObject *source)
79{
80 if (self->fd >= 0 && self->closefd) {
81 PyObject *exc, *val, *tb;
82 PyErr_Fetch(&exc, &val, &tb);
83 if (PyErr_WarnFormat(PyExc_ResourceWarning, 1,
84 "unclosed file %R", source)) {
85 /* Spurious errors can appear at shutdown */
86 if (PyErr_ExceptionMatches(PyExc_Warning))
87 PyErr_WriteUnraisable((PyObject *) self);
88 }
89 PyErr_Restore(exc, val, tb);
90 }
91 Py_RETURN_NONE;
92}
93
Antoine Pitrou7fb111b2009-03-04 11:14:01 +000094static PyObject *
95portable_lseek(int fd, PyObject *posobj, int whence);
96
Antoine Pitroua28fcfd2009-03-13 23:42:55 +000097static PyObject *portable_lseek(int fd, PyObject *posobj, int whence);
98
Kristján Valur Jónsson19288c22008-12-18 17:15:54 +000099/* Returns 0 on success, -1 with exception set on failure. */
Neal Norwitz88b44da2007-08-12 17:23:54 +0000100static int
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000101internal_close(fileio *self)
Guido van Rossuma9e20242007-03-08 00:43:48 +0000102{
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000103 int err = 0;
104 int save_errno = 0;
105 if (self->fd >= 0) {
106 int fd = self->fd;
107 self->fd = -1;
108 /* fd is accessible and someone else may have closed it */
109 if (_PyVerify_fd(fd)) {
110 Py_BEGIN_ALLOW_THREADS
111 err = close(fd);
112 if (err < 0)
113 save_errno = errno;
114 Py_END_ALLOW_THREADS
115 } else {
116 save_errno = errno;
117 err = -1;
118 }
119 }
120 if (err < 0) {
121 errno = save_errno;
122 PyErr_SetFromErrno(PyExc_IOError);
123 return -1;
124 }
125 return 0;
Neal Norwitz88b44da2007-08-12 17:23:54 +0000126}
127
128static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000129fileio_close(fileio *self)
Neal Norwitz88b44da2007-08-12 17:23:54 +0000130{
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000131 if (!self->closefd) {
132 self->fd = -1;
133 Py_RETURN_NONE;
134 }
Antoine Pitroue033e062010-10-29 10:38:18 +0000135 if (self->deallocating) {
136 PyObject *r = fileio_dealloc_warn(self, (PyObject *) self);
137 if (r)
138 Py_DECREF(r);
139 else
140 PyErr_Clear();
141 }
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000142 errno = internal_close(self);
143 if (errno < 0)
144 return NULL;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000145
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000146 return PyObject_CallMethod((PyObject*)&PyRawIOBase_Type,
147 "close", "O", self);
Guido van Rossuma9e20242007-03-08 00:43:48 +0000148}
149
150static PyObject *
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000151fileio_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
Guido van Rossuma9e20242007-03-08 00:43:48 +0000152{
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000153 fileio *self;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000154
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000155 assert(type != NULL && type->tp_alloc != NULL);
Guido van Rossuma9e20242007-03-08 00:43:48 +0000156
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000157 self = (fileio *) type->tp_alloc(type, 0);
158 if (self != NULL) {
159 self->fd = -1;
160 self->readable = 0;
161 self->writable = 0;
162 self->seekable = -1;
163 self->closefd = 1;
164 self->weakreflist = NULL;
165 }
Guido van Rossuma9e20242007-03-08 00:43:48 +0000166
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000167 return (PyObject *) self;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000168}
169
170/* On Unix, open will succeed for directories.
171 In Python, there should be no file objects referring to
172 directories, so we need a check. */
173
174static int
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000175dircheck(fileio* self, const char *name)
Guido van Rossuma9e20242007-03-08 00:43:48 +0000176{
177#if defined(HAVE_FSTAT) && defined(S_IFDIR) && defined(EISDIR)
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000178 struct stat buf;
179 if (self->fd < 0)
180 return 0;
181 if (fstat(self->fd, &buf) == 0 && S_ISDIR(buf.st_mode)) {
182 char *msg = strerror(EISDIR);
183 PyObject *exc;
184 if (internal_close(self))
185 return -1;
Guido van Rossum53807da2007-04-10 19:01:47 +0000186
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000187 exc = PyObject_CallFunction(PyExc_IOError, "(iss)",
188 EISDIR, msg, name);
189 PyErr_SetObject(PyExc_IOError, exc);
190 Py_XDECREF(exc);
191 return -1;
192 }
Guido van Rossuma9e20242007-03-08 00:43:48 +0000193#endif
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000194 return 0;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000195}
196
Benjamin Peterson806d4022009-01-19 15:11:51 +0000197static int
198check_fd(int fd)
199{
200#if defined(HAVE_FSTAT)
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000201 struct stat buf;
202 if (!_PyVerify_fd(fd) || (fstat(fd, &buf) < 0 && errno == EBADF)) {
203 PyObject *exc;
204 char *msg = strerror(EBADF);
205 exc = PyObject_CallFunction(PyExc_OSError, "(is)",
206 EBADF, msg);
207 PyErr_SetObject(PyExc_OSError, exc);
208 Py_XDECREF(exc);
209 return -1;
210 }
Benjamin Peterson806d4022009-01-19 15:11:51 +0000211#endif
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000212 return 0;
Benjamin Peterson806d4022009-01-19 15:11:51 +0000213}
214
Guido van Rossuma9e20242007-03-08 00:43:48 +0000215
216static int
217fileio_init(PyObject *oself, PyObject *args, PyObject *kwds)
218{
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000219 fileio *self = (fileio *) oself;
220 static char *kwlist[] = {"file", "mode", "closefd", NULL};
221 const char *name = NULL;
222 PyObject *nameobj, *stringobj = NULL;
223 char *mode = "r";
224 char *s;
Thomas Helleraf2be262007-07-12 11:03:13 +0000225#ifdef MS_WINDOWS
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000226 Py_UNICODE *widename = NULL;
Thomas Helleraf2be262007-07-12 11:03:13 +0000227#endif
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000228 int ret = 0;
229 int rwa = 0, plus = 0, append = 0;
230 int flags = 0;
231 int fd = -1;
232 int closefd = 1;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000233
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000234 assert(PyFileIO_Check(oself));
235 if (self->fd >= 0) {
236 /* Have to close the existing file first. */
237 if (internal_close(self) < 0)
238 return -1;
239 }
Guido van Rossuma9e20242007-03-08 00:43:48 +0000240
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000241 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|si:fileio",
242 kwlist, &nameobj, &mode, &closefd))
243 return -1;
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000244
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000245 if (PyFloat_Check(nameobj)) {
246 PyErr_SetString(PyExc_TypeError,
247 "integer argument expected, got float");
248 return -1;
249 }
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000250
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000251 fd = PyLong_AsLong(nameobj);
252 if (fd < 0) {
253 if (!PyErr_Occurred()) {
254 PyErr_SetString(PyExc_ValueError,
255 "Negative filedescriptor");
256 return -1;
257 }
258 PyErr_Clear();
259 }
Guido van Rossumb0428152007-04-08 17:44:42 +0000260
Hirokazu Yamamoto8223c242009-05-17 04:21:53 +0000261#ifdef MS_WINDOWS
Victor Stinnerfe9a8612011-09-29 23:19:04 +0200262 if (PyUnicode_Check(nameobj)) {
263 widename = PyUnicode_AsUnicode(nameobj);
264 if (widename == NULL)
265 return -1;
266 } else
Guido van Rossuma9e20242007-03-08 00:43:48 +0000267#endif
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000268 if (fd < 0)
269 {
270 if (PyBytes_Check(nameobj) || PyByteArray_Check(nameobj)) {
271 Py_ssize_t namelen;
272 if (PyObject_AsCharBuffer(nameobj, &name, &namelen) < 0)
273 return -1;
274 }
275 else {
276 PyObject *u = PyUnicode_FromObject(nameobj);
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000277
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000278 if (u == NULL)
279 return -1;
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000280
Victor Stinnerae6265f2010-05-15 16:27:27 +0000281 stringobj = PyUnicode_EncodeFSDefault(u);
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000282 Py_DECREF(u);
283 if (stringobj == NULL)
284 return -1;
285 if (!PyBytes_Check(stringobj)) {
286 PyErr_SetString(PyExc_TypeError,
287 "encoder failed to return bytes");
288 goto error;
289 }
290 name = PyBytes_AS_STRING(stringobj);
291 }
292 }
Guido van Rossuma9e20242007-03-08 00:43:48 +0000293
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000294 s = mode;
295 while (*s) {
296 switch (*s++) {
297 case 'r':
298 if (rwa) {
299 bad_mode:
300 PyErr_SetString(PyExc_ValueError,
Georg Brandl28928ae2010-10-21 13:45:52 +0000301 "Must have exactly one of read/write/append "
302 "mode and at most one plus");
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000303 goto error;
304 }
305 rwa = 1;
306 self->readable = 1;
307 break;
308 case 'w':
309 if (rwa)
310 goto bad_mode;
311 rwa = 1;
312 self->writable = 1;
313 flags |= O_CREAT | O_TRUNC;
314 break;
315 case 'a':
316 if (rwa)
317 goto bad_mode;
318 rwa = 1;
319 self->writable = 1;
320 flags |= O_CREAT;
321 append = 1;
322 break;
323 case 'b':
324 break;
325 case '+':
326 if (plus)
327 goto bad_mode;
328 self->readable = self->writable = 1;
329 plus = 1;
330 break;
331 default:
332 PyErr_Format(PyExc_ValueError,
333 "invalid mode: %.200s", mode);
334 goto error;
335 }
336 }
Guido van Rossuma9e20242007-03-08 00:43:48 +0000337
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000338 if (!rwa)
339 goto bad_mode;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000340
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000341 if (self->readable && self->writable)
342 flags |= O_RDWR;
343 else if (self->readable)
344 flags |= O_RDONLY;
345 else
346 flags |= O_WRONLY;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000347
348#ifdef O_BINARY
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000349 flags |= O_BINARY;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000350#endif
351
Walter Dörwald0e411482007-06-06 16:55:38 +0000352#ifdef O_APPEND
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000353 if (append)
354 flags |= O_APPEND;
Walter Dörwald0e411482007-06-06 16:55:38 +0000355#endif
356
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000357 if (fd >= 0) {
358 if (check_fd(fd))
359 goto error;
360 self->fd = fd;
361 self->closefd = closefd;
362 }
363 else {
364 self->closefd = 1;
365 if (!closefd) {
366 PyErr_SetString(PyExc_ValueError,
367 "Cannot use closefd=False with file name");
368 goto error;
369 }
Guido van Rossum2dced8b2007-10-30 17:27:30 +0000370
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000371 Py_BEGIN_ALLOW_THREADS
372 errno = 0;
Thomas Helleraf2be262007-07-12 11:03:13 +0000373#ifdef MS_WINDOWS
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000374 if (widename != NULL)
375 self->fd = _wopen(widename, flags, 0666);
376 else
Thomas Helleraf2be262007-07-12 11:03:13 +0000377#endif
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000378 self->fd = open(name, flags, 0666);
379 Py_END_ALLOW_THREADS
380 if (self->fd < 0) {
Christian Heimes0b489542007-10-31 19:20:48 +0000381#ifdef MS_WINDOWS
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000382 if (widename != NULL)
Victor Stinnerfe9a8612011-09-29 23:19:04 +0200383 PyErr_SetFromErrnoWithFilenameObject(PyExc_IOError, nameobj);
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000384 else
Christian Heimes0b489542007-10-31 19:20:48 +0000385#endif
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000386 PyErr_SetFromErrnoWithFilename(PyExc_IOError, name);
387 goto error;
388 }
Benjamin Peterson430d4692010-10-30 23:13:57 +0000389 if (dircheck(self, name) < 0)
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000390 goto error;
391 }
Guido van Rossuma9e20242007-03-08 00:43:48 +0000392
Victor Stinner89e34362011-01-07 18:47:22 +0000393#if defined(MS_WINDOWS) || defined(__CYGWIN__)
394 /* don't translate newlines (\r\n <=> \n) */
395 _setmode(self->fd, O_BINARY);
396#endif
397
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000398 if (PyObject_SetAttrString((PyObject *)self, "name", nameobj) < 0)
399 goto error;
Antoine Pitrou08838b62009-01-21 00:55:13 +0000400
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000401 if (append) {
402 /* For consistent behaviour, we explicitly seek to the
403 end of file (otherwise, it might be done only on the
404 first write()). */
405 PyObject *pos = portable_lseek(self->fd, NULL, 2);
Antoine Pitrou8d2b51b2010-10-30 16:19:14 +0000406 if (pos == NULL) {
407 if (closefd) {
408 close(self->fd);
409 self->fd = -1;
410 }
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000411 goto error;
Antoine Pitrou8d2b51b2010-10-30 16:19:14 +0000412 }
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000413 Py_DECREF(pos);
414 }
Antoine Pitrou7fb111b2009-03-04 11:14:01 +0000415
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000416 goto done;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000417
418 error:
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000419 ret = -1;
Benjamin Petersonbbb04122010-10-30 23:16:28 +0000420 if (self->fd >= 0)
421 internal_close(self);
Guido van Rossum53807da2007-04-10 19:01:47 +0000422
Guido van Rossuma9e20242007-03-08 00:43:48 +0000423 done:
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000424 Py_CLEAR(stringobj);
425 return ret;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000426}
427
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000428static int
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000429fileio_traverse(fileio *self, visitproc visit, void *arg)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000430{
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000431 Py_VISIT(self->dict);
432 return 0;
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000433}
434
435static int
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000436fileio_clear(fileio *self)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000437{
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000438 Py_CLEAR(self->dict);
439 return 0;
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000440}
441
Guido van Rossuma9e20242007-03-08 00:43:48 +0000442static void
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000443fileio_dealloc(fileio *self)
Guido van Rossuma9e20242007-03-08 00:43:48 +0000444{
Antoine Pitroue033e062010-10-29 10:38:18 +0000445 self->deallocating = 1;
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000446 if (_PyIOBase_finalize((PyObject *) self) < 0)
447 return;
448 _PyObject_GC_UNTRACK(self);
449 if (self->weakreflist != NULL)
450 PyObject_ClearWeakRefs((PyObject *) self);
451 Py_CLEAR(self->dict);
452 Py_TYPE(self)->tp_free((PyObject *)self);
Guido van Rossuma9e20242007-03-08 00:43:48 +0000453}
454
455static PyObject *
456err_closed(void)
457{
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000458 PyErr_SetString(PyExc_ValueError, "I/O operation on closed file");
459 return NULL;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000460}
461
462static PyObject *
Guido van Rossum53807da2007-04-10 19:01:47 +0000463err_mode(char *action)
464{
Antoine Pitrou0d739d72010-09-05 23:01:12 +0000465 PyErr_Format(IO_STATE->unsupported_operation,
466 "File not open for %s", action);
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000467 return NULL;
Guido van Rossum53807da2007-04-10 19:01:47 +0000468}
469
470static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000471fileio_fileno(fileio *self)
Guido van Rossuma9e20242007-03-08 00:43:48 +0000472{
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000473 if (self->fd < 0)
474 return err_closed();
475 return PyLong_FromLong((long) self->fd);
Guido van Rossuma9e20242007-03-08 00:43:48 +0000476}
477
478static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000479fileio_readable(fileio *self)
Guido van Rossuma9e20242007-03-08 00:43:48 +0000480{
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000481 if (self->fd < 0)
482 return err_closed();
483 return PyBool_FromLong((long) self->readable);
Guido van Rossuma9e20242007-03-08 00:43:48 +0000484}
485
486static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000487fileio_writable(fileio *self)
Guido van Rossuma9e20242007-03-08 00:43:48 +0000488{
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000489 if (self->fd < 0)
490 return err_closed();
491 return PyBool_FromLong((long) self->writable);
Guido van Rossuma9e20242007-03-08 00:43:48 +0000492}
493
494static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000495fileio_seekable(fileio *self)
Guido van Rossuma9e20242007-03-08 00:43:48 +0000496{
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000497 if (self->fd < 0)
498 return err_closed();
499 if (self->seekable < 0) {
500 PyObject *pos = portable_lseek(self->fd, NULL, SEEK_CUR);
501 if (pos == NULL) {
502 PyErr_Clear();
503 self->seekable = 0;
504 } else {
505 Py_DECREF(pos);
506 self->seekable = 1;
507 }
508 }
509 return PyBool_FromLong((long) self->seekable);
Guido van Rossuma9e20242007-03-08 00:43:48 +0000510}
511
512static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000513fileio_readinto(fileio *self, PyObject *args)
Guido van Rossuma9e20242007-03-08 00:43:48 +0000514{
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000515 Py_buffer pbuf;
Victor Stinnere6edec22011-01-04 00:29:35 +0000516 Py_ssize_t n, len;
Guido van Rossum53807da2007-04-10 19:01:47 +0000517
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000518 if (self->fd < 0)
519 return err_closed();
520 if (!self->readable)
521 return err_mode("reading");
Guido van Rossum53807da2007-04-10 19:01:47 +0000522
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000523 if (!PyArg_ParseTuple(args, "w*", &pbuf))
524 return NULL;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000525
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000526 if (_PyVerify_fd(self->fd)) {
Victor Stinnere6edec22011-01-04 00:29:35 +0000527 len = pbuf.len;
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000528 Py_BEGIN_ALLOW_THREADS
529 errno = 0;
Victor Stinnere6edec22011-01-04 00:29:35 +0000530#if defined(MS_WIN64) || defined(MS_WINDOWS)
531 if (len > INT_MAX)
532 len = INT_MAX;
533 n = read(self->fd, pbuf.buf, (int)len);
534#else
Victor Stinner72344792011-01-11 00:04:12 +0000535 n = read(self->fd, pbuf.buf, len);
Victor Stinnere6edec22011-01-04 00:29:35 +0000536#endif
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000537 Py_END_ALLOW_THREADS
538 } else
539 n = -1;
540 PyBuffer_Release(&pbuf);
541 if (n < 0) {
542 if (errno == EAGAIN)
543 Py_RETURN_NONE;
544 PyErr_SetFromErrno(PyExc_IOError);
545 return NULL;
546 }
Guido van Rossuma9e20242007-03-08 00:43:48 +0000547
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000548 return PyLong_FromSsize_t(n);
Guido van Rossuma9e20242007-03-08 00:43:48 +0000549}
550
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000551static size_t
Victor Stinnere9d44ccb2011-05-26 00:16:44 +0200552new_buffersize(fileio *self, size_t currentsize
553#ifdef HAVE_FSTAT
554 , off_t pos, off_t end
555#endif
556 )
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000557{
558#ifdef HAVE_FSTAT
Victor Stinnere9d44ccb2011-05-26 00:16:44 +0200559 if (end != (off_t)-1) {
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000560 /* Files claiming a size smaller than SMALLCHUNK may
561 actually be streaming pseudo-files. In this case, we
562 apply the more aggressive algorithm below.
563 */
564 if (end >= SMALLCHUNK && end >= pos && pos >= 0) {
565 /* Add 1 so if the file were to grow we'd notice. */
566 return currentsize + end - pos + 1;
567 }
568 }
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000569#endif
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000570 if (currentsize > SMALLCHUNK) {
571 /* Keep doubling until we reach BIGCHUNK;
572 then keep adding BIGCHUNK. */
573 if (currentsize <= BIGCHUNK)
574 return currentsize + currentsize;
575 else
576 return currentsize + BIGCHUNK;
577 }
578 return currentsize + SMALLCHUNK;
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000579}
580
Guido van Rossum7165cb12007-07-10 06:54:34 +0000581static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000582fileio_readall(fileio *self)
Guido van Rossum7165cb12007-07-10 06:54:34 +0000583{
Victor Stinnere9d44ccb2011-05-26 00:16:44 +0200584#ifdef HAVE_FSTAT
585 struct stat st;
586 off_t pos, end;
587#endif
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000588 PyObject *result;
589 Py_ssize_t total = 0;
590 int n;
Victor Stinnere9d44ccb2011-05-26 00:16:44 +0200591 size_t newsize;
Guido van Rossum7165cb12007-07-10 06:54:34 +0000592
Victor Stinnerb79f28c2011-05-25 22:09:03 +0200593 if (self->fd < 0)
594 return err_closed();
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000595 if (!_PyVerify_fd(self->fd))
596 return PyErr_SetFromErrno(PyExc_IOError);
Kristján Valur Jónssona8abe862009-03-24 15:27:42 +0000597
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000598 result = PyBytes_FromStringAndSize(NULL, SMALLCHUNK);
599 if (result == NULL)
600 return NULL;
Guido van Rossum7165cb12007-07-10 06:54:34 +0000601
Victor Stinnere9d44ccb2011-05-26 00:16:44 +0200602#ifdef HAVE_FSTAT
603#if defined(MS_WIN64) || defined(MS_WINDOWS)
604 pos = _lseeki64(self->fd, 0L, SEEK_CUR);
605#else
606 pos = lseek(self->fd, 0L, SEEK_CUR);
607#endif
608 if (fstat(self->fd, &st) == 0)
609 end = st.st_size;
610 else
611 end = (off_t)-1;
612#endif
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000613 while (1) {
Victor Stinnere9d44ccb2011-05-26 00:16:44 +0200614#ifdef HAVE_FSTAT
615 newsize = new_buffersize(self, total, pos, end);
616#else
617 newsize = new_buffersize(self, total);
618#endif
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000619 if (newsize > PY_SSIZE_T_MAX || newsize <= 0) {
620 PyErr_SetString(PyExc_OverflowError,
621 "unbounded read returned more bytes "
622 "than a Python string can hold ");
623 Py_DECREF(result);
624 return NULL;
625 }
Christian Heimesa872de52008-12-05 08:26:55 +0000626
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000627 if (PyBytes_GET_SIZE(result) < (Py_ssize_t)newsize) {
628 if (_PyBytes_Resize(&result, newsize) < 0) {
629 if (total == 0) {
630 Py_DECREF(result);
631 return NULL;
632 }
633 PyErr_Clear();
634 break;
635 }
636 }
637 Py_BEGIN_ALLOW_THREADS
638 errno = 0;
639 n = read(self->fd,
640 PyBytes_AS_STRING(result) + total,
641 newsize - total);
642 Py_END_ALLOW_THREADS
643 if (n == 0)
644 break;
645 if (n < 0) {
646 if (total > 0)
647 break;
648 if (errno == EAGAIN) {
649 Py_DECREF(result);
650 Py_RETURN_NONE;
651 }
652 Py_DECREF(result);
653 PyErr_SetFromErrno(PyExc_IOError);
654 return NULL;
655 }
656 total += n;
Victor Stinnere9d44ccb2011-05-26 00:16:44 +0200657#ifdef HAVE_FSTAT
658 pos += n;
659#endif
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000660 }
Guido van Rossum7165cb12007-07-10 06:54:34 +0000661
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000662 if (PyBytes_GET_SIZE(result) > total) {
663 if (_PyBytes_Resize(&result, total) < 0) {
664 /* This should never happen, but just in case */
665 Py_DECREF(result);
666 return NULL;
667 }
668 }
669 return result;
Guido van Rossum7165cb12007-07-10 06:54:34 +0000670}
671
Guido van Rossuma9e20242007-03-08 00:43:48 +0000672static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000673fileio_read(fileio *self, PyObject *args)
Guido van Rossuma9e20242007-03-08 00:43:48 +0000674{
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000675 char *ptr;
676 Py_ssize_t n;
677 Py_ssize_t size = -1;
678 PyObject *bytes;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000679
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000680 if (self->fd < 0)
681 return err_closed();
682 if (!self->readable)
683 return err_mode("reading");
Guido van Rossuma9e20242007-03-08 00:43:48 +0000684
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000685 if (!PyArg_ParseTuple(args, "|O&", &_PyIO_ConvertSsize_t, &size))
686 return NULL;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000687
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000688 if (size < 0) {
689 return fileio_readall(self);
690 }
Guido van Rossumc2f93dc2007-05-24 00:50:02 +0000691
Victor Stinnerc655a722011-07-05 11:31:49 +0200692#if defined(MS_WIN64) || defined(MS_WINDOWS)
693 if (size > INT_MAX)
694 size = INT_MAX;
695#endif
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000696 bytes = PyBytes_FromStringAndSize(NULL, size);
697 if (bytes == NULL)
698 return NULL;
699 ptr = PyBytes_AS_STRING(bytes);
Guido van Rossuma9e20242007-03-08 00:43:48 +0000700
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000701 if (_PyVerify_fd(self->fd)) {
702 Py_BEGIN_ALLOW_THREADS
703 errno = 0;
Victor Stinnerc655a722011-07-05 11:31:49 +0200704#if defined(MS_WIN64) || defined(MS_WINDOWS)
705 n = read(self->fd, ptr, (int)size);
706#else
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000707 n = read(self->fd, ptr, size);
Victor Stinnerc655a722011-07-05 11:31:49 +0200708#endif
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000709 Py_END_ALLOW_THREADS
710 } else
711 n = -1;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000712
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000713 if (n < 0) {
714 Py_DECREF(bytes);
715 if (errno == EAGAIN)
716 Py_RETURN_NONE;
717 PyErr_SetFromErrno(PyExc_IOError);
718 return NULL;
719 }
Guido van Rossuma9e20242007-03-08 00:43:48 +0000720
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000721 if (n != size) {
722 if (_PyBytes_Resize(&bytes, n) < 0) {
723 Py_DECREF(bytes);
724 return NULL;
725 }
726 }
Guido van Rossuma9e20242007-03-08 00:43:48 +0000727
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000728 return (PyObject *) bytes;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000729}
730
731static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000732fileio_write(fileio *self, PyObject *args)
Guido van Rossuma9e20242007-03-08 00:43:48 +0000733{
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000734 Py_buffer pbuf;
Victor Stinnere6edec22011-01-04 00:29:35 +0000735 Py_ssize_t n, len;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000736
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000737 if (self->fd < 0)
738 return err_closed();
739 if (!self->writable)
740 return err_mode("writing");
Guido van Rossum53807da2007-04-10 19:01:47 +0000741
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000742 if (!PyArg_ParseTuple(args, "y*", &pbuf))
743 return NULL;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000744
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000745 if (_PyVerify_fd(self->fd)) {
746 Py_BEGIN_ALLOW_THREADS
747 errno = 0;
Victor Stinnere6edec22011-01-04 00:29:35 +0000748 len = pbuf.len;
749#if defined(MS_WIN64) || defined(MS_WINDOWS)
Victor Stinnere0daff12011-03-20 23:36:35 +0100750 if (len > 32767 && isatty(self->fd)) {
751 /* Issue #11395: the Windows console returns an error (12: not
752 enough space error) on writing into stdout if stdout mode is
753 binary and the length is greater than 66,000 bytes (or less,
754 depending on heap usage). */
755 len = 32767;
756 }
757 else if (len > INT_MAX)
Victor Stinnere6edec22011-01-04 00:29:35 +0000758 len = INT_MAX;
759 n = write(self->fd, pbuf.buf, (int)len);
760#else
Victor Stinner72344792011-01-11 00:04:12 +0000761 n = write(self->fd, pbuf.buf, len);
Victor Stinnere6edec22011-01-04 00:29:35 +0000762#endif
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000763 Py_END_ALLOW_THREADS
764 } else
765 n = -1;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000766
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000767 PyBuffer_Release(&pbuf);
Martin v. Löwis423be952008-08-13 15:53:07 +0000768
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000769 if (n < 0) {
770 if (errno == EAGAIN)
771 Py_RETURN_NONE;
772 PyErr_SetFromErrno(PyExc_IOError);
773 return NULL;
774 }
Guido van Rossuma9e20242007-03-08 00:43:48 +0000775
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000776 return PyLong_FromSsize_t(n);
Guido van Rossuma9e20242007-03-08 00:43:48 +0000777}
778
Guido van Rossum53807da2007-04-10 19:01:47 +0000779/* XXX Windows support below is likely incomplete */
780
Guido van Rossum53807da2007-04-10 19:01:47 +0000781/* Cribbed from posix_lseek() */
782static PyObject *
783portable_lseek(int fd, PyObject *posobj, int whence)
784{
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000785 Py_off_t pos, res;
Guido van Rossum53807da2007-04-10 19:01:47 +0000786
787#ifdef SEEK_SET
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000788 /* Turn 0, 1, 2 into SEEK_{SET,CUR,END} */
789 switch (whence) {
Guido van Rossum53807da2007-04-10 19:01:47 +0000790#if SEEK_SET != 0
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000791 case 0: whence = SEEK_SET; break;
Guido van Rossum53807da2007-04-10 19:01:47 +0000792#endif
793#if SEEK_CUR != 1
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000794 case 1: whence = SEEK_CUR; break;
Guido van Rossum53807da2007-04-10 19:01:47 +0000795#endif
Antoine Pitrou4f7945f2009-01-20 11:42:11 +0000796#if SEEK_END != 2
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000797 case 2: whence = SEEK_END; break;
Guido van Rossum53807da2007-04-10 19:01:47 +0000798#endif
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000799 }
Guido van Rossum53807da2007-04-10 19:01:47 +0000800#endif /* SEEK_SET */
801
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000802 if (posobj == NULL)
803 pos = 0;
804 else {
805 if(PyFloat_Check(posobj)) {
806 PyErr_SetString(PyExc_TypeError, "an integer is required");
807 return NULL;
808 }
Alexandre Vassalotti77250f42008-05-06 19:48:38 +0000809#if defined(HAVE_LARGEFILE_SUPPORT)
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000810 pos = PyLong_AsLongLong(posobj);
Guido van Rossum53807da2007-04-10 19:01:47 +0000811#else
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000812 pos = PyLong_AsLong(posobj);
Guido van Rossum53807da2007-04-10 19:01:47 +0000813#endif
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000814 if (PyErr_Occurred())
815 return NULL;
816 }
Guido van Rossum53807da2007-04-10 19:01:47 +0000817
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000818 if (_PyVerify_fd(fd)) {
819 Py_BEGIN_ALLOW_THREADS
Guido van Rossum53807da2007-04-10 19:01:47 +0000820#if defined(MS_WIN64) || defined(MS_WINDOWS)
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000821 res = _lseeki64(fd, pos, whence);
Guido van Rossum53807da2007-04-10 19:01:47 +0000822#else
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000823 res = lseek(fd, pos, whence);
Guido van Rossum53807da2007-04-10 19:01:47 +0000824#endif
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000825 Py_END_ALLOW_THREADS
826 } else
827 res = -1;
828 if (res < 0)
829 return PyErr_SetFromErrno(PyExc_IOError);
Guido van Rossum53807da2007-04-10 19:01:47 +0000830
Alexandre Vassalotti77250f42008-05-06 19:48:38 +0000831#if defined(HAVE_LARGEFILE_SUPPORT)
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000832 return PyLong_FromLongLong(res);
Alexandre Vassalotti77250f42008-05-06 19:48:38 +0000833#else
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000834 return PyLong_FromLong(res);
Guido van Rossum53807da2007-04-10 19:01:47 +0000835#endif
836}
837
Guido van Rossuma9e20242007-03-08 00:43:48 +0000838static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000839fileio_seek(fileio *self, PyObject *args)
Guido van Rossuma9e20242007-03-08 00:43:48 +0000840{
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000841 PyObject *posobj;
842 int whence = 0;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000843
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000844 if (self->fd < 0)
845 return err_closed();
Guido van Rossuma9e20242007-03-08 00:43:48 +0000846
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000847 if (!PyArg_ParseTuple(args, "O|i", &posobj, &whence))
848 return NULL;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000849
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000850 return portable_lseek(self->fd, posobj, whence);
Guido van Rossuma9e20242007-03-08 00:43:48 +0000851}
852
853static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000854fileio_tell(fileio *self, PyObject *args)
Guido van Rossuma9e20242007-03-08 00:43:48 +0000855{
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000856 if (self->fd < 0)
857 return err_closed();
Guido van Rossuma9e20242007-03-08 00:43:48 +0000858
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000859 return portable_lseek(self->fd, NULL, 1);
Guido van Rossuma9e20242007-03-08 00:43:48 +0000860}
861
Thomas Hellerc6a55ee2007-07-11 12:45:46 +0000862#ifdef HAVE_FTRUNCATE
Guido van Rossuma9e20242007-03-08 00:43:48 +0000863static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000864fileio_truncate(fileio *self, PyObject *args)
Guido van Rossuma9e20242007-03-08 00:43:48 +0000865{
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000866 PyObject *posobj = NULL; /* the new size wanted by the user */
Antoine Pitrou905a2ff2010-01-31 22:47:27 +0000867#ifndef MS_WINDOWS
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000868 Py_off_t pos;
Antoine Pitrou905a2ff2010-01-31 22:47:27 +0000869#endif
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000870 int ret;
871 int fd;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000872
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000873 fd = self->fd;
874 if (fd < 0)
875 return err_closed();
876 if (!self->writable)
877 return err_mode("writing");
Guido van Rossuma9e20242007-03-08 00:43:48 +0000878
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000879 if (!PyArg_ParseTuple(args, "|O", &posobj))
880 return NULL;
Guido van Rossum53807da2007-04-10 19:01:47 +0000881
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000882 if (posobj == Py_None || posobj == NULL) {
883 /* Get the current position. */
884 posobj = portable_lseek(fd, NULL, 1);
885 if (posobj == NULL)
886 return NULL;
887 }
888 else {
889 Py_INCREF(posobj);
890 }
Guido van Rossum53807da2007-04-10 19:01:47 +0000891
Thomas Hellerfdeee3a2007-07-12 11:21:36 +0000892#ifdef MS_WINDOWS
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000893 /* MS _chsize doesn't work if newsize doesn't fit in 32 bits,
894 so don't even try using it. */
895 {
896 PyObject *oldposobj, *tempposobj;
897 HANDLE hFile;
Antoine Pitrou905a2ff2010-01-31 22:47:27 +0000898
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000899 /* we save the file pointer position */
900 oldposobj = portable_lseek(fd, NULL, 1);
901 if (oldposobj == NULL) {
902 Py_DECREF(posobj);
903 return NULL;
904 }
Thomas Hellerfdeee3a2007-07-12 11:21:36 +0000905
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000906 /* we then move to the truncation position */
907 tempposobj = portable_lseek(fd, posobj, 0);
908 if (tempposobj == NULL) {
909 Py_DECREF(oldposobj);
910 Py_DECREF(posobj);
911 return NULL;
912 }
913 Py_DECREF(tempposobj);
Antoine Pitrou905a2ff2010-01-31 22:47:27 +0000914
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000915 /* Truncate. Note that this may grow the file! */
916 Py_BEGIN_ALLOW_THREADS
917 errno = 0;
918 hFile = (HANDLE)_get_osfhandle(fd);
919 ret = hFile == (HANDLE)-1; /* testing for INVALID_HANDLE value */
920 if (ret == 0) {
921 ret = SetEndOfFile(hFile) == 0;
922 if (ret)
923 errno = EACCES;
924 }
925 Py_END_ALLOW_THREADS
926
927 /* we restore the file pointer position in any case */
928 tempposobj = portable_lseek(fd, oldposobj, 0);
929 Py_DECREF(oldposobj);
930 if (tempposobj == NULL) {
931 Py_DECREF(posobj);
932 return NULL;
933 }
934 Py_DECREF(tempposobj);
935 }
Thomas Hellerfdeee3a2007-07-12 11:21:36 +0000936#else
Antoine Pitrou905a2ff2010-01-31 22:47:27 +0000937
938#if defined(HAVE_LARGEFILE_SUPPORT)
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000939 pos = PyLong_AsLongLong(posobj);
Antoine Pitrou905a2ff2010-01-31 22:47:27 +0000940#else
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000941 pos = PyLong_AsLong(posobj);
Antoine Pitrou905a2ff2010-01-31 22:47:27 +0000942#endif
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000943 if (PyErr_Occurred()){
944 Py_DECREF(posobj);
945 return NULL;
946 }
Antoine Pitrou905a2ff2010-01-31 22:47:27 +0000947
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000948 Py_BEGIN_ALLOW_THREADS
949 errno = 0;
950 ret = ftruncate(fd, pos);
951 Py_END_ALLOW_THREADS
Antoine Pitrou905a2ff2010-01-31 22:47:27 +0000952
Thomas Hellerfdeee3a2007-07-12 11:21:36 +0000953#endif /* !MS_WINDOWS */
Guido van Rossuma9e20242007-03-08 00:43:48 +0000954
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000955 if (ret != 0) {
956 Py_DECREF(posobj);
957 PyErr_SetFromErrno(PyExc_IOError);
958 return NULL;
959 }
Guido van Rossuma9e20242007-03-08 00:43:48 +0000960
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000961 return posobj;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000962}
Antoine Pitrou905a2ff2010-01-31 22:47:27 +0000963#endif /* HAVE_FTRUNCATE */
Guido van Rossum53807da2007-04-10 19:01:47 +0000964
965static char *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000966mode_string(fileio *self)
Guido van Rossum53807da2007-04-10 19:01:47 +0000967{
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000968 if (self->readable) {
969 if (self->writable)
970 return "rb+";
971 else
972 return "rb";
973 }
974 else
975 return "wb";
Guido van Rossum53807da2007-04-10 19:01:47 +0000976}
Guido van Rossuma9e20242007-03-08 00:43:48 +0000977
978static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000979fileio_repr(fileio *self)
Guido van Rossuma9e20242007-03-08 00:43:48 +0000980{
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000981 PyObject *nameobj, *res;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000982
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000983 if (self->fd < 0)
984 return PyUnicode_FromFormat("<_io.FileIO [closed]>");
Antoine Pitrou716c4442009-05-23 19:04:03 +0000985
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000986 nameobj = PyObject_GetAttrString((PyObject *) self, "name");
987 if (nameobj == NULL) {
988 if (PyErr_ExceptionMatches(PyExc_AttributeError))
989 PyErr_Clear();
990 else
991 return NULL;
992 res = PyUnicode_FromFormat("<_io.FileIO fd=%d mode='%s'>",
993 self->fd, mode_string(self));
994 }
995 else {
996 res = PyUnicode_FromFormat("<_io.FileIO name=%R mode='%s'>",
997 nameobj, mode_string(self));
998 Py_DECREF(nameobj);
999 }
1000 return res;
Guido van Rossuma9e20242007-03-08 00:43:48 +00001001}
1002
1003static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +00001004fileio_isatty(fileio *self)
Guido van Rossuma9e20242007-03-08 00:43:48 +00001005{
Antoine Pitrouae4b4722010-05-05 16:31:07 +00001006 long res;
Guido van Rossum53807da2007-04-10 19:01:47 +00001007
Antoine Pitrouae4b4722010-05-05 16:31:07 +00001008 if (self->fd < 0)
1009 return err_closed();
1010 Py_BEGIN_ALLOW_THREADS
1011 res = isatty(self->fd);
1012 Py_END_ALLOW_THREADS
1013 return PyBool_FromLong(res);
Guido van Rossuma9e20242007-03-08 00:43:48 +00001014}
1015
Antoine Pitrou243757e2010-11-05 21:15:39 +00001016static PyObject *
1017fileio_getstate(fileio *self)
1018{
1019 PyErr_Format(PyExc_TypeError,
1020 "cannot serialize '%s' object", Py_TYPE(self)->tp_name);
1021 return NULL;
1022}
1023
Guido van Rossuma9e20242007-03-08 00:43:48 +00001024
1025PyDoc_STRVAR(fileio_doc,
1026"file(name: str[, mode: str]) -> file IO object\n"
1027"\n"
1028"Open a file. The mode can be 'r', 'w' or 'a' for reading (default),\n"
Antoine Pitrouae4b4722010-05-05 16:31:07 +00001029"writing or appending. The file will be created if it doesn't exist\n"
Guido van Rossuma9e20242007-03-08 00:43:48 +00001030"when opened for writing or appending; it will be truncated when\n"
1031"opened for writing. Add a '+' to the mode to allow simultaneous\n"
1032"reading and writing.");
1033
1034PyDoc_STRVAR(read_doc,
1035"read(size: int) -> bytes. read at most size bytes, returned as bytes.\n"
1036"\n"
1037"Only makes one system call, so less data may be returned than requested\n"
Guido van Rossum7165cb12007-07-10 06:54:34 +00001038"In non-blocking mode, returns None if no data is available.\n"
1039"On end-of-file, returns ''.");
1040
1041PyDoc_STRVAR(readall_doc,
1042"readall() -> bytes. read all data from the file, returned as bytes.\n"
1043"\n"
1044"In non-blocking mode, returns as much as is immediately available,\n"
1045"or None if no data is available. On end-of-file, returns ''.");
Guido van Rossuma9e20242007-03-08 00:43:48 +00001046
1047PyDoc_STRVAR(write_doc,
1048"write(b: bytes) -> int. Write bytes b to file, return number written.\n"
1049"\n"
1050"Only makes one system call, so not all of the data may be written.\n"
1051"The number of bytes actually written is returned.");
1052
1053PyDoc_STRVAR(fileno_doc,
1054"fileno() -> int. \"file descriptor\".\n"
1055"\n"
1056"This is needed for lower-level file interfaces, such the fcntl module.");
1057
1058PyDoc_STRVAR(seek_doc,
1059"seek(offset: int[, whence: int]) -> None. Move to new file position.\n"
1060"\n"
1061"Argument offset is a byte count. Optional argument whence defaults to\n"
1062"0 (offset from start of file, offset should be >= 0); other values are 1\n"
1063"(move relative to current position, positive or negative), and 2 (move\n"
1064"relative to end of file, usually negative, although many platforms allow\n"
1065"seeking beyond the end of a file)."
1066"\n"
1067"Note that not all file objects are seekable.");
1068
Thomas Hellerc6a55ee2007-07-11 12:45:46 +00001069#ifdef HAVE_FTRUNCATE
Guido van Rossuma9e20242007-03-08 00:43:48 +00001070PyDoc_STRVAR(truncate_doc,
Antoine Pitrouae4b4722010-05-05 16:31:07 +00001071"truncate([size: int]) -> None. Truncate the file to at most size bytes.\n"
Guido van Rossuma9e20242007-03-08 00:43:48 +00001072"\n"
Alexandre Vassalotti77250f42008-05-06 19:48:38 +00001073"Size defaults to the current file position, as returned by tell()."
1074"The current file position is changed to the value of size.");
Thomas Hellerc6a55ee2007-07-11 12:45:46 +00001075#endif
Guido van Rossuma9e20242007-03-08 00:43:48 +00001076
1077PyDoc_STRVAR(tell_doc,
Antoine Pitrouae4b4722010-05-05 16:31:07 +00001078"tell() -> int. Current file position");
Guido van Rossuma9e20242007-03-08 00:43:48 +00001079
1080PyDoc_STRVAR(readinto_doc,
Benjamin Peterson9a8082f2009-03-05 00:55:56 +00001081"readinto() -> Same as RawIOBase.readinto().");
Guido van Rossuma9e20242007-03-08 00:43:48 +00001082
1083PyDoc_STRVAR(close_doc,
1084"close() -> None. Close the file.\n"
1085"\n"
1086"A closed file cannot be used for further I/O operations. close() may be\n"
1087"called more than once without error. Changes the fileno to -1.");
1088
1089PyDoc_STRVAR(isatty_doc,
1090"isatty() -> bool. True if the file is connected to a tty device.");
1091
Guido van Rossuma9e20242007-03-08 00:43:48 +00001092PyDoc_STRVAR(seekable_doc,
1093"seekable() -> bool. True if file supports random-access.");
1094
1095PyDoc_STRVAR(readable_doc,
1096"readable() -> bool. True if file was opened in a read mode.");
1097
1098PyDoc_STRVAR(writable_doc,
1099"writable() -> bool. True if file was opened in a write mode.");
1100
1101static PyMethodDef fileio_methods[] = {
Antoine Pitrouae4b4722010-05-05 16:31:07 +00001102 {"read", (PyCFunction)fileio_read, METH_VARARGS, read_doc},
1103 {"readall", (PyCFunction)fileio_readall, METH_NOARGS, readall_doc},
1104 {"readinto", (PyCFunction)fileio_readinto, METH_VARARGS, readinto_doc},
1105 {"write", (PyCFunction)fileio_write, METH_VARARGS, write_doc},
1106 {"seek", (PyCFunction)fileio_seek, METH_VARARGS, seek_doc},
1107 {"tell", (PyCFunction)fileio_tell, METH_VARARGS, tell_doc},
Thomas Hellerc6a55ee2007-07-11 12:45:46 +00001108#ifdef HAVE_FTRUNCATE
Antoine Pitrouae4b4722010-05-05 16:31:07 +00001109 {"truncate", (PyCFunction)fileio_truncate, METH_VARARGS, truncate_doc},
Thomas Hellerc6a55ee2007-07-11 12:45:46 +00001110#endif
Antoine Pitrouae4b4722010-05-05 16:31:07 +00001111 {"close", (PyCFunction)fileio_close, METH_NOARGS, close_doc},
1112 {"seekable", (PyCFunction)fileio_seekable, METH_NOARGS, seekable_doc},
1113 {"readable", (PyCFunction)fileio_readable, METH_NOARGS, readable_doc},
1114 {"writable", (PyCFunction)fileio_writable, METH_NOARGS, writable_doc},
1115 {"fileno", (PyCFunction)fileio_fileno, METH_NOARGS, fileno_doc},
1116 {"isatty", (PyCFunction)fileio_isatty, METH_NOARGS, isatty_doc},
Antoine Pitroue033e062010-10-29 10:38:18 +00001117 {"_dealloc_warn", (PyCFunction)fileio_dealloc_warn, METH_O, NULL},
Antoine Pitrou243757e2010-11-05 21:15:39 +00001118 {"__getstate__", (PyCFunction)fileio_getstate, METH_NOARGS, NULL},
Antoine Pitrouae4b4722010-05-05 16:31:07 +00001119 {NULL, NULL} /* sentinel */
Guido van Rossuma9e20242007-03-08 00:43:48 +00001120};
1121
Guido van Rossum53807da2007-04-10 19:01:47 +00001122/* 'closed' and 'mode' are attributes for backwards compatibility reasons. */
1123
Guido van Rossumb0428152007-04-08 17:44:42 +00001124static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +00001125get_closed(fileio *self, void *closure)
Guido van Rossumb0428152007-04-08 17:44:42 +00001126{
Antoine Pitrouae4b4722010-05-05 16:31:07 +00001127 return PyBool_FromLong((long)(self->fd < 0));
Guido van Rossum53807da2007-04-10 19:01:47 +00001128}
1129
1130static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +00001131get_closefd(fileio *self, void *closure)
Christian Heimesecc42a22008-11-05 19:30:32 +00001132{
Antoine Pitrouae4b4722010-05-05 16:31:07 +00001133 return PyBool_FromLong((long)(self->closefd));
Christian Heimesecc42a22008-11-05 19:30:32 +00001134}
1135
1136static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +00001137get_mode(fileio *self, void *closure)
Guido van Rossum53807da2007-04-10 19:01:47 +00001138{
Antoine Pitrouae4b4722010-05-05 16:31:07 +00001139 return PyUnicode_FromString(mode_string(self));
Guido van Rossumb0428152007-04-08 17:44:42 +00001140}
1141
1142static PyGetSetDef fileio_getsetlist[] = {
Antoine Pitrouae4b4722010-05-05 16:31:07 +00001143 {"closed", (getter)get_closed, NULL, "True if the file is closed"},
1144 {"closefd", (getter)get_closefd, NULL,
1145 "True if the file descriptor will be closed"},
1146 {"mode", (getter)get_mode, NULL, "String giving the file mode"},
1147 {NULL},
Guido van Rossumb0428152007-04-08 17:44:42 +00001148};
1149
Guido van Rossuma9e20242007-03-08 00:43:48 +00001150PyTypeObject PyFileIO_Type = {
Antoine Pitrouae4b4722010-05-05 16:31:07 +00001151 PyVarObject_HEAD_INIT(NULL, 0)
1152 "_io.FileIO",
1153 sizeof(fileio),
1154 0,
1155 (destructor)fileio_dealloc, /* tp_dealloc */
1156 0, /* tp_print */
1157 0, /* tp_getattr */
1158 0, /* tp_setattr */
1159 0, /* tp_reserved */
1160 (reprfunc)fileio_repr, /* tp_repr */
1161 0, /* tp_as_number */
1162 0, /* tp_as_sequence */
1163 0, /* tp_as_mapping */
1164 0, /* tp_hash */
1165 0, /* tp_call */
1166 0, /* tp_str */
1167 PyObject_GenericGetAttr, /* tp_getattro */
1168 0, /* tp_setattro */
1169 0, /* tp_as_buffer */
1170 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE
1171 | Py_TPFLAGS_HAVE_GC, /* tp_flags */
1172 fileio_doc, /* tp_doc */
1173 (traverseproc)fileio_traverse, /* tp_traverse */
1174 (inquiry)fileio_clear, /* tp_clear */
1175 0, /* tp_richcompare */
1176 offsetof(fileio, weakreflist), /* tp_weaklistoffset */
1177 0, /* tp_iter */
1178 0, /* tp_iternext */
1179 fileio_methods, /* tp_methods */
1180 0, /* tp_members */
1181 fileio_getsetlist, /* tp_getset */
1182 0, /* tp_base */
1183 0, /* tp_dict */
1184 0, /* tp_descr_get */
1185 0, /* tp_descr_set */
1186 offsetof(fileio, dict), /* tp_dictoffset */
1187 fileio_init, /* tp_init */
1188 PyType_GenericAlloc, /* tp_alloc */
1189 fileio_new, /* tp_new */
1190 PyObject_GC_Del, /* tp_free */
Guido van Rossuma9e20242007-03-08 00:43:48 +00001191};