/src/cpython/Modules/_io/fileio.c
Line | Count | Source |
1 | | /* Author: Daniel Stutzbach */ |
2 | | |
3 | | #include "Python.h" |
4 | | #include "pycore_abstract.h" // _PyIndex_Check() |
5 | | #include "pycore_fileutils.h" // _Py_BEGIN_SUPPRESS_IPH |
6 | | #include "pycore_object.h" // _PyObject_GC_UNTRACK() |
7 | | #include "pycore_pyerrors.h" // _PyErr_ChainExceptions1() |
8 | | |
9 | | #include <stdbool.h> // bool |
10 | | #ifdef HAVE_UNISTD_H |
11 | | # include <unistd.h> // lseek() |
12 | | #endif |
13 | | #ifdef HAVE_SYS_TYPES_H |
14 | | # include <sys/types.h> |
15 | | #endif |
16 | | #ifdef HAVE_IO_H |
17 | | # include <io.h> |
18 | | #endif |
19 | | #ifdef HAVE_FCNTL_H |
20 | | # include <fcntl.h> // open() |
21 | | #endif |
22 | | |
23 | | #include "_iomodule.h" |
24 | | |
25 | | /* |
26 | | * Known likely problems: |
27 | | * |
28 | | * - Files larger then 2**32-1 |
29 | | * - Files with unicode filenames |
30 | | * - Passing numbers greater than 2**32-1 when an integer is expected |
31 | | * - Making it work on Windows and other oddball platforms |
32 | | * |
33 | | * To Do: |
34 | | * |
35 | | * - autoconfify header file inclusion |
36 | | */ |
37 | | |
38 | | #ifdef MS_WINDOWS |
39 | | // can simulate truncate with Win32 API functions; see file_truncate |
40 | | # define HAVE_FTRUNCATE |
41 | | # ifndef WIN32_LEAN_AND_MEAN |
42 | | # define WIN32_LEAN_AND_MEAN |
43 | | # endif |
44 | | # include <windows.h> |
45 | | #endif |
46 | | |
47 | | #if BUFSIZ < (8*1024) |
48 | | # define SMALLCHUNK (8*1024) |
49 | | #elif (BUFSIZ >= (2 << 25)) |
50 | | # error "unreasonable BUFSIZ > 64 MiB defined" |
51 | | #else |
52 | 0 | # define SMALLCHUNK BUFSIZ |
53 | | #endif |
54 | | |
55 | | /* Size at which a buffer is considered "large" and behavior should change to |
56 | | avoid excessive memory allocation */ |
57 | 2.07k | #define LARGE_BUFFER_CUTOFF_SIZE 65536 |
58 | | |
59 | | /*[clinic input] |
60 | | module _io |
61 | | class _io.FileIO "fileio *" "clinic_state()->PyFileIO_Type" |
62 | | [clinic start generated code]*/ |
63 | | /*[clinic end generated code: output=da39a3ee5e6b4b0d input=ac25ec278f4d6703]*/ |
64 | | |
65 | | typedef struct { |
66 | | PyObject_HEAD |
67 | | int fd; |
68 | | unsigned int created : 1; |
69 | | unsigned int readable : 1; |
70 | | unsigned int writable : 1; |
71 | | unsigned int appending : 1; |
72 | | signed int seekable : 2; /* -1 means unknown */ |
73 | | unsigned int truncate : 1; |
74 | | unsigned int closefd : 1; |
75 | | char finalizing; |
76 | | /* Stat result which was grabbed at file open, useful for optimizing common |
77 | | File I/O patterns to be more efficient. This is only guidance / an |
78 | | estimate, as it is subject to Time-Of-Check to Time-Of-Use (TOCTOU) |
79 | | issues / bugs. Both the underlying file descriptor and file may be |
80 | | modified outside of the fileio object / Python (ex. gh-90102, GH-121941, |
81 | | gh-109523). */ |
82 | | struct _Py_stat_struct *stat_atopen; |
83 | | } fileio; |
84 | | |
85 | | #define PyFileIO_Check(state, op) (PyObject_TypeCheck((op), state->PyFileIO_Type)) |
86 | 644k | #define PyFileIO_CAST(op) ((fileio *)(op)) |
87 | | |
88 | | /* Forward declarations */ |
89 | | static PyObject* portable_lseek(fileio *self, PyObject *posobj, int whence, bool suppress_pipe_error); |
90 | | |
91 | | int |
92 | | _PyFileIO_closed(PyObject *self) |
93 | 615k | { |
94 | 615k | return (PyFileIO_CAST(self)->fd < 0); |
95 | 615k | } |
96 | | |
97 | | /* Because this can call arbitrary code, it shouldn't be called when |
98 | | the refcount is 0 (that is, not directly from tp_dealloc unless |
99 | | the refcount has been temporarily re-incremented). */ |
100 | | /*[clinic input] |
101 | | _io.FileIO._dealloc_warn |
102 | | |
103 | | source: object |
104 | | / |
105 | | [clinic start generated code]*/ |
106 | | |
107 | | static PyObject * |
108 | | _io_FileIO__dealloc_warn_impl(fileio *self, PyObject *source) |
109 | | /*[clinic end generated code: output=c7b7d122decd6575 input=3ea7e1cc0685edc2]*/ |
110 | 0 | { |
111 | 0 | if (self->fd >= 0 && self->closefd) { |
112 | 0 | PyObject *exc = PyErr_GetRaisedException(); |
113 | 0 | if (PyErr_ResourceWarning(source, 1, "unclosed file %R", source)) { |
114 | | /* Spurious errors can appear at shutdown */ |
115 | 0 | if (PyErr_ExceptionMatches(PyExc_Warning)) { |
116 | 0 | PyErr_FormatUnraisable("Exception ignored " |
117 | 0 | "while finalizing file %R", self); |
118 | 0 | } |
119 | 0 | } |
120 | 0 | PyErr_SetRaisedException(exc); |
121 | 0 | } |
122 | 0 | Py_RETURN_NONE; |
123 | 0 | } |
124 | | |
125 | | /* Returns 0 on success, -1 with exception set on failure. */ |
126 | | static int |
127 | | internal_close(fileio *self) |
128 | 22.1k | { |
129 | 22.1k | int err = 0; |
130 | 22.1k | int save_errno = 0; |
131 | 22.1k | if (self->fd >= 0) { |
132 | 22.1k | int fd = self->fd; |
133 | 22.1k | self->fd = -1; |
134 | | /* fd is accessible and someone else may have closed it */ |
135 | 22.1k | Py_BEGIN_ALLOW_THREADS |
136 | 22.1k | _Py_BEGIN_SUPPRESS_IPH |
137 | 22.1k | err = close(fd); |
138 | 22.1k | if (err < 0) |
139 | 0 | save_errno = errno; |
140 | 22.1k | _Py_END_SUPPRESS_IPH |
141 | 22.1k | Py_END_ALLOW_THREADS |
142 | 22.1k | } |
143 | 22.1k | PyMem_Free(self->stat_atopen); |
144 | 22.1k | self->stat_atopen = NULL; |
145 | 22.1k | if (err < 0) { |
146 | 0 | errno = save_errno; |
147 | 0 | PyErr_SetFromErrno(PyExc_OSError); |
148 | 0 | return -1; |
149 | 0 | } |
150 | 22.1k | return 0; |
151 | 22.1k | } |
152 | | |
153 | | /*[clinic input] |
154 | | _io.FileIO.close |
155 | | |
156 | | cls: defining_class |
157 | | / |
158 | | |
159 | | Close the file. |
160 | | |
161 | | A closed file cannot be used for further I/O operations. close() |
162 | | may be called more than once without error. |
163 | | [clinic start generated code]*/ |
164 | | |
165 | | static PyObject * |
166 | | _io_FileIO_close_impl(fileio *self, PyTypeObject *cls) |
167 | | /*[clinic end generated code: output=c30cbe9d1f23ca58 input=b405751dc4163da3]*/ |
168 | 22.1k | { |
169 | 22.1k | PyObject *res; |
170 | 22.1k | int rc; |
171 | 22.1k | _PyIO_State *state = get_io_state_by_cls(cls); |
172 | 22.1k | res = PyObject_CallMethodOneArg((PyObject*)state->PyRawIOBase_Type, |
173 | 22.1k | &_Py_ID(close), (PyObject *)self); |
174 | 22.1k | if (!self->closefd) { |
175 | 0 | self->fd = -1; |
176 | 0 | return res; |
177 | 0 | } |
178 | | |
179 | 22.1k | PyObject *exc = NULL; |
180 | 22.1k | if (res == NULL) { |
181 | 0 | exc = PyErr_GetRaisedException(); |
182 | 0 | } |
183 | 22.1k | if (self->finalizing) { |
184 | 0 | PyObject *r = _io_FileIO__dealloc_warn_impl(self, (PyObject *)self); |
185 | 0 | if (r) { |
186 | 0 | Py_DECREF(r); |
187 | 0 | } |
188 | 0 | else { |
189 | 0 | PyErr_Clear(); |
190 | 0 | } |
191 | 0 | } |
192 | 22.1k | rc = internal_close(self); |
193 | 22.1k | if (res == NULL) { |
194 | 0 | _PyErr_ChainExceptions1(exc); |
195 | 0 | } |
196 | 22.1k | if (rc < 0) { |
197 | 0 | Py_CLEAR(res); |
198 | 0 | } |
199 | 22.1k | return res; |
200 | 22.1k | } |
201 | | |
202 | | static PyObject * |
203 | | fileio_new(PyTypeObject *type, PyObject *args, PyObject *kwds) |
204 | 22.3k | { |
205 | 22.3k | assert(type != NULL && type->tp_alloc != NULL); |
206 | | |
207 | 22.3k | fileio *self = (fileio *) type->tp_alloc(type, 0); |
208 | 22.3k | if (self == NULL) { |
209 | 0 | return NULL; |
210 | 0 | } |
211 | | |
212 | 22.3k | self->fd = -1; |
213 | 22.3k | self->created = 0; |
214 | 22.3k | self->readable = 0; |
215 | 22.3k | self->writable = 0; |
216 | 22.3k | self->appending = 0; |
217 | 22.3k | self->seekable = -1; |
218 | 22.3k | self->truncate = 0; |
219 | 22.3k | self->stat_atopen = NULL; |
220 | 22.3k | self->closefd = 1; |
221 | 22.3k | return (PyObject *) self; |
222 | 22.3k | } |
223 | | |
224 | | #ifdef O_CLOEXEC |
225 | | extern int _Py_open_cloexec_works; |
226 | | #endif |
227 | | |
228 | | /*[clinic input] |
229 | | _io.FileIO.__init__ |
230 | | file as nameobj: object |
231 | | mode: str = "r" |
232 | | closefd: bool = True |
233 | | opener: object = None |
234 | | |
235 | | Open a file. |
236 | | |
237 | | The mode can be 'r' (default), 'w', 'x' or 'a' for reading, |
238 | | writing, exclusive creation or appending. The file will be created |
239 | | if it doesn't exist when opened for writing or appending; it will be |
240 | | truncated when opened for writing. A FileExistsError will be raised |
241 | | if it already exists when opened for creating. Opening a file for |
242 | | creating implies writing so this mode behaves in a similar way to |
243 | | 'w'. Add a '+' to the mode to allow simultaneous reading and |
244 | | writing. |
245 | | |
246 | | A custom opener can be used by passing a callable as *opener*. |
247 | | The underlying file descriptor for the file object is then obtained |
248 | | by calling opener with (*name*, *flags*). *opener* must return |
249 | | an open file descriptor (passing os.open as *opener* results in |
250 | | functionality similar to passing None). |
251 | | [clinic start generated code]*/ |
252 | | |
253 | | static int |
254 | | _io_FileIO___init___impl(fileio *self, PyObject *nameobj, const char *mode, |
255 | | int closefd, PyObject *opener) |
256 | | /*[clinic end generated code: output=23413f68e6484bbd input=bac4efcd8f930bf3]*/ |
257 | 22.3k | { |
258 | | #ifdef MS_WINDOWS |
259 | | wchar_t *widename = NULL; |
260 | | #else |
261 | 22.3k | const char *name = NULL; |
262 | 22.3k | #endif |
263 | 22.3k | PyObject *stringobj = NULL; |
264 | 22.3k | const char *s; |
265 | 22.3k | int ret = 0; |
266 | 22.3k | int rwa = 0, plus = 0; |
267 | 22.3k | int flags = 0; |
268 | 22.3k | int fd = -1; |
269 | 22.3k | int fd_is_own = 0; |
270 | 22.3k | #ifdef O_CLOEXEC |
271 | 22.3k | int *atomic_flag_works = &_Py_open_cloexec_works; |
272 | | #elif !defined(MS_WINDOWS) |
273 | | int *atomic_flag_works = NULL; |
274 | | #endif |
275 | 22.3k | int fstat_result; |
276 | 22.3k | int async_err = 0; |
277 | | |
278 | | #ifdef Py_DEBUG |
279 | | _PyIO_State *state = find_io_state_by_def(Py_TYPE(self)); |
280 | | assert(PyFileIO_Check(state, self)); |
281 | | #endif |
282 | 22.3k | if (self->fd >= 0) { |
283 | 0 | if (self->closefd) { |
284 | | /* Have to close the existing file first. */ |
285 | 0 | if (internal_close(self) < 0) { |
286 | 0 | return -1; |
287 | 0 | } |
288 | 0 | } |
289 | 0 | else |
290 | 0 | self->fd = -1; |
291 | 0 | } |
292 | | |
293 | 22.3k | if (PyBool_Check(nameobj)) { |
294 | 0 | if (PyErr_WarnEx(PyExc_RuntimeWarning, |
295 | 0 | "bool is used as a file descriptor", 1)) |
296 | 0 | { |
297 | 0 | return -1; |
298 | 0 | } |
299 | 0 | } |
300 | 22.3k | if (_PyIndex_Check(nameobj)) { |
301 | 247 | fd = PyLong_AsInt(nameobj); |
302 | 247 | if (fd < 0) { |
303 | 0 | if (!PyErr_Occurred()) { |
304 | 0 | PyErr_SetString(PyExc_ValueError, |
305 | 0 | "negative file descriptor"); |
306 | 0 | return -1; |
307 | 0 | } |
308 | | /* Failed to convert; try other paths. */ |
309 | 0 | PyErr_Clear(); |
310 | 0 | } |
311 | 247 | } |
312 | | |
313 | 22.3k | if (fd < 0) { |
314 | | #ifdef MS_WINDOWS |
315 | | if (!PyUnicode_FSDecoder(nameobj, &stringobj)) { |
316 | | return -1; |
317 | | } |
318 | | widename = PyUnicode_AsWideCharString(stringobj, NULL); |
319 | | if (widename == NULL) |
320 | | return -1; |
321 | | #else |
322 | 22.0k | if (!PyUnicode_FSConverter(nameobj, &stringobj)) { |
323 | 0 | return -1; |
324 | 0 | } |
325 | 22.0k | name = PyBytes_AS_STRING(stringobj); |
326 | 22.0k | #endif |
327 | 22.0k | } |
328 | | |
329 | 22.3k | s = mode; |
330 | 44.6k | while (*s) { |
331 | 22.3k | switch (*s++) { |
332 | 0 | case 'x': |
333 | 0 | if (rwa) { |
334 | 0 | bad_mode: |
335 | 0 | PyErr_SetString(PyExc_ValueError, |
336 | 0 | "Must have exactly one of create/read/write/append " |
337 | 0 | "mode and at most one plus"); |
338 | 0 | goto error; |
339 | 0 | } |
340 | 0 | rwa = 1; |
341 | 0 | self->created = 1; |
342 | 0 | self->writable = 1; |
343 | 0 | flags |= O_EXCL | O_CREAT; |
344 | 0 | break; |
345 | 2.14k | case 'r': |
346 | 2.14k | if (rwa) |
347 | 0 | goto bad_mode; |
348 | 2.14k | rwa = 1; |
349 | 2.14k | self->readable = 1; |
350 | 2.14k | break; |
351 | 20.1k | case 'w': |
352 | 20.1k | if (rwa) |
353 | 0 | goto bad_mode; |
354 | 20.1k | rwa = 1; |
355 | 20.1k | self->writable = 1; |
356 | 20.1k | self->truncate = 1; |
357 | 20.1k | flags |= O_CREAT | O_TRUNC; |
358 | 20.1k | break; |
359 | 0 | case 'a': |
360 | 0 | if (rwa) |
361 | 0 | goto bad_mode; |
362 | 0 | rwa = 1; |
363 | 0 | self->writable = 1; |
364 | 0 | self->appending = 1; |
365 | 0 | flags |= O_APPEND | O_CREAT; |
366 | 0 | break; |
367 | 0 | case 'b': |
368 | 0 | break; |
369 | 0 | case '+': |
370 | 0 | if (plus) |
371 | 0 | goto bad_mode; |
372 | 0 | self->readable = self->writable = 1; |
373 | 0 | plus = 1; |
374 | 0 | break; |
375 | 0 | default: |
376 | 0 | PyErr_Format(PyExc_ValueError, |
377 | 0 | "invalid mode: %.200s", mode); |
378 | 0 | goto error; |
379 | 22.3k | } |
380 | 22.3k | } |
381 | | |
382 | 22.3k | if (!rwa) |
383 | 0 | goto bad_mode; |
384 | | |
385 | 22.3k | if (self->readable && self->writable) |
386 | 0 | flags |= O_RDWR; |
387 | 22.3k | else if (self->readable) |
388 | 2.14k | flags |= O_RDONLY; |
389 | 20.1k | else |
390 | 20.1k | flags |= O_WRONLY; |
391 | | |
392 | | #ifdef O_BINARY |
393 | | flags |= O_BINARY; |
394 | | #endif |
395 | | |
396 | | #ifdef MS_WINDOWS |
397 | | flags |= O_NOINHERIT; |
398 | | #elif defined(O_CLOEXEC) |
399 | 22.3k | flags |= O_CLOEXEC; |
400 | 22.3k | #endif |
401 | | |
402 | 22.3k | if (PySys_Audit("open", "Osi", nameobj, mode, flags) < 0) { |
403 | 0 | goto error; |
404 | 0 | } |
405 | | |
406 | 22.3k | if (fd >= 0) { |
407 | 247 | self->fd = fd; |
408 | 247 | self->closefd = closefd; |
409 | 247 | } |
410 | 22.0k | else { |
411 | 22.0k | self->closefd = 1; |
412 | 22.0k | if (!closefd) { |
413 | 0 | PyErr_SetString(PyExc_ValueError, |
414 | 0 | "Cannot use closefd=False with file name"); |
415 | 0 | goto error; |
416 | 0 | } |
417 | | |
418 | 22.0k | errno = 0; |
419 | 22.0k | if (opener == Py_None) { |
420 | 22.0k | do { |
421 | 22.0k | Py_BEGIN_ALLOW_THREADS |
422 | | #ifdef MS_WINDOWS |
423 | | self->fd = _wopen(widename, flags, 0666); |
424 | | #else |
425 | 22.0k | self->fd = open(name, flags, 0666); |
426 | 22.0k | #endif |
427 | 22.0k | Py_END_ALLOW_THREADS |
428 | 22.0k | } while (self->fd < 0 && errno == EINTR && |
429 | 0 | !(async_err = PyErr_CheckSignals())); |
430 | | |
431 | 22.0k | if (async_err) |
432 | 0 | goto error; |
433 | | |
434 | 22.0k | if (self->fd < 0) { |
435 | 11 | PyErr_SetFromErrnoWithFilenameObject(PyExc_OSError, nameobj); |
436 | 11 | goto error; |
437 | 11 | } |
438 | 22.0k | } |
439 | 0 | else { |
440 | 0 | PyObject *fdobj; |
441 | |
|
442 | 0 | #ifndef MS_WINDOWS |
443 | | /* the opener may clear the atomic flag */ |
444 | 0 | atomic_flag_works = NULL; |
445 | 0 | #endif |
446 | |
|
447 | 0 | fdobj = PyObject_CallFunction(opener, "Oi", nameobj, flags); |
448 | 0 | if (fdobj == NULL) |
449 | 0 | goto error; |
450 | 0 | if (!PyLong_Check(fdobj)) { |
451 | 0 | Py_DECREF(fdobj); |
452 | 0 | PyErr_SetString(PyExc_TypeError, |
453 | 0 | "expected integer from opener"); |
454 | 0 | goto error; |
455 | 0 | } |
456 | | |
457 | 0 | self->fd = PyLong_AsInt(fdobj); |
458 | 0 | Py_DECREF(fdobj); |
459 | 0 | if (self->fd < 0) { |
460 | 0 | if (!PyErr_Occurred()) { |
461 | | /* The opener returned a negative but didn't set an |
462 | | exception. See issue #27066 */ |
463 | 0 | PyErr_Format(PyExc_ValueError, |
464 | 0 | "opener returned %d", self->fd); |
465 | 0 | } |
466 | 0 | goto error; |
467 | 0 | } |
468 | 0 | } |
469 | 22.0k | fd_is_own = 1; |
470 | | |
471 | 22.0k | #ifndef MS_WINDOWS |
472 | 22.0k | if (_Py_set_inheritable(self->fd, 0, atomic_flag_works) < 0) |
473 | 0 | goto error; |
474 | 22.0k | #endif |
475 | 22.0k | } |
476 | | |
477 | 22.3k | PyMem_Free(self->stat_atopen); |
478 | 22.3k | self->stat_atopen = PyMem_New(struct _Py_stat_struct, 1); |
479 | 22.3k | if (self->stat_atopen == NULL) { |
480 | 0 | PyErr_NoMemory(); |
481 | 0 | goto error; |
482 | 0 | } |
483 | 22.3k | Py_BEGIN_ALLOW_THREADS |
484 | 22.3k | fstat_result = _Py_fstat_noraise(self->fd, self->stat_atopen); |
485 | 22.3k | Py_END_ALLOW_THREADS |
486 | 22.3k | if (fstat_result < 0) { |
487 | | /* Tolerate fstat() errors other than EBADF. See Issue #25717, where |
488 | | an anonymous file on a Virtual Box shared folder filesystem would |
489 | | raise ENOENT. */ |
490 | | #ifdef MS_WINDOWS |
491 | | if (GetLastError() == ERROR_INVALID_HANDLE) { |
492 | | PyErr_SetFromWindowsErr(0); |
493 | | #else |
494 | 0 | if (errno == EBADF) { |
495 | 0 | PyErr_SetFromErrno(PyExc_OSError); |
496 | 0 | #endif |
497 | 0 | goto error; |
498 | 0 | } |
499 | | |
500 | 0 | PyMem_Free(self->stat_atopen); |
501 | 0 | self->stat_atopen = NULL; |
502 | 0 | } |
503 | 22.3k | else { |
504 | 22.3k | #if defined(S_ISDIR) && defined(EISDIR) |
505 | | /* On Unix, open will succeed for directories. |
506 | | In Python, there should be no file objects referring to |
507 | | directories, so we need a check. */ |
508 | 22.3k | if (S_ISDIR(self->stat_atopen->st_mode)) { |
509 | 0 | errno = EISDIR; |
510 | 0 | PyErr_SetFromErrnoWithFilenameObject(PyExc_OSError, nameobj); |
511 | 0 | goto error; |
512 | 0 | } |
513 | 22.3k | #endif /* defined(S_ISDIR) */ |
514 | 22.3k | } |
515 | | |
516 | | #if defined(MS_WINDOWS) || defined(__CYGWIN__) |
517 | | /* don't translate newlines (\r\n <=> \n) */ |
518 | | _setmode(self->fd, O_BINARY); |
519 | | #endif |
520 | | |
521 | 22.3k | if (PyObject_SetAttr((PyObject *)self, &_Py_ID(name), nameobj) < 0) |
522 | 0 | goto error; |
523 | | |
524 | 22.3k | if (self->appending) { |
525 | | /* For consistent behaviour, we explicitly seek to the |
526 | | end of file (otherwise, it might be done only on the |
527 | | first write()). */ |
528 | 0 | PyObject *pos = portable_lseek(self, NULL, 2, true); |
529 | 0 | if (pos == NULL) |
530 | 0 | goto error; |
531 | 0 | Py_DECREF(pos); |
532 | 0 | } |
533 | | |
534 | 22.3k | goto done; |
535 | | |
536 | 22.3k | error: |
537 | 11 | ret = -1; |
538 | 11 | if (!fd_is_own) |
539 | 11 | self->fd = -1; |
540 | 11 | if (self->fd >= 0) { |
541 | 0 | PyObject *exc = PyErr_GetRaisedException(); |
542 | 0 | internal_close(self); |
543 | 0 | _PyErr_ChainExceptions1(exc); |
544 | 0 | } |
545 | 11 | PyMem_Free(self->stat_atopen); |
546 | 11 | self->stat_atopen = NULL; |
547 | | |
548 | 22.3k | done: |
549 | | #ifdef MS_WINDOWS |
550 | | PyMem_Free(widename); |
551 | | #endif |
552 | 22.3k | Py_CLEAR(stringobj); |
553 | 22.3k | return ret; |
554 | 11 | } |
555 | | |
556 | | static int |
557 | | fileio_traverse(PyObject *op, visitproc visit, void *arg) |
558 | 6.13k | { |
559 | 6.13k | fileio *self = PyFileIO_CAST(op); |
560 | 6.13k | Py_VISIT(Py_TYPE(self)); |
561 | 6.13k | return PyObject_VisitManagedDict(op, visit, arg); |
562 | 6.13k | } |
563 | | |
564 | | static int |
565 | | fileio_clear(PyObject *op) |
566 | 22.2k | { |
567 | 22.2k | PyObject_ClearManagedDict(op); |
568 | 22.2k | return 0; |
569 | 22.2k | } |
570 | | |
571 | | static void |
572 | | fileio_dealloc(PyObject *op) |
573 | 22.2k | { |
574 | 22.2k | fileio *self = PyFileIO_CAST(op); |
575 | 22.2k | self->finalizing = 1; |
576 | 22.2k | if (_PyIOBase_finalize(op) < 0) { |
577 | 0 | return; |
578 | 0 | } |
579 | | |
580 | 22.2k | _PyObject_GC_UNTRACK(self); |
581 | 22.2k | if (self->stat_atopen != NULL) { |
582 | 0 | PyMem_Free(self->stat_atopen); |
583 | 0 | self->stat_atopen = NULL; |
584 | 0 | } |
585 | 22.2k | PyObject_ClearWeakRefs(op); |
586 | 22.2k | (void)fileio_clear(op); |
587 | | |
588 | 22.2k | PyTypeObject *tp = Py_TYPE(op); |
589 | 22.2k | tp->tp_free(op); |
590 | 22.2k | Py_DECREF(tp); |
591 | 22.2k | } |
592 | | |
593 | | static PyObject * |
594 | | err_closed(void) |
595 | 0 | { |
596 | 0 | PyErr_SetString(PyExc_ValueError, "I/O operation on closed file"); |
597 | 0 | return NULL; |
598 | 0 | } |
599 | | |
600 | | static PyObject * |
601 | | err_mode(_PyIO_State *state, const char *action) |
602 | 0 | { |
603 | 0 | return PyErr_Format(state->unsupported_operation, |
604 | 0 | "File not open for %s", action); |
605 | 0 | } |
606 | | |
607 | | /*[clinic input] |
608 | | _io.FileIO.fileno |
609 | | |
610 | | Return the underlying file descriptor (an integer). |
611 | | [clinic start generated code]*/ |
612 | | |
613 | | static PyObject * |
614 | | _io_FileIO_fileno_impl(fileio *self) |
615 | | /*[clinic end generated code: output=a9626ce5398ece90 input=0b9b2de67335ada3]*/ |
616 | 0 | { |
617 | 0 | if (self->fd < 0) |
618 | 0 | return err_closed(); |
619 | 0 | return PyLong_FromLong((long) self->fd); |
620 | 0 | } |
621 | | |
622 | | /*[clinic input] |
623 | | _io.FileIO.readable |
624 | | |
625 | | True if file was opened in a read mode. |
626 | | [clinic start generated code]*/ |
627 | | |
628 | | static PyObject * |
629 | | _io_FileIO_readable_impl(fileio *self) |
630 | | /*[clinic end generated code: output=640744a6150fe9ba input=a3fdfed6eea721c5]*/ |
631 | 2.18k | { |
632 | 2.18k | if (self->fd < 0) |
633 | 0 | return err_closed(); |
634 | 2.18k | return PyBool_FromLong((long) self->readable); |
635 | 2.18k | } |
636 | | |
637 | | /*[clinic input] |
638 | | _io.FileIO.writable |
639 | | |
640 | | True if file was opened in a write mode. |
641 | | [clinic start generated code]*/ |
642 | | |
643 | | static PyObject * |
644 | | _io_FileIO_writable_impl(fileio *self) |
645 | | /*[clinic end generated code: output=96cefc5446e89977 input=c204a808ca2e1748]*/ |
646 | 20.2k | { |
647 | 20.2k | if (self->fd < 0) |
648 | 0 | return err_closed(); |
649 | 20.2k | return PyBool_FromLong((long) self->writable); |
650 | 20.2k | } |
651 | | |
652 | | /*[clinic input] |
653 | | _io.FileIO.seekable |
654 | | |
655 | | True if file supports random-access. |
656 | | [clinic start generated code]*/ |
657 | | |
658 | | static PyObject * |
659 | | _io_FileIO_seekable_impl(fileio *self) |
660 | | /*[clinic end generated code: output=47909ca0a42e9287 input=c8e5554d2fd63c7f]*/ |
661 | 140 | { |
662 | 140 | if (self->fd < 0) |
663 | 0 | return err_closed(); |
664 | 140 | if (self->seekable < 0) { |
665 | | /* portable_lseek() sets the seekable attribute */ |
666 | 0 | PyObject *pos = portable_lseek(self, NULL, SEEK_CUR, false); |
667 | 0 | assert(self->seekable >= 0); |
668 | 0 | if (pos == NULL) { |
669 | 0 | PyErr_Clear(); |
670 | 0 | } |
671 | 0 | else { |
672 | 0 | Py_DECREF(pos); |
673 | 0 | } |
674 | 0 | } |
675 | 140 | return PyBool_FromLong((long) self->seekable); |
676 | 140 | } |
677 | | |
678 | | /*[clinic input] |
679 | | _io.FileIO.readinto |
680 | | cls: defining_class |
681 | | buffer: Py_buffer(accept={rwbuffer}) |
682 | | / |
683 | | |
684 | | Same as RawIOBase.readinto(). |
685 | | [clinic start generated code]*/ |
686 | | |
687 | | static PyObject * |
688 | | _io_FileIO_readinto_impl(fileio *self, PyTypeObject *cls, Py_buffer *buffer) |
689 | | /*[clinic end generated code: output=97f0f3d69534db34 input=fd20323e18ce1ec8]*/ |
690 | 44 | { |
691 | 44 | Py_ssize_t n; |
692 | 44 | int err; |
693 | | |
694 | 44 | if (self->fd < 0) |
695 | 0 | return err_closed(); |
696 | 44 | if (!self->readable) { |
697 | 0 | _PyIO_State *state = get_io_state_by_cls(cls); |
698 | 0 | return err_mode(state, "reading"); |
699 | 0 | } |
700 | | |
701 | 44 | n = _Py_read(self->fd, buffer->buf, buffer->len); |
702 | | /* copy errno because PyBuffer_Release() can indirectly modify it */ |
703 | 44 | err = errno; |
704 | | |
705 | 44 | if (n == -1) { |
706 | 0 | if (err == EAGAIN) { |
707 | 0 | PyErr_Clear(); |
708 | 0 | Py_RETURN_NONE; |
709 | 0 | } |
710 | 0 | return NULL; |
711 | 0 | } |
712 | | |
713 | 44 | return PyLong_FromSsize_t(n); |
714 | 44 | } |
715 | | |
716 | | static size_t |
717 | | new_buffersize(fileio *self, size_t currentsize) |
718 | 0 | { |
719 | 0 | size_t addend; |
720 | | |
721 | | /* Expand the buffer by an amount proportional to the current size, |
722 | | giving us amortized linear-time behavior. For bigger sizes, use a |
723 | | less-than-double growth factor to avoid excessive allocation. */ |
724 | 0 | assert(currentsize <= PY_SSIZE_T_MAX); |
725 | 0 | if (currentsize > LARGE_BUFFER_CUTOFF_SIZE) |
726 | 0 | addend = currentsize >> 3; |
727 | 0 | else |
728 | 0 | addend = 256 + currentsize; |
729 | 0 | if (addend < SMALLCHUNK) |
730 | | /* Avoid tiny read() calls. */ |
731 | 0 | addend = SMALLCHUNK; |
732 | 0 | return addend + currentsize; |
733 | 0 | } |
734 | | |
735 | | /*[clinic input] |
736 | | _io.FileIO.readall |
737 | | |
738 | | cls: defining_class |
739 | | / |
740 | | |
741 | | Read all data from the file, returned as bytes. |
742 | | |
743 | | Reads until either there is an error or read() returns size 0 |
744 | | (indicates EOF). If the file is already at EOF, returns an empty |
745 | | bytes object. |
746 | | |
747 | | In non-blocking mode, returns as much data as could be read before |
748 | | EAGAIN. If no data is available (EAGAIN is returned before bytes |
749 | | are read) returns None. |
750 | | [clinic start generated code]*/ |
751 | | |
752 | | static PyObject * |
753 | | _io_FileIO_readall_impl(fileio *self, PyTypeObject *cls) |
754 | | /*[clinic end generated code: output=d546737ec895c462 input=65d05bd0169f2df5]*/ |
755 | 2.07k | { |
756 | 2.07k | Py_off_t pos, end; |
757 | 2.07k | PyBytesWriter *writer; |
758 | 2.07k | Py_ssize_t bytes_read = 0; |
759 | 2.07k | Py_ssize_t n; |
760 | 2.07k | size_t bufsize; |
761 | | |
762 | 2.07k | if (self->fd < 0) { |
763 | 0 | return err_closed(); |
764 | 0 | } |
765 | 2.07k | if (!self->readable) { |
766 | 0 | _PyIO_State *state = get_io_state_by_cls(cls); |
767 | 0 | return err_mode(state, "reading"); |
768 | 0 | } |
769 | | |
770 | 2.07k | if (self->stat_atopen != NULL && self->stat_atopen->st_size < _PY_READ_MAX) { |
771 | 2.07k | end = (Py_off_t)self->stat_atopen->st_size; |
772 | 2.07k | } |
773 | 0 | else { |
774 | 0 | end = -1; |
775 | 0 | } |
776 | 2.07k | if (end <= 0) { |
777 | | /* Use a default size and resize as needed. */ |
778 | 0 | bufsize = SMALLCHUNK; |
779 | 0 | } |
780 | 2.07k | else { |
781 | | /* This is probably a real file. */ |
782 | 2.07k | if (end > _PY_READ_MAX - 1) { |
783 | 0 | bufsize = _PY_READ_MAX; |
784 | 0 | } |
785 | 2.07k | else { |
786 | | /* In order to detect end of file, need a read() of at |
787 | | least 1 byte which returns size 0. Oversize the buffer |
788 | | by 1 byte so the I/O can be completed with two read() |
789 | | calls (one for all data, one for EOF) without needing |
790 | | to resize the buffer. */ |
791 | 2.07k | bufsize = (size_t)end + 1; |
792 | 2.07k | } |
793 | | |
794 | | /* While a lot of code does open().read() to get the whole contents |
795 | | of a file it is possible a caller seeks/reads a ways into the file |
796 | | then calls readall() to get the rest, which would result in allocating |
797 | | more than required. Guard against that for larger files where we expect |
798 | | the I/O time to dominate anyways while keeping small files fast. */ |
799 | 2.07k | if (bufsize > LARGE_BUFFER_CUTOFF_SIZE) { |
800 | 202 | Py_BEGIN_ALLOW_THREADS |
801 | 202 | _Py_BEGIN_SUPPRESS_IPH |
802 | | #ifdef MS_WINDOWS |
803 | | pos = _lseeki64(self->fd, 0L, SEEK_CUR); |
804 | | #else |
805 | 202 | pos = lseek(self->fd, 0L, SEEK_CUR); |
806 | 202 | #endif |
807 | 202 | _Py_END_SUPPRESS_IPH |
808 | 202 | Py_END_ALLOW_THREADS |
809 | | |
810 | 202 | if (end >= pos && pos >= 0 && (end - pos) < (_PY_READ_MAX - 1)) { |
811 | 202 | bufsize = (size_t)(end - pos) + 1; |
812 | 202 | } |
813 | 202 | } |
814 | 2.07k | } |
815 | | |
816 | 2.07k | writer = PyBytesWriter_Create(bufsize); |
817 | 2.07k | if (writer == NULL) { |
818 | 0 | return NULL; |
819 | 0 | } |
820 | | |
821 | 4.15k | while (1) { |
822 | 4.15k | if (bytes_read >= (Py_ssize_t)bufsize) { |
823 | 0 | bufsize = new_buffersize(self, bytes_read); |
824 | 0 | if (bufsize > PY_SSIZE_T_MAX || bufsize <= 0) { |
825 | 0 | PyErr_SetString(PyExc_OverflowError, |
826 | 0 | "unbounded read returned more bytes " |
827 | 0 | "than a Python bytes object can hold"); |
828 | 0 | PyBytesWriter_Discard(writer); |
829 | 0 | return NULL; |
830 | 0 | } |
831 | | |
832 | 0 | if (PyBytesWriter_GetSize(writer) < (Py_ssize_t)bufsize) { |
833 | 0 | if (PyBytesWriter_Resize(writer, bufsize) < 0) |
834 | 0 | return NULL; |
835 | 0 | } |
836 | 0 | } |
837 | | |
838 | 4.15k | n = _Py_read(self->fd, |
839 | 4.15k | (char*)PyBytesWriter_GetData(writer) + bytes_read, |
840 | 4.15k | bufsize - bytes_read); |
841 | | |
842 | 4.15k | if (n == 0) |
843 | 2.07k | break; |
844 | 2.07k | if (n == -1) { |
845 | 0 | if (errno == EAGAIN) { |
846 | 0 | PyErr_Clear(); |
847 | 0 | if (bytes_read > 0) |
848 | 0 | break; |
849 | 0 | PyBytesWriter_Discard(writer); |
850 | 0 | Py_RETURN_NONE; |
851 | 0 | } |
852 | 0 | PyBytesWriter_Discard(writer); |
853 | 0 | return NULL; |
854 | 0 | } |
855 | 2.07k | bytes_read += n; |
856 | 2.07k | } |
857 | | |
858 | 2.07k | return PyBytesWriter_FinishWithSize(writer, bytes_read); |
859 | 2.07k | } |
860 | | |
861 | | /*[clinic input] |
862 | | _io.FileIO.read |
863 | | cls: defining_class |
864 | | size: Py_ssize_t(accept={int, NoneType}) = -1 |
865 | | / |
866 | | |
867 | | Read at most size bytes, returned as bytes. |
868 | | |
869 | | If size is less than 0, read all bytes in the file making multiple |
870 | | read calls. See ``FileIO.readall``. |
871 | | |
872 | | Attempts to make only one system call, retrying only per PEP 475 |
873 | | (EINTR). This means less data may be returned than requested. |
874 | | |
875 | | In non-blocking mode, returns None if no data is available. Return |
876 | | an empty bytes object at EOF. |
877 | | [clinic start generated code]*/ |
878 | | |
879 | | static PyObject * |
880 | | _io_FileIO_read_impl(fileio *self, PyTypeObject *cls, Py_ssize_t size) |
881 | | /*[clinic end generated code: output=bbd749c7c224143e input=c7baa3b440af9337]*/ |
882 | 0 | { |
883 | 0 | if (self->fd < 0) |
884 | 0 | return err_closed(); |
885 | 0 | if (!self->readable) { |
886 | 0 | _PyIO_State *state = get_io_state_by_cls(cls); |
887 | 0 | return err_mode(state, "reading"); |
888 | 0 | } |
889 | | |
890 | 0 | if (size < 0) |
891 | 0 | return _io_FileIO_readall_impl(self, cls); |
892 | | |
893 | 0 | if (size > _PY_READ_MAX) { |
894 | 0 | size = _PY_READ_MAX; |
895 | 0 | } |
896 | |
|
897 | 0 | PyBytesWriter *writer = PyBytesWriter_Create(size); |
898 | 0 | if (writer == NULL) { |
899 | 0 | return NULL; |
900 | 0 | } |
901 | 0 | char *ptr = PyBytesWriter_GetData(writer); |
902 | |
|
903 | 0 | Py_ssize_t n = _Py_read(self->fd, ptr, size); |
904 | 0 | if (n == -1) { |
905 | | // copy errno because PyBytesWriter_Discard() can indirectly modify it |
906 | 0 | int err = errno; |
907 | 0 | PyBytesWriter_Discard(writer); |
908 | 0 | if (err == EAGAIN) { |
909 | 0 | PyErr_Clear(); |
910 | 0 | Py_RETURN_NONE; |
911 | 0 | } |
912 | 0 | return NULL; |
913 | 0 | } |
914 | | |
915 | 0 | return PyBytesWriter_FinishWithSize(writer, n); |
916 | 0 | } |
917 | | |
918 | | /*[clinic input] |
919 | | _io.FileIO.write |
920 | | cls: defining_class |
921 | | b: Py_buffer |
922 | | / |
923 | | |
924 | | Write buffer b to file, return number of bytes written. |
925 | | |
926 | | Only makes one system call, so not all of the data may be written. |
927 | | The number of bytes actually written is returned. In non-blocking |
928 | | mode, returns None if the write would block. |
929 | | [clinic start generated code]*/ |
930 | | |
931 | | static PyObject * |
932 | | _io_FileIO_write_impl(fileio *self, PyTypeObject *cls, Py_buffer *b) |
933 | | /*[clinic end generated code: output=927e25be80f3b77b input=233f1f70f9e8b09e]*/ |
934 | 195k | { |
935 | 195k | Py_ssize_t n; |
936 | 195k | int err; |
937 | | |
938 | 195k | if (self->fd < 0) |
939 | 0 | return err_closed(); |
940 | 195k | if (!self->writable) { |
941 | 0 | _PyIO_State *state = get_io_state_by_cls(cls); |
942 | 0 | return err_mode(state, "writing"); |
943 | 0 | } |
944 | | |
945 | 195k | n = _Py_write(self->fd, b->buf, b->len); |
946 | | /* copy errno because PyBuffer_Release() can indirectly modify it */ |
947 | 195k | err = errno; |
948 | | |
949 | 195k | if (n < 0) { |
950 | 0 | if (err == EAGAIN) { |
951 | 0 | PyErr_Clear(); |
952 | 0 | Py_RETURN_NONE; |
953 | 0 | } |
954 | 0 | return NULL; |
955 | 0 | } |
956 | | |
957 | 195k | return PyLong_FromSsize_t(n); |
958 | 195k | } |
959 | | |
960 | | /* XXX Windows support below is likely incomplete */ |
961 | | |
962 | | /* Cribbed from posix_lseek() */ |
963 | | static PyObject * |
964 | | portable_lseek(fileio *self, PyObject *posobj, int whence, bool suppress_pipe_error) |
965 | 22.3k | { |
966 | 22.3k | Py_off_t pos, res; |
967 | 22.3k | int fd = self->fd; |
968 | | |
969 | 22.3k | #ifdef SEEK_SET |
970 | | /* Turn 0, 1, 2 into SEEK_{SET,CUR,END} */ |
971 | 22.3k | switch (whence) { |
972 | | #if SEEK_SET != 0 |
973 | | case 0: whence = SEEK_SET; break; |
974 | | #endif |
975 | | #if SEEK_CUR != 1 |
976 | | case 1: whence = SEEK_CUR; break; |
977 | | #endif |
978 | | #if SEEK_END != 2 |
979 | | case 2: whence = SEEK_END; break; |
980 | | #endif |
981 | 22.3k | } |
982 | 22.3k | #endif /* SEEK_SET */ |
983 | | |
984 | 22.3k | if (posobj == NULL) { |
985 | 22.3k | pos = 0; |
986 | 22.3k | } |
987 | 0 | else { |
988 | | #if defined(HAVE_LARGEFILE_SUPPORT) |
989 | | pos = PyLong_AsLongLong(posobj); |
990 | | #else |
991 | 0 | pos = PyLong_AsLong(posobj); |
992 | 0 | #endif |
993 | 0 | if (PyErr_Occurred()) |
994 | 0 | return NULL; |
995 | 0 | } |
996 | | |
997 | 22.3k | Py_BEGIN_ALLOW_THREADS |
998 | 22.3k | _Py_BEGIN_SUPPRESS_IPH |
999 | | #ifdef MS_WINDOWS |
1000 | | HANDLE h = (HANDLE)_get_osfhandle(fd); |
1001 | | if (h != INVALID_HANDLE_VALUE && GetFileType(h) == FILE_TYPE_PIPE) { |
1002 | | res = -1; |
1003 | | errno = ESPIPE; |
1004 | | } |
1005 | | else { |
1006 | | res = _lseeki64(fd, pos, whence); |
1007 | | } |
1008 | | #else |
1009 | 22.3k | res = lseek(fd, pos, whence); |
1010 | 22.3k | #endif |
1011 | 22.3k | _Py_END_SUPPRESS_IPH |
1012 | 22.3k | Py_END_ALLOW_THREADS |
1013 | | |
1014 | 22.3k | if (self->seekable < 0) { |
1015 | 22.3k | self->seekable = (res >= 0); |
1016 | 22.3k | } |
1017 | | |
1018 | 22.3k | if (res < 0) { |
1019 | 0 | if (suppress_pipe_error && errno == ESPIPE) { |
1020 | 0 | res = 0; |
1021 | 0 | } else { |
1022 | 0 | return PyErr_SetFromErrno(PyExc_OSError); |
1023 | 0 | } |
1024 | 0 | } |
1025 | | |
1026 | | #if defined(HAVE_LARGEFILE_SUPPORT) |
1027 | | return PyLong_FromLongLong(res); |
1028 | | #else |
1029 | 22.3k | return PyLong_FromLong(res); |
1030 | 22.3k | #endif |
1031 | 22.3k | } |
1032 | | |
1033 | | /*[clinic input] |
1034 | | _io.FileIO.seek |
1035 | | pos: object |
1036 | | whence: int = 0 |
1037 | | / |
1038 | | |
1039 | | Move to new file position and return the file position. |
1040 | | |
1041 | | Argument offset is a byte count. Optional argument whence defaults |
1042 | | to SEEK_SET or 0 (offset from start of file, offset should be >= 0); |
1043 | | other values are SEEK_CUR or 1 (move relative to current position, |
1044 | | positive or negative), and SEEK_END or 2 (move relative to end of |
1045 | | file, usually negative, although many platforms allow seeking beyond |
1046 | | the end of a file). |
1047 | | |
1048 | | Note that not all file objects are seekable. |
1049 | | [clinic start generated code]*/ |
1050 | | |
1051 | | static PyObject * |
1052 | | _io_FileIO_seek_impl(fileio *self, PyObject *pos, int whence) |
1053 | | /*[clinic end generated code: output=c976acdf054e6655 input=f165a1b4f5d494ad]*/ |
1054 | 0 | { |
1055 | 0 | if (self->fd < 0) |
1056 | 0 | return err_closed(); |
1057 | | |
1058 | 0 | return portable_lseek(self, pos, whence, false); |
1059 | 0 | } |
1060 | | |
1061 | | /*[clinic input] |
1062 | | _io.FileIO.tell |
1063 | | |
1064 | | Current file position. |
1065 | | |
1066 | | Can raise OSError for non seekable files. |
1067 | | [clinic start generated code]*/ |
1068 | | |
1069 | | static PyObject * |
1070 | | _io_FileIO_tell_impl(fileio *self) |
1071 | | /*[clinic end generated code: output=ffe2147058809d0b input=807e24ead4cec2f9]*/ |
1072 | 22.3k | { |
1073 | 22.3k | if (self->fd < 0) |
1074 | 0 | return err_closed(); |
1075 | | |
1076 | 22.3k | return portable_lseek(self, NULL, 1, false); |
1077 | 22.3k | } |
1078 | | |
1079 | | #ifdef HAVE_FTRUNCATE |
1080 | | /*[clinic input] |
1081 | | @permit_long_summary |
1082 | | _io.FileIO.truncate |
1083 | | cls: defining_class |
1084 | | size as posobj: object = None |
1085 | | / |
1086 | | |
1087 | | Truncate the file to at most size bytes and return the truncated size. |
1088 | | |
1089 | | Size defaults to the current file position, as returned by tell(). |
1090 | | The current file position is changed to the value of size. |
1091 | | [clinic start generated code]*/ |
1092 | | |
1093 | | static PyObject * |
1094 | | _io_FileIO_truncate_impl(fileio *self, PyTypeObject *cls, PyObject *posobj) |
1095 | | /*[clinic end generated code: output=d936732a49e8d5a2 input=8f22152bcf900ed2]*/ |
1096 | 0 | { |
1097 | 0 | Py_off_t pos; |
1098 | 0 | int ret; |
1099 | 0 | int fd; |
1100 | |
|
1101 | 0 | fd = self->fd; |
1102 | 0 | if (fd < 0) |
1103 | 0 | return err_closed(); |
1104 | 0 | if (!self->writable) { |
1105 | 0 | _PyIO_State *state = get_io_state_by_cls(cls); |
1106 | 0 | return err_mode(state, "writing"); |
1107 | 0 | } |
1108 | | |
1109 | 0 | if (posobj == Py_None) { |
1110 | | /* Get the current position. */ |
1111 | 0 | posobj = portable_lseek(self, NULL, 1, false); |
1112 | 0 | if (posobj == NULL) |
1113 | 0 | return NULL; |
1114 | 0 | } |
1115 | 0 | else { |
1116 | 0 | Py_INCREF(posobj); |
1117 | 0 | } |
1118 | | |
1119 | | #if defined(HAVE_LARGEFILE_SUPPORT) |
1120 | | pos = PyLong_AsLongLong(posobj); |
1121 | | #else |
1122 | 0 | pos = PyLong_AsLong(posobj); |
1123 | 0 | #endif |
1124 | 0 | if (PyErr_Occurred()){ |
1125 | 0 | Py_DECREF(posobj); |
1126 | 0 | return NULL; |
1127 | 0 | } |
1128 | | |
1129 | 0 | Py_BEGIN_ALLOW_THREADS |
1130 | 0 | _Py_BEGIN_SUPPRESS_IPH |
1131 | 0 | errno = 0; |
1132 | | #ifdef MS_WINDOWS |
1133 | | ret = _chsize_s(fd, pos); |
1134 | | #else |
1135 | 0 | ret = ftruncate(fd, pos); |
1136 | 0 | #endif |
1137 | 0 | _Py_END_SUPPRESS_IPH |
1138 | 0 | Py_END_ALLOW_THREADS |
1139 | |
|
1140 | 0 | if (ret != 0) { |
1141 | 0 | PyErr_SetFromErrno(PyExc_OSError); |
1142 | 0 | Py_DECREF(posobj); |
1143 | 0 | return NULL; |
1144 | 0 | } |
1145 | | |
1146 | | /* Since the file was truncated, its size at open is no longer accurate |
1147 | | as an estimate. Clear out the stat result, and rely on dynamic resize |
1148 | | code if a readall is requested. */ |
1149 | 0 | if (self->stat_atopen != NULL) { |
1150 | 0 | PyMem_Free(self->stat_atopen); |
1151 | 0 | self->stat_atopen = NULL; |
1152 | 0 | } |
1153 | |
|
1154 | 0 | return posobj; |
1155 | 0 | } |
1156 | | #endif /* HAVE_FTRUNCATE */ |
1157 | | |
1158 | | static const char * |
1159 | | mode_string(fileio *self) |
1160 | 3 | { |
1161 | 3 | if (self->created) { |
1162 | 0 | if (self->readable) |
1163 | 0 | return "xb+"; |
1164 | 0 | else |
1165 | 0 | return "xb"; |
1166 | 0 | } |
1167 | 3 | if (self->appending) { |
1168 | 0 | if (self->readable) |
1169 | 0 | return "ab+"; |
1170 | 0 | else |
1171 | 0 | return "ab"; |
1172 | 0 | } |
1173 | 3 | else if (self->readable) { |
1174 | 3 | if (self->writable) { |
1175 | 0 | if (self->truncate) { |
1176 | 0 | return "wb+"; |
1177 | 0 | } |
1178 | 0 | else { |
1179 | 0 | return "rb+"; |
1180 | 0 | } |
1181 | 0 | } |
1182 | 3 | else { |
1183 | 3 | return "rb"; |
1184 | 3 | } |
1185 | 3 | } |
1186 | 0 | else |
1187 | 0 | return "wb"; |
1188 | 3 | } |
1189 | | |
1190 | | static PyObject * |
1191 | | fileio_repr(PyObject *op) |
1192 | 0 | { |
1193 | 0 | fileio *self = PyFileIO_CAST(op); |
1194 | 0 | const char *type_name = Py_TYPE(self)->tp_name; |
1195 | |
|
1196 | 0 | if (self->fd < 0) { |
1197 | 0 | return PyUnicode_FromFormat("<%.100s [closed]>", type_name); |
1198 | 0 | } |
1199 | | |
1200 | 0 | PyObject *nameobj; |
1201 | 0 | if (PyObject_GetOptionalAttr((PyObject *) self, &_Py_ID(name), &nameobj) < 0) { |
1202 | 0 | return NULL; |
1203 | 0 | } |
1204 | 0 | PyObject *res; |
1205 | 0 | if (nameobj == NULL) { |
1206 | 0 | res = PyUnicode_FromFormat( |
1207 | 0 | "<%.100s fd=%d mode='%s' closefd=%s>", |
1208 | 0 | type_name, self->fd, mode_string(self), self->closefd ? "True" : "False"); |
1209 | 0 | } |
1210 | 0 | else { |
1211 | 0 | int status = Py_ReprEnter((PyObject *)self); |
1212 | 0 | res = NULL; |
1213 | 0 | if (status == 0) { |
1214 | 0 | res = PyUnicode_FromFormat( |
1215 | 0 | "<%.100s name=%R mode='%s' closefd=%s>", |
1216 | 0 | type_name, nameobj, mode_string(self), self->closefd ? "True" : "False"); |
1217 | 0 | Py_ReprLeave((PyObject *)self); |
1218 | 0 | } |
1219 | 0 | else if (status > 0) { |
1220 | 0 | PyErr_Format(PyExc_RuntimeError, |
1221 | 0 | "reentrant call inside %.100s.__repr__", type_name); |
1222 | 0 | } |
1223 | 0 | Py_DECREF(nameobj); |
1224 | 0 | } |
1225 | 0 | return res; |
1226 | 0 | } |
1227 | | |
1228 | | /*[clinic input] |
1229 | | _io.FileIO.isatty |
1230 | | |
1231 | | True if the file is connected to a TTY device. |
1232 | | [clinic start generated code]*/ |
1233 | | |
1234 | | static PyObject * |
1235 | | _io_FileIO_isatty_impl(fileio *self) |
1236 | | /*[clinic end generated code: output=932c39924e9a8070 input=cd94ca1f5e95e843]*/ |
1237 | 148 | { |
1238 | 148 | long res; |
1239 | | |
1240 | 148 | if (self->fd < 0) |
1241 | 0 | return err_closed(); |
1242 | 148 | Py_BEGIN_ALLOW_THREADS |
1243 | 148 | _Py_BEGIN_SUPPRESS_IPH |
1244 | 148 | res = isatty(self->fd); |
1245 | 148 | _Py_END_SUPPRESS_IPH |
1246 | 148 | Py_END_ALLOW_THREADS |
1247 | 148 | return PyBool_FromLong(res); |
1248 | 148 | } |
1249 | | |
1250 | | /* Checks whether the file is a TTY using an open-only optimization. |
1251 | | |
1252 | | TTYs are always character devices. If the interpreter knows a file is |
1253 | | not a character device when it would call ``isatty``, can skip that |
1254 | | call. Inside ``open()`` there is a fresh stat result that contains that |
1255 | | information. Use the stat result to skip a system call. Outside of that |
1256 | | context TOCTOU issues (the fd could be arbitrarily modified by |
1257 | | surrounding code). */ |
1258 | | /*[clinic input] |
1259 | | _io.FileIO._isatty_open_only |
1260 | | [clinic start generated code]*/ |
1261 | | |
1262 | | static PyObject * |
1263 | | _io_FileIO__isatty_open_only_impl(fileio *self) |
1264 | | /*[clinic end generated code: output=2b4689154d4b8b84 input=228767ff567cdfb6]*/ |
1265 | 22.3k | { |
1266 | 22.3k | if (self->stat_atopen != NULL && !S_ISCHR(self->stat_atopen->st_mode)) { |
1267 | 22.2k | Py_RETURN_FALSE; |
1268 | 22.2k | } |
1269 | 37 | return _io_FileIO_isatty_impl(self); |
1270 | 22.3k | } |
1271 | | |
1272 | | #include "clinic/fileio.c.h" |
1273 | | |
1274 | | static PyMethodDef fileio_methods[] = { |
1275 | | _IO_FILEIO_READ_METHODDEF |
1276 | | _IO_FILEIO_READALL_METHODDEF |
1277 | | _IO_FILEIO_READINTO_METHODDEF |
1278 | | _IO_FILEIO_WRITE_METHODDEF |
1279 | | _IO_FILEIO_SEEK_METHODDEF |
1280 | | _IO_FILEIO_TELL_METHODDEF |
1281 | | _IO_FILEIO_TRUNCATE_METHODDEF |
1282 | | _IO_FILEIO_CLOSE_METHODDEF |
1283 | | _IO_FILEIO_SEEKABLE_METHODDEF |
1284 | | _IO_FILEIO_READABLE_METHODDEF |
1285 | | _IO_FILEIO_WRITABLE_METHODDEF |
1286 | | _IO_FILEIO_FILENO_METHODDEF |
1287 | | _IO_FILEIO_ISATTY_METHODDEF |
1288 | | _IO_FILEIO__ISATTY_OPEN_ONLY_METHODDEF |
1289 | | _IO_FILEIO__DEALLOC_WARN_METHODDEF |
1290 | | {"__getstate__", _PyIOBase_cannot_pickle, METH_NOARGS}, |
1291 | | {NULL, NULL} /* sentinel */ |
1292 | | }; |
1293 | | |
1294 | | /* 'closed' and 'mode' are attributes for backwards compatibility reasons. */ |
1295 | | |
1296 | | /*[clinic input] |
1297 | | @getter |
1298 | | _io.FileIO.closed -> bool |
1299 | | |
1300 | | True if the file is closed. |
1301 | | [clinic start generated code]*/ |
1302 | | |
1303 | | static int |
1304 | | _io_FileIO_closed_get_impl(fileio *self) |
1305 | | /*[clinic end generated code: output=5052fd0688b475f2 input=6024cca6d484d9a2]*/ |
1306 | 66.6k | { |
1307 | 66.6k | return self->fd < 0; |
1308 | 66.6k | } |
1309 | | |
1310 | | /*[clinic input] |
1311 | | @getter |
1312 | | _io.FileIO.closefd -> bool |
1313 | | |
1314 | | True if the file descriptor will be closed by close(). |
1315 | | [clinic start generated code]*/ |
1316 | | |
1317 | | static int |
1318 | | _io_FileIO_closefd_get_impl(fileio *self) |
1319 | | /*[clinic end generated code: output=11963fca763399cc input=ed3d108a6f07ad5c]*/ |
1320 | 0 | { |
1321 | 0 | return self->closefd; |
1322 | 0 | } |
1323 | | |
1324 | | /*[clinic input] |
1325 | | @getter |
1326 | | _io.FileIO.mode |
1327 | | |
1328 | | String giving the file mode. |
1329 | | [clinic start generated code]*/ |
1330 | | |
1331 | | static PyObject * |
1332 | | _io_FileIO_mode_get_impl(fileio *self) |
1333 | | /*[clinic end generated code: output=d5178215493e2e7e input=300a448fc9b2fea4]*/ |
1334 | 3 | { |
1335 | 3 | return PyUnicode_FromString(mode_string(self)); |
1336 | 3 | } |
1337 | | |
1338 | | /*[clinic input] |
1339 | | @getter |
1340 | | _io.FileIO._blksize -> long |
1341 | | |
1342 | | Stat st_blksize if available. |
1343 | | [clinic start generated code]*/ |
1344 | | |
1345 | | static long |
1346 | | _io_FileIO__blksize_get_impl(fileio *self) |
1347 | | /*[clinic end generated code: output=e47eaf8cd6c0079f input=699d87d750798ccb]*/ |
1348 | 22.3k | { |
1349 | 22.3k | #ifdef HAVE_STRUCT_STAT_ST_BLKSIZE |
1350 | 22.3k | if (self->stat_atopen != NULL && self->stat_atopen->st_blksize > 1) { |
1351 | 22.3k | return self->stat_atopen->st_blksize; |
1352 | 22.3k | } |
1353 | 0 | #endif /* HAVE_STRUCT_STAT_ST_BLKSIZE */ |
1354 | 0 | return DEFAULT_BUFFER_SIZE; |
1355 | 22.3k | } |
1356 | | |
1357 | | static PyGetSetDef fileio_getsetlist[] = { |
1358 | | _IO_FILEIO_CLOSED_GETSETDEF |
1359 | | _IO_FILEIO_CLOSEFD_GETSETDEF |
1360 | | _IO_FILEIO_MODE_GETSETDEF |
1361 | | _IO_FILEIO__BLKSIZE_GETSETDEF |
1362 | | {NULL}, |
1363 | | }; |
1364 | | |
1365 | | static PyMemberDef fileio_members[] = { |
1366 | | {"_finalizing", Py_T_BOOL, offsetof(fileio, finalizing), 0}, |
1367 | | {NULL} |
1368 | | }; |
1369 | | |
1370 | | static PyType_Slot fileio_slots[] = { |
1371 | | {Py_tp_dealloc, fileio_dealloc}, |
1372 | | {Py_tp_repr, fileio_repr}, |
1373 | | {Py_tp_doc, (void *)_io_FileIO___init____doc__}, |
1374 | | {Py_tp_traverse, fileio_traverse}, |
1375 | | {Py_tp_clear, fileio_clear}, |
1376 | | {Py_tp_methods, fileio_methods}, |
1377 | | {Py_tp_members, fileio_members}, |
1378 | | {Py_tp_getset, fileio_getsetlist}, |
1379 | | {Py_tp_init, _io_FileIO___init__}, |
1380 | | {Py_tp_new, fileio_new}, |
1381 | | {0, NULL}, |
1382 | | }; |
1383 | | |
1384 | | PyType_Spec _Py_fileio_spec = { |
1385 | | .name = "_io.FileIO", |
1386 | | .basicsize = sizeof(fileio), |
1387 | | .flags = (Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC | |
1388 | | Py_TPFLAGS_IMMUTABLETYPE), |
1389 | | .slots = fileio_slots, |
1390 | | }; |