Debian Codegraph @

cpython27/Modules/_io/fileio.c

raw symbols SCIP
1 /* Author: Daniel Stutzbach */
2
3 #define PY_SSIZE_T_CLEAN
4 #include "Python.h"
5 #ifdef HAVE_SYS_TYPES_H
6 #include <sys/types.h>
7 #endif
8 #ifdef HAVE_SYS_STAT_H
9 #include <sys/stat.h>
10 #endif
11 #ifdef HAVE_IO_H
12 #include <io.h>
13 #endif
14 #ifdef HAVE_FCNTL_H
15 #include <fcntl.h>
16 #endif
17 #include <stddef.h> /* For offsetof */
18 #include "_iomodule.h"
19
20 /*
21 * Known likely problems:
22 *
23 * - Files larger then 2**32-1
24 * - Files with unicode filenames
25 * - Passing numbers greater than 2**32-1 when an integer is expected
26 * - Making it work on Windows and other oddball platforms
27 *
28 * To Do:
29 *
30 * - autoconfify header file inclusion
31 */
32
33 #ifdef MS_WINDOWS
34 /* can simulate truncate with Win32 API functions; see file_truncate */
35 #define HAVE_FTRUNCATE
36 #define WIN32_LEAN_AND_MEAN
37 #include <windows.h>
38 #endif
39
40 #if BUFSIZ < (8*1024)
41 #define SMALLCHUNK (8*1024)
42 #elif (BUFSIZ >= (2 << 25))
43 #error "unreasonable BUFSIZ > 64MB defined"
44 #else
45 #define SMALLCHUNK BUFSIZ
46 #endif
47
48 typedef struct {
49 PyObject_HEAD
50 int fd;
51 unsigned int readable : 1;
52 unsigned int writable : 1;
53 unsigned int appending : 1;
54 signed int seekable : 2; /* -1 means unknown */
55 unsigned int closefd : 1;
56 PyObject *weakreflist;
57 PyObject *dict;
58 } fileio;
59
60 PyTypeObject PyFileIO_Type;
61
62 #define PyFileIO_Check(op) (PyObject_TypeCheck((op), &PyFileIO_Type))
63
64 int
65 _PyFileIO_closed(PyObject *self)
66 {
67 return ((fileio *)self)->fd < 0;
68 }
69
70 static PyObject *
71 portable_lseek(int fd, PyObject *posobj, int whence);
72
73 static PyObject *portable_lseek(int fd, PyObject *posobj, int whence);
74
75 /* Returns 0 on success, -1 with exception set on failure. */
76 static int
77 internal_close(fileio *self)
78 {
79 int err = 0;
80 int save_errno = 0;
81 if (self->fd >= 0) {
82 int fd = self->fd;
83 self->fd = -1;
84 /* fd is accessible and someone else may have closed it */
85 if (_PyVerify_fd(fd)) {
86 Py_BEGIN_ALLOW_THREADS
87 err = close(fd);
88 if (err < 0)
89 save_errno = errno;
90 Py_END_ALLOW_THREADS
91 } else {
92 save_errno = errno;
93 err = -1;
94 }
95 }
96 if (err < 0) {
97 errno = save_errno;
98 PyErr_SetFromErrno(PyExc_IOError);
99 return -1;
100 }
101 return 0;
102 }
103
104 static PyObject *
105 fileio_close(fileio *self)
106 {
107 PyObject *res;
108 res = PyObject_CallMethod((PyObject*)&PyRawIOBase_Type,
109 "close", "O", self);
110 if (!self->closefd) {
111 self->fd = -1;
112 return res;
113 }
114 if (internal_close(self) < 0)
115 Py_CLEAR(res);
116 return res;
117 }
118
119 static PyObject *
120 fileio_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
121 {
122 fileio *self;
123
124 assert(type != NULL && type->tp_alloc != NULL);
125
126 self = (fileio *) type->tp_alloc(type, 0);
127 if (self != NULL) {
128 self->fd = -1;
129 self->readable = 0;
130 self->writable = 0;
131 self->appending = 0;
132 self->seekable = -1;
133 self->closefd = 1;
134 self->weakreflist = NULL;
135 }
136
137 return (PyObject *) self;
138 }
139
140 /* On Unix, open will succeed for directories.
141 In Python, there should be no file objects referring to
142 directories, so we need a check. */
143
144 static int
145 dircheck(fileio* self, PyObject *nameobj)
146 {
147 #if defined(HAVE_FSTAT) && defined(S_IFDIR) && defined(EISDIR)
148 struct stat buf;
149 int res;
150 if (self->fd < 0)
151 return 0;
152
153 Py_BEGIN_ALLOW_THREADS
154 res = fstat(self->fd, &buf);
155 Py_END_ALLOW_THREADS
156
157 if (res == 0 && S_ISDIR(buf.st_mode)) {
158 errno = EISDIR;
159 PyErr_SetFromErrnoWithFilenameObject(PyExc_IOError, nameobj);
160 return -1;
161 }
162 #endif
163 return 0;
164 }
165
166 static int
167 check_fd(int fd)
168 {
169 #if defined(HAVE_FSTAT)
170 struct stat buf;
171 int res;
172 PyObject *exc;
173 char *msg;
174
175 if (!_PyVerify_fd(fd)) {
176 goto badfd;
177 }
178
179 Py_BEGIN_ALLOW_THREADS
180 res = fstat(fd, &buf);
181 Py_END_ALLOW_THREADS
182
183 if (res < 0 && errno == EBADF) {
184 goto badfd;
185 }
186
187 return 0;
188
189 badfd:
190 msg = strerror(EBADF);
191 exc = PyObject_CallFunction(PyExc_OSError, "(is)",
192 EBADF, msg);
193 PyErr_SetObject(PyExc_OSError, exc);
194 Py_XDECREF(exc);
195 return -1;
196 #else
197 return 0;
198 #endif
199 }
200
201
202 static int
203 fileio_init(PyObject *oself, PyObject *args, PyObject *kwds)
204 {
205 fileio *self = (fileio *) oself;
206 static char *kwlist[] = {"file", "mode", "closefd", NULL};
207 const char *name = NULL;
208 PyObject *nameobj, *stringobj = NULL;
209 char *mode = "r";
210 char *s;
211 #ifdef MS_WINDOWS
212 Py_UNICODE *widename = NULL;
213 #endif
214 int ret = 0;
215 int rwa = 0, plus = 0;
216 int flags = 0;
217 int fd = -1;
218 int closefd = 1;
219 int fd_is_own = 0;
220
221 assert(PyFileIO_Check(oself));
222 if (self->fd >= 0) {
223 if (self->closefd) {
224 /* Have to close the existing file first. */
225 if (internal_close(self) < 0)
226 return -1;
227 }
228 else
229 self->fd = -1;
230 }
231
232 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|si:fileio",
233 kwlist, &nameobj, &mode, &closefd))
234 return -1;
235
236 if (PyFloat_Check(nameobj)) {
237 PyErr_SetString(PyExc_TypeError,
238 "integer argument expected, got float");
239 return -1;
240 }
241
242 fd = _PyLong_AsInt(nameobj);
243 if (fd < 0) {
244 if (!PyErr_Occurred()) {
245 PyErr_SetString(PyExc_ValueError,
246 "negative file descriptor");
247 return -1;
248 }
249 PyErr_Clear();
250 }
251
252 #ifdef MS_WINDOWS
253 if (PyUnicode_Check(nameobj)) {
254 widename = PyUnicode_AS_UNICODE(nameobj);
255 if (wcslen(widename) != (size_t)PyUnicode_GET_SIZE(nameobj)) {
256 PyErr_SetString(PyExc_TypeError, "embedded NUL character");
257 return -1;
258 }
259 }
260 if (widename == NULL)
261 #endif
262 if (fd < 0)
263 {
264 if (PyBytes_Check(nameobj) || PyByteArray_Check(nameobj)) {
265 Py_ssize_t namelen;
266 if (PyObject_AsCharBuffer(nameobj, &name, &namelen) < 0)
267 return -1;
268 if (strlen(name) != (size_t)namelen) {
269 PyErr_SetString(PyExc_TypeError, "embedded NUL character");
270 return -1;
271 }
272 }
273 else {
274 PyObject *u = PyUnicode_FromObject(nameobj);
275
276 if (u == NULL)
277 return -1;
278
279 stringobj = PyUnicode_AsEncodedString(
280 u, Py_FileSystemDefaultEncoding, NULL);
281 Py_DECREF(u);
282 if (stringobj == NULL)
283 return -1;
284 if (!PyBytes_Check(stringobj)) {
285 PyErr_SetString(PyExc_TypeError,
286 "encoder failed to return bytes");
287 goto error;
288 }
289 name = PyBytes_AS_STRING(stringobj);
290 if (strlen(name) != (size_t)PyBytes_GET_SIZE(stringobj)) {
291 PyErr_SetString(PyExc_TypeError, "embedded NUL character");
292 goto error;
293 }
294 }
295 }
296
297 s = mode;
298 while (*s) {
299 switch (*s++) {
300 case 'r':
301 if (rwa) {
302 bad_mode:
303 PyErr_SetString(PyExc_ValueError,
304 "Must have exactly one of read/write/append "
305 "mode and at most one plus");
306 goto error;
307 }
308 rwa = 1;
309 self->readable = 1;
310 break;
311 case 'w':
312 if (rwa)
313 goto bad_mode;
314 rwa = 1;
315 self->writable = 1;
316 flags |= O_CREAT | O_TRUNC;
317 break;
318 case 'a':
319 if (rwa)
320 goto bad_mode;
321 rwa = 1;
322 self->writable = 1;
323 self->appending = 1;
324 flags |= O_APPEND | O_CREAT;
325 break;
326 case 'b':
327 break;
328 case '+':
329 if (plus)
330 goto bad_mode;
331 self->readable = self->writable = 1;
332 plus = 1;
333 break;
334 default:
335 PyErr_Format(PyExc_ValueError,
336 "invalid mode: %.200s", mode);
337 goto error;
338 }
339 }
340
341 if (!rwa)
342 goto bad_mode;
343
344 if (self->readable && self->writable)
345 flags |= O_RDWR;
346 else if (self->readable)
347 flags |= O_RDONLY;
348 else
349 flags |= O_WRONLY;
350
351 #ifdef O_BINARY
352 flags |= O_BINARY;
353 #endif
354
355 if (fd >= 0) {
356 if (check_fd(fd))
357 goto error;
358 self->fd = fd;
359 self->closefd = closefd;
360 }
361 else {
362 self->closefd = 1;
363 if (!closefd) {
364 PyErr_SetString(PyExc_ValueError,
365 "Cannot use closefd=False with file name");
366 goto error;
367 }
368
369 Py_BEGIN_ALLOW_THREADS
370 errno = 0;
371 #ifdef MS_WINDOWS
372 if (widename != NULL)
373 self->fd = _wopen(widename, flags, 0666);
374 else
375 #endif
376 self->fd = open(name, flags, 0666);
377 Py_END_ALLOW_THREADS
378 fd_is_own = 1;
379 if (self->fd < 0) {
380 #ifdef MS_WINDOWS
381 if (widename != NULL)
382 PyErr_SetFromErrnoWithUnicodeFilename(PyExc_IOError, widename);
383 else
384 #endif
385 PyErr_SetFromErrnoWithFilename(PyExc_IOError, name);
386 goto error;
387 }
388 }
389 if (dircheck(self, nameobj) < 0)
390 goto error;
391
392 if (PyObject_SetAttrString((PyObject *)self, "name", nameobj) < 0)
393 goto error;
394
395 if (self->appending) {
396 /* For consistent behaviour, we explicitly seek to the
397 end of file (otherwise, it might be done only on the
398 first write()). */
399 PyObject *pos = portable_lseek(self->fd, NULL, 2);
400 if (pos == NULL)
401 goto error;
402 Py_DECREF(pos);
403 }
404
405 goto done;
406
407 error:
408 if (!fd_is_own)
409 self->fd = -1;
410
411 ret = -1;
412
413 done:
414 Py_CLEAR(stringobj);
415 return ret;
416 }
417
418 static int
419 fileio_traverse(fileio *self, visitproc visit, void *arg)
420 {
421 Py_VISIT(self->dict);
422 return 0;
423 }
424
425 static int
426 fileio_clear(fileio *self)
427 {
428 Py_CLEAR(self->dict);
429 return 0;
430 }
431
432 static void
433 fileio_dealloc(fileio *self)
434 {
435 if (_PyIOBase_finalize((PyObject *) self) < 0)
436 return;
437 _PyObject_GC_UNTRACK(self);
438 if (self->weakreflist != NULL)
439 PyObject_ClearWeakRefs((PyObject *) self);
440 Py_CLEAR(self->dict);
441 Py_TYPE(self)->tp_free((PyObject *)self);
442 }
443
444 static PyObject *
445 err_closed(void)
446 {
447 PyErr_SetString(PyExc_ValueError, "I/O operation on closed file");
448 return NULL;
449 }
450
451 static PyObject *
452 err_mode(char *action)
453 {
454 PyErr_Format(PyExc_ValueError, "File not open for %s", action);
455 return NULL;
456 }
457
458 static PyObject *
459 fileio_fileno(fileio *self)
460 {
461 if (self->fd < 0)
462 return err_closed();
463 return PyInt_FromLong((long) self->fd);
464 }
465
466 static PyObject *
467 fileio_readable(fileio *self)
468 {
469 if (self->fd < 0)
470 return err_closed();
471 return PyBool_FromLong((long) self->readable);
472 }
473
474 static PyObject *
475 fileio_writable(fileio *self)
476 {
477 if (self->fd < 0)
478 return err_closed();
479 return PyBool_FromLong((long) self->writable);
480 }
481
482 static PyObject *
483 fileio_seekable(fileio *self)
484 {
485 if (self->fd < 0)
486 return err_closed();
487 if (self->seekable < 0) {
488 PyObject *pos = portable_lseek(self->fd, NULL, SEEK_CUR);
489 if (pos == NULL) {
490 PyErr_Clear();
491 self->seekable = 0;
492 } else {
493 Py_DECREF(pos);
494 self->seekable = 1;
495 }
496 }
497 return PyBool_FromLong((long) self->seekable);
498 }
499
500 static PyObject *
501 fileio_readinto(fileio *self, PyObject *args)
502 {
503 Py_buffer pbuf;
504 Py_ssize_t n, len;
505
506 if (self->fd < 0)
507 return err_closed();
508 if (!self->readable)
509 return err_mode("reading");
510
511 if (!PyArg_ParseTuple(args, "w*", &pbuf))
512 return NULL;
513
514 if (_PyVerify_fd(self->fd)) {
515 len = pbuf.len;
516 Py_BEGIN_ALLOW_THREADS
517 errno = 0;
518 #if defined(MS_WIN64) || defined(MS_WINDOWS)
519 if (len > INT_MAX)
520 len = INT_MAX;
521 n = read(self->fd, pbuf.buf, (int)len);
522 #else
523 n = read(self->fd, pbuf.buf, len);
524 #endif
525 Py_END_ALLOW_THREADS
526 } else
527 n = -1;
528 PyBuffer_Release(&pbuf);
529 if (n < 0) {
530 if (errno == EAGAIN)
531 Py_RETURN_NONE;
532 PyErr_SetFromErrno(PyExc_IOError);
533 return NULL;
534 }
535
536 return PyLong_FromSsize_t(n);
537 }
538
539 static size_t
540 new_buffersize(fileio *self, size_t currentsize)
541 {
542 #ifdef HAVE_FSTAT
543 off_t pos, end;
544 struct stat st;
545 int res;
546
547 Py_BEGIN_ALLOW_THREADS
548 res = fstat(self->fd, &st);
549 Py_END_ALLOW_THREADS
550
551 if (res == 0) {
552 end = st.st_size;
553
554 Py_BEGIN_ALLOW_THREADS
555 pos = lseek(self->fd, 0L, SEEK_CUR);
556 Py_END_ALLOW_THREADS
557
558 /* Files claiming a size smaller than SMALLCHUNK may
559 actually be streaming pseudo-files. In this case, we
560 apply the more aggressive algorithm below.
561 */
562 if (end >= SMALLCHUNK && end >= pos && pos >= 0) {
563 /* Add 1 so if the file were to grow we'd notice. */
564 return currentsize + end - pos + 1;
565 }
566 }
567 #endif
568 /* Expand the buffer by an amount proportional to the current size,
569 giving us amortized linear-time behavior. Use a less-than-double
570 growth factor to avoid excessive allocation. */
571 return currentsize + (currentsize >> 3) + 6;
572 }
573
574 static PyObject *
575 fileio_readall(fileio *self)
576 {
577 PyObject *result;
578 Py_ssize_t total = 0;
579 Py_ssize_t n;
580
581 if (self->fd < 0)
582 return err_closed();
583 if (!_PyVerify_fd(self->fd))
584 return PyErr_SetFromErrno(PyExc_IOError);
585
586 result = PyBytes_FromStringAndSize(NULL, SMALLCHUNK);
587 if (result == NULL)
588 return NULL;
589
590 while (1) {
591 size_t newsize = new_buffersize(self, total);
592 if (newsize > PY_SSIZE_T_MAX || newsize <= 0) {
593 PyErr_SetString(PyExc_OverflowError,
594 "unbounded read returned more bytes "
595 "than a Python string can hold ");
596 Py_DECREF(result);
597 return NULL;
598 }
599
600 if (PyBytes_GET_SIZE(result) < (Py_ssize_t)newsize) {
601 if (_PyBytes_Resize(&result, newsize) < 0)
602 return NULL; /* result has been freed */
603 }
604 Py_BEGIN_ALLOW_THREADS
605 errno = 0;
606 n = newsize - total;
607 #if defined(MS_WIN64) || defined(MS_WINDOWS)
608 if (n > INT_MAX)
609 n = INT_MAX;
610 n = read(self->fd,
611 PyBytes_AS_STRING(result) + total,
612 (int)n);
613 #else
614 n = read(self->fd,
615 PyBytes_AS_STRING(result) + total,
616 n);
617 #endif
618 Py_END_ALLOW_THREADS
619 if (n == 0)
620 break;
621 if (n < 0) {
622 if (errno == EINTR) {
623 if (PyErr_CheckSignals()) {
624 Py_DECREF(result);
625 return NULL;
626 }
627 continue;
628 }
629 if (errno == EAGAIN) {
630 if (total > 0)
631 break;
632 Py_DECREF(result);
633 Py_RETURN_NONE;
634 }
635 Py_DECREF(result);
636 PyErr_SetFromErrno(PyExc_IOError);
637 return NULL;
638 }
639 total += n;
640 }
641
642 if (PyBytes_GET_SIZE(result) > total) {
643 if (_PyBytes_Resize(&result, total) < 0) {
644 /* This should never happen, but just in case */
645 return NULL;
646 }
647 }
648 return result;
649 }
650
651 static PyObject *
652 fileio_read(fileio *self, PyObject *args)
653 {
654 char *ptr;
655 Py_ssize_t n;
656 Py_ssize_t size = -1;
657 PyObject *bytes;
658
659 if (self->fd < 0)
660 return err_closed();
661 if (!self->readable)
662 return err_mode("reading");
663
664 if (!PyArg_ParseTuple(args, "|O&", &_PyIO_ConvertSsize_t, &size))
665 return NULL;
666
667 if (size < 0) {
668 return fileio_readall(self);
669 }
670
671 #if defined(MS_WIN64) || defined(MS_WINDOWS)
672 if (size > INT_MAX)
673 size = INT_MAX;
674 #endif
675 bytes = PyBytes_FromStringAndSize(NULL, size);
676 if (bytes == NULL)
677 return NULL;
678 ptr = PyBytes_AS_STRING(bytes);
679
680 if (_PyVerify_fd(self->fd)) {
681 Py_BEGIN_ALLOW_THREADS
682 errno = 0;
683 #if defined(MS_WIN64) || defined(MS_WINDOWS)
684 n = read(self->fd, ptr, (int)size);
685 #else
686 n = read(self->fd, ptr, size);
687 #endif
688 Py_END_ALLOW_THREADS
689 } else
690 n = -1;
691
692 if (n < 0) {
693 Py_DECREF(bytes);
694 if (errno == EAGAIN)
695 Py_RETURN_NONE;
696 PyErr_SetFromErrno(PyExc_IOError);
697 return NULL;
698 }
699
700 if (n != size) {
701 if (_PyBytes_Resize(&bytes, n) < 0)
702 return NULL;
703 }
704
705 return (PyObject *) bytes;
706 }
707
708 static PyObject *
709 fileio_write(fileio *self, PyObject *args)
710 {
711 Py_buffer pbuf;
712 Py_ssize_t n, len;
713
714 if (self->fd < 0)
715 return err_closed();
716 if (!self->writable)
717 return err_mode("writing");
718
719 if (!PyArg_ParseTuple(args, "s*:write", &pbuf)) {
720 return NULL;
721 }
722 if (PyUnicode_Check(PyTuple_GET_ITEM(args, 0)) &&
723 PyErr_WarnPy3k("write() argument must be string or buffer, "
724 "not 'unicode'", 1) < 0)
725 {
726 PyBuffer_Release(&pbuf);
727 return NULL;
728 }
729
730 if (_PyVerify_fd(self->fd)) {
731 Py_BEGIN_ALLOW_THREADS
732 errno = 0;
733 len = pbuf.len;
734 #if defined(MS_WIN64) || defined(MS_WINDOWS)
735 if (len > INT_MAX)
736 len = INT_MAX;
737 n = write(self->fd, pbuf.buf, (int)len);
738 #else
739 n = write(self->fd, pbuf.buf, len);
740 #endif
741 Py_END_ALLOW_THREADS
742 } else
743 n = -1;
744
745 PyBuffer_Release(&pbuf);
746
747 if (n < 0) {
748 if (errno == EAGAIN)
749 Py_RETURN_NONE;
750 PyErr_SetFromErrno(PyExc_IOError);
751 return NULL;
752 }
753
754 return PyLong_FromSsize_t(n);
755 }
756
757 /* XXX Windows support below is likely incomplete */
758
759 /* Cribbed from posix_lseek() */
760 static PyObject *
761 portable_lseek(int fd, PyObject *posobj, int whence)
762 {
763 Py_off_t pos, res;
764
765 #ifdef SEEK_SET
766 /* Turn 0, 1, 2 into SEEK_{SET,CUR,END} */
767 switch (whence) {
768 #if SEEK_SET != 0
769 case 0: whence = SEEK_SET; break;
770 #endif
771 #if SEEK_CUR != 1
772 case 1: whence = SEEK_CUR; break;
773 #endif
774 #if SEEK_END != 2
775 case 2: whence = SEEK_END; break;
776 #endif
777 }
778 #endif /* SEEK_SET */
779
780 if (posobj == NULL)
781 pos = 0;
782 else {
783 if(PyFloat_Check(posobj)) {
784 PyErr_SetString(PyExc_TypeError, "an integer is required");
785 return NULL;
786 }
787 #if defined(HAVE_LARGEFILE_SUPPORT)
788 pos = PyLong_AsLongLong(posobj);
789 #else
790 pos = PyLong_AsLong(posobj);
791 #endif
792 if (PyErr_Occurred())
793 return NULL;
794 }
795
796 if (_PyVerify_fd(fd)) {
797 Py_BEGIN_ALLOW_THREADS
798 #if defined(MS_WIN64) || defined(MS_WINDOWS)
799 res = _lseeki64(fd, pos, whence);
800 #else
801 res = lseek(fd, pos, whence);
802 #endif
803 Py_END_ALLOW_THREADS
804 } else
805 res = -1;
806 if (res < 0)
807 return PyErr_SetFromErrno(PyExc_IOError);
808
809 #if defined(HAVE_LARGEFILE_SUPPORT)
810 return PyLong_FromLongLong(res);
811 #else
812 return PyLong_FromLong(res);
813 #endif
814 }
815
816 static PyObject *
817 fileio_seek(fileio *self, PyObject *args)
818 {
819 PyObject *posobj;
820 int whence = 0;
821
822 if (self->fd < 0)
823 return err_closed();
824
825 if (!PyArg_ParseTuple(args, "O|i", &posobj, &whence))
826 return NULL;
827
828 return portable_lseek(self->fd, posobj, whence);
829 }
830
831 static PyObject *
832 fileio_tell(fileio *self, PyObject *args)
833 {
834 if (self->fd < 0)
835 return err_closed();
836
837 return portable_lseek(self->fd, NULL, 1);
838 }
839
840 #ifdef HAVE_FTRUNCATE
841 static PyObject *
842 fileio_truncate(fileio *self, PyObject *args)
843 {
844 PyObject *posobj = NULL; /* the new size wanted by the user */
845 #ifndef MS_WINDOWS
846 Py_off_t pos;
847 #endif
848 int ret;
849 int fd;
850
851 fd = self->fd;
852 if (fd < 0)
853 return err_closed();
854 if (!self->writable)
855 return err_mode("writing");
856
857 if (!PyArg_ParseTuple(args, "|O", &posobj))
858 return NULL;
859
860 if (posobj == Py_None || posobj == NULL) {
861 /* Get the current position. */
862 posobj = portable_lseek(fd, NULL, 1);
863 if (posobj == NULL)
864 return NULL;
865 }
866 else {
867 Py_INCREF(posobj);
868 }
869
870 #ifdef MS_WINDOWS
871 /* MS _chsize doesn't work if newsize doesn't fit in 32 bits,
872 so don't even try using it. */
873 {
874 PyObject *oldposobj, *tempposobj;
875 HANDLE hFile;
876
877 /* we save the file pointer position */
878 oldposobj = portable_lseek(fd, NULL, 1);
879 if (oldposobj == NULL) {
880 Py_DECREF(posobj);
881 return NULL;
882 }
883
884 /* we then move to the truncation position */
885 tempposobj = portable_lseek(fd, posobj, 0);
886 if (tempposobj == NULL) {
887 Py_DECREF(oldposobj);
888 Py_DECREF(posobj);
889 return NULL;
890 }
891 Py_DECREF(tempposobj);
892
893 /* Truncate. Note that this may grow the file! */
894 Py_BEGIN_ALLOW_THREADS
895 errno = 0;
896 hFile = (HANDLE)_get_osfhandle(fd);
897 ret = hFile == (HANDLE)-1; /* testing for INVALID_HANDLE value */
898 if (ret == 0) {
899 ret = SetEndOfFile(hFile) == 0;
900 if (ret)
901 errno = EACCES;
902 }
903 Py_END_ALLOW_THREADS
904
905 /* we restore the file pointer position in any case */
906 tempposobj = portable_lseek(fd, oldposobj, 0);
907 Py_DECREF(oldposobj);
908 if (tempposobj == NULL) {
909 Py_DECREF(posobj);
910 return NULL;
911 }
912 Py_DECREF(tempposobj);
913 }
914 #else
915
916 #if defined(HAVE_LARGEFILE_SUPPORT)
917 pos = PyLong_AsLongLong(posobj);
918 #else
919 pos = PyLong_AsLong(posobj);
920 #endif
921 if (PyErr_Occurred()){
922 Py_DECREF(posobj);
923 return NULL;
924 }
925
926 Py_BEGIN_ALLOW_THREADS
927 errno = 0;
928 ret = ftruncate(fd, pos);
929 Py_END_ALLOW_THREADS
930
931 #endif /* !MS_WINDOWS */
932
933 if (ret != 0) {
934 Py_DECREF(posobj);
935 PyErr_SetFromErrno(PyExc_IOError);
936 return NULL;
937 }
938
939 return posobj;
940 }
941 #endif /* HAVE_FTRUNCATE */
942
943 static char *
944 mode_string(fileio *self)
945 {
946 if (self->appending) {
947 if (self->readable)
948 return "ab+";
949 else
950 return "ab";
951 }
952 else if (self->readable) {
953 if (self->writable)
954 return "rb+";
955 else
956 return "rb";
957 }
958 else
959 return "wb";
960 }
961
962 static PyObject *
963 fileio_repr(fileio *self)
964 {
965 PyObject *nameobj, *res;
966
967 if (self->fd < 0)
968 return PyString_FromFormat("<_io.FileIO [closed]>");
969
970 nameobj = PyObject_GetAttrString((PyObject *) self, "name");
971 if (nameobj == NULL) {
972 if (PyErr_ExceptionMatches(PyExc_AttributeError))
973 PyErr_Clear();
974 else
975 return NULL;
976 res = PyString_FromFormat("<_io.FileIO fd=%d mode='%s'>",
977 self->fd, mode_string(self));
978 }
979 else {
980 PyObject *repr = PyObject_Repr(nameobj);
981 Py_DECREF(nameobj);
982 if (repr == NULL)
983 return NULL;
984 res = PyString_FromFormat("<_io.FileIO name=%s mode='%s'>",
985 PyString_AS_STRING(repr),
986 mode_string(self));
987 Py_DECREF(repr);
988 }
989 return res;
990 }
991
992 static PyObject *
993 fileio_isatty(fileio *self)
994 {
995 long res;
996
997 if (self->fd < 0)
998 return err_closed();
999 Py_BEGIN_ALLOW_THREADS
1000 res = isatty(self->fd);
1001 Py_END_ALLOW_THREADS
1002 return PyBool_FromLong(res);
1003 }
1004
1005
1006 PyDoc_STRVAR(fileio_doc,
1007 "file(name: str[, mode: str]) -> file IO object\n"
1008 "\n"
1009 "Open a file. The mode can be 'r' (default), 'w' or 'a' for reading,\n"
1010 "writing or appending. The file will be created if it doesn't exist\n"
1011 "when opened for writing or appending; it will be truncated when\n"
1012 "opened for writing. Add a '+' to the mode to allow simultaneous\n"
1013 "reading and writing.");
1014
1015 PyDoc_STRVAR(read_doc,
1016 "read(size: int) -> bytes. read at most size bytes, returned as bytes.\n"
1017 "\n"
1018 "Only makes one system call, so less data may be returned than requested\n"
1019 "In non-blocking mode, returns None if no data is available.\n"
1020 "On end-of-file, returns ''.");
1021
1022 PyDoc_STRVAR(readall_doc,
1023 "readall() -> bytes. read all data from the file, returned as bytes.\n"
1024 "\n"
1025 "In non-blocking mode, returns as much as is immediately available,\n"
1026 "or None if no data is available. On end-of-file, returns ''.");
1027
1028 PyDoc_STRVAR(write_doc,
1029 "write(b) -> int. Write array of bytes b, return number written.\n"
1030 "\n"
1031 "Only makes one system call, so not all of the data may be written.\n"
1032 "The number of bytes actually written is returned. In non-blocking mode,\n"
1033 "returns None if the write would block."
1034 );
1035
1036 PyDoc_STRVAR(fileno_doc,
1037 "fileno() -> int. Return the underlying file descriptor (an integer).");
1038
1039 PyDoc_STRVAR(seek_doc,
1040 "seek(offset: int[, whence: int]) -> int. Move to new file position\n"
1041 "and return the file position.\n"
1042 "\n"
1043 "Argument offset is a byte count. Optional argument whence defaults to\n"
1044 "SEEK_SET or 0 (offset from start of file, offset should be >= 0); other values\n"
1045 "are SEEK_CUR or 1 (move relative to current position, positive or negative),\n"
1046 "and SEEK_END or 2 (move relative to end of file, usually negative, although\n"
1047 "many platforms allow seeking beyond the end of a file).\n"
1048 "\n"
1049 "Note that not all file objects are seekable.");
1050
1051 #ifdef HAVE_FTRUNCATE
1052 PyDoc_STRVAR(truncate_doc,
1053 "truncate([size: int]) -> int. Truncate the file to at most size bytes and\n"
1054 "return the truncated size.\n"
1055 "\n"
1056 "Size defaults to the current file position, as returned by tell().\n"
1057 "The current file position is changed to the value of size.");
1058 #endif
1059
1060 PyDoc_STRVAR(tell_doc,
1061 "tell() -> int. Current file position.\n"
1062 "\n"
1063 "Can raise OSError for non seekable files."
1064 );
1065
1066 PyDoc_STRVAR(readinto_doc,
1067 "readinto() -> Same as RawIOBase.readinto().");
1068
1069 PyDoc_STRVAR(close_doc,
1070 "close() -> None. Close the file.\n"
1071 "\n"
1072 "A closed file cannot be used for further I/O operations. close() may be\n"
1073 "called more than once without error.");
1074
1075 PyDoc_STRVAR(isatty_doc,
1076 "isatty() -> bool. True if the file is connected to a TTY device.");
1077
1078 PyDoc_STRVAR(seekable_doc,
1079 "seekable() -> bool. True if file supports random-access.");
1080
1081 PyDoc_STRVAR(readable_doc,
1082 "readable() -> bool. True if file was opened in a read mode.");
1083
1084 PyDoc_STRVAR(writable_doc,
1085 "writable() -> bool. True if file was opened in a write mode.");
1086
1087 static PyMethodDef fileio_methods[] = {
1088 {"read", (PyCFunction)fileio_read, METH_VARARGS, read_doc},
1089 {"readall", (PyCFunction)fileio_readall, METH_NOARGS, readall_doc},
1090 {"readinto", (PyCFunction)fileio_readinto, METH_VARARGS, readinto_doc},
1091 {"write", (PyCFunction)fileio_write, METH_VARARGS, write_doc},
1092 {"seek", (PyCFunction)fileio_seek, METH_VARARGS, seek_doc},
1093 {"tell", (PyCFunction)fileio_tell, METH_VARARGS, tell_doc},
1094 #ifdef HAVE_FTRUNCATE
1095 {"truncate", (PyCFunction)fileio_truncate, METH_VARARGS, truncate_doc},
1096 #endif
1097 {"close", (PyCFunction)fileio_close, METH_NOARGS, close_doc},
1098 {"seekable", (PyCFunction)fileio_seekable, METH_NOARGS, seekable_doc},
1099 {"readable", (PyCFunction)fileio_readable, METH_NOARGS, readable_doc},
1100 {"writable", (PyCFunction)fileio_writable, METH_NOARGS, writable_doc},
1101 {"fileno", (PyCFunction)fileio_fileno, METH_NOARGS, fileno_doc},
1102 {"isatty", (PyCFunction)fileio_isatty, METH_NOARGS, isatty_doc},
1103 {NULL, NULL} /* sentinel */
1104 };
1105
1106 /* 'closed' and 'mode' are attributes for backwards compatibility reasons. */
1107
1108 static PyObject *
1109 get_closed(fileio *self, void *closure)
1110 {
1111 return PyBool_FromLong((long)(self->fd < 0));
1112 }
1113
1114 static PyObject *
1115 get_closefd(fileio *self, void *closure)
1116 {
1117 return PyBool_FromLong((long)(self->closefd));
1118 }
1119
1120 static PyObject *
1121 get_mode(fileio *self, void *closure)
1122 {
1123 return PyUnicode_FromString(mode_string(self));
1124 }
1125
1126 static PyGetSetDef fileio_getsetlist[] = {
1127 {"closed", (getter)get_closed, NULL, "True if the file is closed"},
1128 {"closefd", (getter)get_closefd, NULL,
1129 "True if the file descriptor will be closed by close()."},
1130 {"mode", (getter)get_mode, NULL, "String giving the file mode"},
1131 {NULL},
1132 };
1133
1134 PyTypeObject PyFileIO_Type = {
1135 PyVarObject_HEAD_INIT(NULL, 0)
1136 "_io.FileIO",
1137 sizeof(fileio),
1138 0,
1139 (destructor)fileio_dealloc, /* tp_dealloc */
1140 0, /* tp_print */
1141 0, /* tp_getattr */
1142 0, /* tp_setattr */
1143 0, /* tp_reserved */
1144 (reprfunc)fileio_repr, /* tp_repr */
1145 0, /* tp_as_number */
1146 0, /* tp_as_sequence */
1147 0, /* tp_as_mapping */
1148 0, /* tp_hash */
1149 0, /* tp_call */
1150 0, /* tp_str */
1151 PyObject_GenericGetAttr, /* tp_getattro */
1152 0, /* tp_setattro */
1153 0, /* tp_as_buffer */
1154 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE
1155 | Py_TPFLAGS_HAVE_GC, /* tp_flags */
1156 fileio_doc, /* tp_doc */
1157 (traverseproc)fileio_traverse, /* tp_traverse */
1158 (inquiry)fileio_clear, /* tp_clear */
1159 0, /* tp_richcompare */
1160 offsetof(fileio, weakreflist), /* tp_weaklistoffset */
1161 0, /* tp_iter */
1162 0, /* tp_iternext */
1163 fileio_methods, /* tp_methods */
1164 0, /* tp_members */
1165 fileio_getsetlist, /* tp_getset */
1166 0, /* tp_base */
1167 0, /* tp_dict */
1168 0, /* tp_descr_get */
1169 0, /* tp_descr_set */
1170 offsetof(fileio, dict), /* tp_dictoffset */
1171 fileio_init, /* tp_init */
1172 PyType_GenericAlloc, /* tp_alloc */
1173 fileio_new, /* tp_new */
1174 PyObject_GC_Del, /* tp_free */
1175 };