blob: ea727f25c5e54c53462c9ae6f8d21aac399e58cf [file] [log] [blame]
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001/*
2 An implementation of the new I/O lib as defined by PEP 3116 - "New I/O"
Brett Cannonefb00c02012-02-29 18:31:31 -05003
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00004 Classes defined here: UnsupportedOperation, BlockingIOError.
5 Functions defined here: open().
Brett Cannonefb00c02012-02-29 18:31:31 -05006
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00007 Mostly written by Amaury Forgeot d'Arc
8*/
9
10#define PY_SSIZE_T_CLEAN
11#include "Python.h"
12#include "structmember.h"
13#include "_iomodule.h"
14
15#ifdef HAVE_SYS_TYPES_H
16#include <sys/types.h>
17#endif /* HAVE_SYS_TYPES_H */
18
19#ifdef HAVE_SYS_STAT_H
20#include <sys/stat.h>
21#endif /* HAVE_SYS_STAT_H */
22
23
24/* Various interned strings */
25
26PyObject *_PyIO_str_close;
27PyObject *_PyIO_str_closed;
28PyObject *_PyIO_str_decode;
29PyObject *_PyIO_str_encode;
30PyObject *_PyIO_str_fileno;
31PyObject *_PyIO_str_flush;
32PyObject *_PyIO_str_getstate;
33PyObject *_PyIO_str_isatty;
34PyObject *_PyIO_str_newlines;
35PyObject *_PyIO_str_nl;
36PyObject *_PyIO_str_read;
37PyObject *_PyIO_str_read1;
38PyObject *_PyIO_str_readable;
Victor Stinnerb57f1082011-05-26 00:19:38 +020039PyObject *_PyIO_str_readall;
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +000040PyObject *_PyIO_str_readinto;
41PyObject *_PyIO_str_readline;
42PyObject *_PyIO_str_reset;
43PyObject *_PyIO_str_seek;
44PyObject *_PyIO_str_seekable;
Antoine Pitroue4501852009-05-14 18:55:55 +000045PyObject *_PyIO_str_setstate;
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +000046PyObject *_PyIO_str_tell;
47PyObject *_PyIO_str_truncate;
48PyObject *_PyIO_str_writable;
49PyObject *_PyIO_str_write;
50
51PyObject *_PyIO_empty_str;
52PyObject *_PyIO_empty_bytes;
Antoine Pitroue4501852009-05-14 18:55:55 +000053PyObject *_PyIO_zero;
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +000054
55
56PyDoc_STRVAR(module_doc,
57"The io module provides the Python interfaces to stream handling. The\n"
58"builtin open function is defined in this module.\n"
59"\n"
60"At the top of the I/O hierarchy is the abstract base class IOBase. It\n"
61"defines the basic interface to a stream. Note, however, that there is no\n"
Éric Araujofab97662012-02-26 02:14:08 +010062"separation between reading and writing to streams; implementations are\n"
Andrew Svetlov737fb892012-12-18 21:14:22 +020063"allowed to raise an IOError if they do not support a given operation.\n"
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +000064"\n"
65"Extending IOBase is RawIOBase which deals simply with the reading and\n"
Benjamin Peterson8f2b6652009-04-05 00:46:27 +000066"writing of raw bytes to a stream. FileIO subclasses RawIOBase to provide\n"
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +000067"an interface to OS files.\n"
68"\n"
69"BufferedIOBase deals with buffering on a raw byte stream (RawIOBase). Its\n"
70"subclasses, BufferedWriter, BufferedReader, and BufferedRWPair buffer\n"
71"streams that are readable, writable, and both respectively.\n"
72"BufferedRandom provides a buffered interface to random access\n"
73"streams. BytesIO is a simple stream of in-memory bytes.\n"
74"\n"
75"Another IOBase subclass, TextIOBase, deals with the encoding and decoding\n"
76"of streams into text. TextIOWrapper, which extends it, is a buffered text\n"
77"interface to a buffered raw stream (`BufferedIOBase`). Finally, StringIO\n"
78"is a in-memory stream for text.\n"
79"\n"
80"Argument names are not part of the specification, and only the arguments\n"
81"of open() are intended to be used as keyword arguments.\n"
82"\n"
83"data:\n"
84"\n"
85"DEFAULT_BUFFER_SIZE\n"
86"\n"
87" An int containing the default buffer size used by the module's buffered\n"
88" I/O classes. open() uses the file's blksize (as obtained by os.stat) if\n"
89" possible.\n"
90 );
91
92
93/*
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +000094 * The main open() function
95 */
Serhiy Storchakaf24131f2015-04-16 11:19:43 +030096/*[clinic input]
97module _io
98
99_io.open
100 file: object
101 mode: str = "r"
102 buffering: int = -1
103 encoding: str(nullable=True) = NULL
104 errors: str(nullable=True) = NULL
105 newline: str(nullable=True) = NULL
106 closefd: int(c_default="1") = True
107 opener: object = None
108
109Open file and return a stream. Raise IOError upon failure.
110
111file is either a text or byte string giving the name (and the path
112if the file isn't in the current working directory) of the file to
113be opened or an integer file descriptor of the file to be
114wrapped. (If a file descriptor is given, it is closed when the
115returned I/O object is closed, unless closefd is set to False.)
116
117mode is an optional string that specifies the mode in which the file
118is opened. It defaults to 'r' which means open for reading in text
119mode. Other common values are 'w' for writing (truncating the file if
120it already exists), 'x' for creating and writing to a new file, and
121'a' for appending (which on some Unix systems, means that all writes
122append to the end of the file regardless of the current seek position).
123In text mode, if encoding is not specified the encoding used is platform
124dependent: locale.getpreferredencoding(False) is called to get the
125current locale encoding. (For reading and writing raw bytes use binary
126mode and leave encoding unspecified.) The available modes are:
127
128========= ===============================================================
129Character Meaning
130--------- ---------------------------------------------------------------
131'r' open for reading (default)
132'w' open for writing, truncating the file first
133'x' create a new file and open it for writing
134'a' open for writing, appending to the end of the file if it exists
135'b' binary mode
136't' text mode (default)
137'+' open a disk file for updating (reading and writing)
138'U' universal newline mode (deprecated)
139========= ===============================================================
140
141The default mode is 'rt' (open for reading text). For binary random
142access, the mode 'w+b' opens and truncates the file to 0 bytes, while
143'r+b' opens the file without truncation. The 'x' mode implies 'w' and
144raises an `FileExistsError` if the file already exists.
145
146Python distinguishes between files opened in binary and text modes,
147even when the underlying operating system doesn't. Files opened in
148binary mode (appending 'b' to the mode argument) return contents as
149bytes objects without any decoding. In text mode (the default, or when
150't' is appended to the mode argument), the contents of the file are
151returned as strings, the bytes having been first decoded using a
152platform-dependent encoding or using the specified encoding if given.
153
154'U' mode is deprecated and will raise an exception in future versions
155of Python. It has no effect in Python 3. Use newline to control
156universal newlines mode.
157
158buffering is an optional integer used to set the buffering policy.
159Pass 0 to switch buffering off (only allowed in binary mode), 1 to select
160line buffering (only usable in text mode), and an integer > 1 to indicate
161the size of a fixed-size chunk buffer. When no buffering argument is
162given, the default buffering policy works as follows:
163
164* Binary files are buffered in fixed-size chunks; the size of the buffer
165 is chosen using a heuristic trying to determine the underlying device's
166 "block size" and falling back on `io.DEFAULT_BUFFER_SIZE`.
167 On many systems, the buffer will typically be 4096 or 8192 bytes long.
168
169* "Interactive" text files (files for which isatty() returns True)
170 use line buffering. Other text files use the policy described above
171 for binary files.
172
173encoding is the name of the encoding used to decode or encode the
174file. This should only be used in text mode. The default encoding is
175platform dependent, but any encoding supported by Python can be
176passed. See the codecs module for the list of supported encodings.
177
178errors is an optional string that specifies how encoding errors are to
179be handled---this argument should not be used in binary mode. Pass
180'strict' to raise a ValueError exception if there is an encoding error
181(the default of None has the same effect), or pass 'ignore' to ignore
182errors. (Note that ignoring encoding errors can lead to data loss.)
183See the documentation for codecs.register or run 'help(codecs.Codec)'
184for a list of the permitted encoding error strings.
185
186newline controls how universal newlines works (it only applies to text
187mode). It can be None, '', '\n', '\r', and '\r\n'. It works as
188follows:
189
190* On input, if newline is None, universal newlines mode is
191 enabled. Lines in the input can end in '\n', '\r', or '\r\n', and
192 these are translated into '\n' before being returned to the
193 caller. If it is '', universal newline mode is enabled, but line
194 endings are returned to the caller untranslated. If it has any of
195 the other legal values, input lines are only terminated by the given
196 string, and the line ending is returned to the caller untranslated.
197
198* On output, if newline is None, any '\n' characters written are
199 translated to the system default line separator, os.linesep. If
200 newline is '' or '\n', no translation takes place. If newline is any
201 of the other legal values, any '\n' characters written are translated
202 to the given string.
203
204If closefd is False, the underlying file descriptor will be kept open
205when the file is closed. This does not work when a file name is given
206and must be True in that case.
207
208A custom opener can be used by passing a callable as *opener*. The
209underlying file descriptor for the file object is then obtained by
210calling *opener* with (*file*, *flags*). *opener* must return an open
211file descriptor (passing os.open as *opener* results in functionality
212similar to passing None).
213
214open() returns a file object whose type depends on the mode, and
215through which the standard file operations such as reading and writing
216are performed. When open() is used to open a file in a text mode ('w',
217'r', 'wt', 'rt', etc.), it returns a TextIOWrapper. When used to open
218a file in a binary mode, the returned class varies: in read binary
219mode, it returns a BufferedReader; in write binary and append binary
220modes, it returns a BufferedWriter, and in read/write mode, it returns
221a BufferedRandom.
222
223It is also possible to use a string or bytearray as a file for both
224reading and writing. For strings StringIO can be used like a file
225opened in a text mode, and for bytes a BytesIO can be used like a file
226opened in a binary mode.
227[clinic start generated code]*/
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000228
229static PyObject *
Serhiy Storchakaf24131f2015-04-16 11:19:43 +0300230_io_open_impl(PyModuleDef *module, PyObject *file, const char *mode,
231 int buffering, const char *encoding, const char *errors,
232 const char *newline, int closefd, PyObject *opener)
233/*[clinic end generated code: output=7615d0d746eb14d2 input=0541ce15691a82f2]*/
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000234{
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000235 unsigned i;
236
Charles-François Natalidc3044c2012-01-09 22:40:02 +0100237 int creating = 0, reading = 0, writing = 0, appending = 0, updating = 0;
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000238 int text = 0, binary = 0, universal = 0;
239
Christian Heimes89ff3c72012-09-10 03:50:48 +0200240 char rawmode[6], *m;
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000241 int line_buffering, isatty;
242
Serhiy Storchakaf10063e2014-06-09 13:32:34 +0300243 PyObject *raw, *modeobj = NULL, *buffer, *wrapper, *result = NULL;
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000244
Antoine Pitroude687222014-06-29 20:07:28 -0400245 _Py_IDENTIFIER(_blksize);
Martin v. Löwisbd928fe2011-10-14 10:20:37 +0200246 _Py_IDENTIFIER(isatty);
Martin v. Löwis767046a2011-10-14 15:35:36 +0200247 _Py_IDENTIFIER(mode);
Serhiy Storchakaf10063e2014-06-09 13:32:34 +0300248 _Py_IDENTIFIER(close);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200249
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000250 if (!PyUnicode_Check(file) &&
251 !PyBytes_Check(file) &&
252 !PyNumber_Check(file)) {
253 PyErr_Format(PyExc_TypeError, "invalid file: %R", file);
254 return NULL;
255 }
256
257 /* Decode mode */
258 for (i = 0; i < strlen(mode); i++) {
259 char c = mode[i];
260
261 switch (c) {
Charles-François Natalidc3044c2012-01-09 22:40:02 +0100262 case 'x':
263 creating = 1;
264 break;
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000265 case 'r':
266 reading = 1;
267 break;
268 case 'w':
269 writing = 1;
270 break;
271 case 'a':
272 appending = 1;
273 break;
274 case '+':
275 updating = 1;
276 break;
277 case 't':
278 text = 1;
279 break;
280 case 'b':
281 binary = 1;
282 break;
283 case 'U':
284 universal = 1;
285 reading = 1;
286 break;
287 default:
288 goto invalid_mode;
289 }
290
291 /* c must not be duplicated */
292 if (strchr(mode+i+1, c)) {
293 invalid_mode:
294 PyErr_Format(PyExc_ValueError, "invalid mode: '%s'", mode);
295 return NULL;
296 }
297
298 }
299
300 m = rawmode;
Charles-François Natalidc3044c2012-01-09 22:40:02 +0100301 if (creating) *(m++) = 'x';
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000302 if (reading) *(m++) = 'r';
303 if (writing) *(m++) = 'w';
304 if (appending) *(m++) = 'a';
305 if (updating) *(m++) = '+';
306 *m = '\0';
307
308 /* Parameters validation */
309 if (universal) {
310 if (writing || appending) {
311 PyErr_SetString(PyExc_ValueError,
312 "can't use U and writing mode at once");
313 return NULL;
314 }
Serhiy Storchaka6787a382013-11-23 22:12:06 +0200315 if (PyErr_WarnEx(PyExc_DeprecationWarning,
316 "'U' mode is deprecated", 1) < 0)
317 return NULL;
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000318 reading = 1;
319 }
320
321 if (text && binary) {
322 PyErr_SetString(PyExc_ValueError,
323 "can't have text and binary mode at once");
324 return NULL;
325 }
326
Charles-François Natalidc3044c2012-01-09 22:40:02 +0100327 if (creating + reading + writing + appending > 1) {
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000328 PyErr_SetString(PyExc_ValueError,
Charles-François Natalidc3044c2012-01-09 22:40:02 +0100329 "must have exactly one of create/read/write/append mode");
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000330 return NULL;
331 }
332
333 if (binary && encoding != NULL) {
334 PyErr_SetString(PyExc_ValueError,
335 "binary mode doesn't take an encoding argument");
336 return NULL;
337 }
338
339 if (binary && errors != NULL) {
340 PyErr_SetString(PyExc_ValueError,
341 "binary mode doesn't take an errors argument");
342 return NULL;
343 }
344
345 if (binary && newline != NULL) {
346 PyErr_SetString(PyExc_ValueError,
347 "binary mode doesn't take a newline argument");
348 return NULL;
349 }
350
351 /* Create the Raw file stream */
352 raw = PyObject_CallFunction((PyObject *)&PyFileIO_Type,
Ross Lagerwall59142db2011-10-31 20:34:46 +0200353 "OsiO", file, rawmode, closefd, opener);
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000354 if (raw == NULL)
355 return NULL;
Serhiy Storchakaf10063e2014-06-09 13:32:34 +0300356 result = raw;
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000357
358 modeobj = PyUnicode_FromString(mode);
359 if (modeobj == NULL)
360 goto error;
361
362 /* buffering */
363 {
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200364 PyObject *res = _PyObject_CallMethodId(raw, &PyId_isatty, NULL);
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000365 if (res == NULL)
366 goto error;
367 isatty = PyLong_AsLong(res);
368 Py_DECREF(res);
369 if (isatty == -1 && PyErr_Occurred())
370 goto error;
371 }
372
373 if (buffering == 1 || (buffering < 0 && isatty)) {
374 buffering = -1;
375 line_buffering = 1;
376 }
377 else
378 line_buffering = 0;
379
380 if (buffering < 0) {
Antoine Pitroude687222014-06-29 20:07:28 -0400381 PyObject *blksize_obj;
382 blksize_obj = _PyObject_GetAttrId(raw, &PyId__blksize);
383 if (blksize_obj == NULL)
384 goto error;
385 buffering = PyLong_AsLong(blksize_obj);
386 Py_DECREF(blksize_obj);
387 if (buffering == -1 && PyErr_Occurred())
388 goto error;
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000389 }
390 if (buffering < 0) {
391 PyErr_SetString(PyExc_ValueError,
392 "invalid buffering size");
393 goto error;
394 }
395
396 /* if not buffering, returns the raw file object */
397 if (buffering == 0) {
398 if (!binary) {
399 PyErr_SetString(PyExc_ValueError,
400 "can't have unbuffered text I/O");
401 goto error;
402 }
403
404 Py_DECREF(modeobj);
Serhiy Storchakaf10063e2014-06-09 13:32:34 +0300405 return result;
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000406 }
407
408 /* wraps into a buffered file */
409 {
410 PyObject *Buffered_class;
411
412 if (updating)
413 Buffered_class = (PyObject *)&PyBufferedRandom_Type;
Charles-François Natalidc3044c2012-01-09 22:40:02 +0100414 else if (creating || writing || appending)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000415 Buffered_class = (PyObject *)&PyBufferedWriter_Type;
416 else if (reading)
417 Buffered_class = (PyObject *)&PyBufferedReader_Type;
418 else {
419 PyErr_Format(PyExc_ValueError,
420 "unknown mode: '%s'", mode);
421 goto error;
422 }
423
424 buffer = PyObject_CallFunction(Buffered_class, "Oi", raw, buffering);
425 }
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000426 if (buffer == NULL)
427 goto error;
Serhiy Storchakaf10063e2014-06-09 13:32:34 +0300428 result = buffer;
429 Py_DECREF(raw);
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000430
431
432 /* if binary, returns the buffered file */
433 if (binary) {
434 Py_DECREF(modeobj);
Serhiy Storchakaf10063e2014-06-09 13:32:34 +0300435 return result;
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000436 }
437
438 /* wraps into a TextIOWrapper */
439 wrapper = PyObject_CallFunction((PyObject *)&PyTextIOWrapper_Type,
440 "Osssi",
441 buffer,
442 encoding, errors, newline,
443 line_buffering);
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000444 if (wrapper == NULL)
445 goto error;
Serhiy Storchakaf10063e2014-06-09 13:32:34 +0300446 result = wrapper;
447 Py_DECREF(buffer);
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000448
Martin v. Löwis767046a2011-10-14 15:35:36 +0200449 if (_PyObject_SetAttrId(wrapper, &PyId_mode, modeobj) < 0)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000450 goto error;
451 Py_DECREF(modeobj);
Serhiy Storchakaf10063e2014-06-09 13:32:34 +0300452 return result;
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000453
454 error:
Serhiy Storchakaf10063e2014-06-09 13:32:34 +0300455 if (result != NULL) {
Benjamin Peterson4f654fb2014-07-04 17:00:25 -0700456 PyObject *exc, *val, *tb, *close_result;
Serhiy Storchakaf10063e2014-06-09 13:32:34 +0300457 PyErr_Fetch(&exc, &val, &tb);
Benjamin Peterson4f654fb2014-07-04 17:00:25 -0700458 close_result = _PyObject_CallMethodId(result, &PyId_close, NULL);
Serhiy Storchakae2bd2a72014-10-08 22:31:52 +0300459 _PyErr_ChainExceptions(exc, val, tb);
460 Py_XDECREF(close_result);
Serhiy Storchakaf10063e2014-06-09 13:32:34 +0300461 Py_DECREF(result);
462 }
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000463 Py_XDECREF(modeobj);
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000464 return NULL;
465}
466
467/*
468 * Private helpers for the io module.
469 */
470
471Py_off_t
472PyNumber_AsOff_t(PyObject *item, PyObject *err)
473{
474 Py_off_t result;
475 PyObject *runerr;
476 PyObject *value = PyNumber_Index(item);
477 if (value == NULL)
478 return -1;
479
480 /* We're done if PyLong_AsSsize_t() returns without error. */
481 result = PyLong_AsOff_t(value);
482 if (result != -1 || !(runerr = PyErr_Occurred()))
483 goto finish;
484
485 /* Error handling code -- only manage OverflowError differently */
486 if (!PyErr_GivenExceptionMatches(runerr, PyExc_OverflowError))
487 goto finish;
488
489 PyErr_Clear();
490 /* If no error-handling desired then the default clipping
491 is sufficient.
492 */
493 if (!err) {
494 assert(PyLong_Check(value));
495 /* Whether or not it is less than or equal to
496 zero is determined by the sign of ob_size
497 */
498 if (_PyLong_Sign(value) < 0)
499 result = PY_OFF_T_MIN;
500 else
501 result = PY_OFF_T_MAX;
502 }
503 else {
504 /* Otherwise replace the error with caller's error object. */
505 PyErr_Format(err,
506 "cannot fit '%.200s' into an offset-sized integer",
507 item->ob_type->tp_name);
508 }
509
510 finish:
511 Py_DECREF(value);
512 return result;
513}
514
Benjamin Petersonbf5ff762009-12-13 19:25:34 +0000515
516/* Basically the "n" format code with the ability to turn None into -1. */
Brett Cannonefb00c02012-02-29 18:31:31 -0500517int
Benjamin Petersonbf5ff762009-12-13 19:25:34 +0000518_PyIO_ConvertSsize_t(PyObject *obj, void *result) {
519 Py_ssize_t limit;
520 if (obj == Py_None) {
521 limit = -1;
522 }
523 else if (PyNumber_Check(obj)) {
524 limit = PyNumber_AsSsize_t(obj, PyExc_OverflowError);
525 if (limit == -1 && PyErr_Occurred())
526 return 0;
527 }
528 else {
529 PyErr_Format(PyExc_TypeError,
530 "integer argument expected, got '%.200s'",
531 Py_TYPE(obj)->tp_name);
532 return 0;
533 }
534 *((Py_ssize_t *)result) = limit;
535 return 1;
536}
537
538
Antoine Pitrou712cb732013-12-21 15:51:54 +0100539_PyIO_State *
540_PyIO_get_module_state(void)
541{
542 PyObject *mod = PyState_FindModule(&_PyIO_Module);
543 _PyIO_State *state;
544 if (mod == NULL || (state = IO_MOD_STATE(mod)) == NULL) {
545 PyErr_SetString(PyExc_RuntimeError,
546 "could not find io module state "
547 "(interpreter shutdown?)");
548 return NULL;
549 }
550 return state;
551}
552
Antoine Pitrou932ff832013-08-01 21:04:50 +0200553PyObject *
554_PyIO_get_locale_module(_PyIO_State *state)
555{
556 PyObject *mod;
557 if (state->locale_module != NULL) {
558 assert(PyWeakref_CheckRef(state->locale_module));
559 mod = PyWeakref_GET_OBJECT(state->locale_module);
560 if (mod != Py_None) {
561 Py_INCREF(mod);
562 return mod;
563 }
564 Py_CLEAR(state->locale_module);
565 }
Antoine Pitroufd4722c2013-10-12 00:13:50 +0200566 mod = PyImport_ImportModule("_bootlocale");
Antoine Pitrou932ff832013-08-01 21:04:50 +0200567 if (mod == NULL)
568 return NULL;
569 state->locale_module = PyWeakref_NewRef(mod, NULL);
570 if (state->locale_module == NULL) {
571 Py_DECREF(mod);
572 return NULL;
573 }
574 return mod;
575}
576
577
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000578static int
579iomodule_traverse(PyObject *mod, visitproc visit, void *arg) {
580 _PyIO_State *state = IO_MOD_STATE(mod);
581 if (!state->initialized)
582 return 0;
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000583 if (state->locale_module != NULL) {
584 Py_VISIT(state->locale_module);
585 }
586 Py_VISIT(state->unsupported_operation);
587 return 0;
588}
589
Benjamin Petersonbf5ff762009-12-13 19:25:34 +0000590
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000591static int
592iomodule_clear(PyObject *mod) {
593 _PyIO_State *state = IO_MOD_STATE(mod);
594 if (!state->initialized)
595 return 0;
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000596 if (state->locale_module != NULL)
597 Py_CLEAR(state->locale_module);
598 Py_CLEAR(state->unsupported_operation);
599 return 0;
600}
601
602static void
603iomodule_free(PyObject *mod) {
604 iomodule_clear(mod);
605}
606
Benjamin Petersonbf5ff762009-12-13 19:25:34 +0000607
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000608/*
609 * Module definition
610 */
611
Serhiy Storchakaf24131f2015-04-16 11:19:43 +0300612#include "clinic/_iomodule.c.h"
613
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000614static PyMethodDef module_methods[] = {
Serhiy Storchakaf24131f2015-04-16 11:19:43 +0300615 _IO_OPEN_METHODDEF
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000616 {NULL, NULL}
617};
618
619struct PyModuleDef _PyIO_Module = {
620 PyModuleDef_HEAD_INIT,
621 "io",
622 module_doc,
623 sizeof(_PyIO_State),
624 module_methods,
625 NULL,
626 iomodule_traverse,
627 iomodule_clear,
628 (freefunc)iomodule_free,
629};
630
631PyMODINIT_FUNC
632PyInit__io(void)
633{
634 PyObject *m = PyModule_Create(&_PyIO_Module);
635 _PyIO_State *state = NULL;
636 if (m == NULL)
637 return NULL;
638 state = IO_MOD_STATE(m);
639 state->initialized = 0;
640
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000641#define ADD_TYPE(type, name) \
642 if (PyType_Ready(type) < 0) \
643 goto fail; \
644 Py_INCREF(type); \
645 if (PyModule_AddObject(m, name, (PyObject *)type) < 0) { \
646 Py_DECREF(type); \
647 goto fail; \
648 }
649
650 /* DEFAULT_BUFFER_SIZE */
651 if (PyModule_AddIntMacro(m, DEFAULT_BUFFER_SIZE) < 0)
652 goto fail;
653
654 /* UnsupportedOperation inherits from ValueError and IOError */
655 state->unsupported_operation = PyObject_CallFunction(
656 (PyObject *)&PyType_Type, "s(OO){}",
657 "UnsupportedOperation", PyExc_ValueError, PyExc_IOError);
658 if (state->unsupported_operation == NULL)
659 goto fail;
660 Py_INCREF(state->unsupported_operation);
661 if (PyModule_AddObject(m, "UnsupportedOperation",
662 state->unsupported_operation) < 0)
663 goto fail;
664
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200665 /* BlockingIOError, for compatibility */
666 Py_INCREF(PyExc_BlockingIOError);
667 if (PyModule_AddObject(m, "BlockingIOError",
668 (PyObject *) PyExc_BlockingIOError) < 0)
669 goto fail;
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000670
671 /* Concrete base types of the IO ABCs.
672 (the ABCs themselves are declared through inheritance in io.py)
673 */
674 ADD_TYPE(&PyIOBase_Type, "_IOBase");
675 ADD_TYPE(&PyRawIOBase_Type, "_RawIOBase");
676 ADD_TYPE(&PyBufferedIOBase_Type, "_BufferedIOBase");
677 ADD_TYPE(&PyTextIOBase_Type, "_TextIOBase");
678
679 /* Implementation of concrete IO objects. */
680 /* FileIO */
681 PyFileIO_Type.tp_base = &PyRawIOBase_Type;
682 ADD_TYPE(&PyFileIO_Type, "FileIO");
683
684 /* BytesIO */
685 PyBytesIO_Type.tp_base = &PyBufferedIOBase_Type;
686 ADD_TYPE(&PyBytesIO_Type, "BytesIO");
Antoine Pitrou972ee132010-09-06 18:48:21 +0000687 if (PyType_Ready(&_PyBytesIOBuffer_Type) < 0)
688 goto fail;
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000689
690 /* StringIO */
691 PyStringIO_Type.tp_base = &PyTextIOBase_Type;
692 ADD_TYPE(&PyStringIO_Type, "StringIO");
693
694 /* BufferedReader */
695 PyBufferedReader_Type.tp_base = &PyBufferedIOBase_Type;
696 ADD_TYPE(&PyBufferedReader_Type, "BufferedReader");
697
698 /* BufferedWriter */
699 PyBufferedWriter_Type.tp_base = &PyBufferedIOBase_Type;
700 ADD_TYPE(&PyBufferedWriter_Type, "BufferedWriter");
701
702 /* BufferedRWPair */
703 PyBufferedRWPair_Type.tp_base = &PyBufferedIOBase_Type;
704 ADD_TYPE(&PyBufferedRWPair_Type, "BufferedRWPair");
705
706 /* BufferedRandom */
707 PyBufferedRandom_Type.tp_base = &PyBufferedIOBase_Type;
708 ADD_TYPE(&PyBufferedRandom_Type, "BufferedRandom");
709
710 /* TextIOWrapper */
711 PyTextIOWrapper_Type.tp_base = &PyTextIOBase_Type;
712 ADD_TYPE(&PyTextIOWrapper_Type, "TextIOWrapper");
713
714 /* IncrementalNewlineDecoder */
715 ADD_TYPE(&PyIncrementalNewlineDecoder_Type, "IncrementalNewlineDecoder");
716
717 /* Interned strings */
Antoine Pitroufc1b6f02012-01-18 16:13:56 +0100718#define ADD_INTERNED(name) \
719 if (!_PyIO_str_ ## name && \
720 !(_PyIO_str_ ## name = PyUnicode_InternFromString(# name))) \
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000721 goto fail;
Antoine Pitroufc1b6f02012-01-18 16:13:56 +0100722
723 ADD_INTERNED(close)
724 ADD_INTERNED(closed)
725 ADD_INTERNED(decode)
726 ADD_INTERNED(encode)
727 ADD_INTERNED(fileno)
728 ADD_INTERNED(flush)
729 ADD_INTERNED(getstate)
730 ADD_INTERNED(isatty)
731 ADD_INTERNED(newlines)
732 ADD_INTERNED(read)
733 ADD_INTERNED(read1)
734 ADD_INTERNED(readable)
Antoine Pitroubb5b92d2012-01-18 16:19:19 +0100735 ADD_INTERNED(readall)
Antoine Pitroufc1b6f02012-01-18 16:13:56 +0100736 ADD_INTERNED(readinto)
737 ADD_INTERNED(readline)
738 ADD_INTERNED(reset)
739 ADD_INTERNED(seek)
740 ADD_INTERNED(seekable)
741 ADD_INTERNED(setstate)
742 ADD_INTERNED(tell)
743 ADD_INTERNED(truncate)
744 ADD_INTERNED(write)
745 ADD_INTERNED(writable)
746
747 if (!_PyIO_str_nl &&
748 !(_PyIO_str_nl = PyUnicode_InternFromString("\n")))
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000749 goto fail;
Antoine Pitroufc1b6f02012-01-18 16:13:56 +0100750
751 if (!_PyIO_empty_str &&
752 !(_PyIO_empty_str = PyUnicode_FromStringAndSize(NULL, 0)))
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000753 goto fail;
Antoine Pitroufc1b6f02012-01-18 16:13:56 +0100754 if (!_PyIO_empty_bytes &&
755 !(_PyIO_empty_bytes = PyBytes_FromStringAndSize(NULL, 0)))
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000756 goto fail;
Antoine Pitroufc1b6f02012-01-18 16:13:56 +0100757 if (!_PyIO_zero &&
758 !(_PyIO_zero = PyLong_FromLong(0L)))
Antoine Pitroue4501852009-05-14 18:55:55 +0000759 goto fail;
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000760
761 state->initialized = 1;
762
763 return m;
764
765 fail:
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000766 Py_XDECREF(state->unsupported_operation);
767 Py_DECREF(m);
768 return NULL;
769}