Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 1 | /* |
| 2 | An implementation of the new I/O lib as defined by PEP 3116 - "New I/O" |
Brett Cannon | efb00c0 | 2012-02-29 18:31:31 -0500 | [diff] [blame] | 3 | |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 4 | Classes defined here: UnsupportedOperation, BlockingIOError. |
| 5 | Functions defined here: open(). |
Brett Cannon | efb00c0 | 2012-02-29 18:31:31 -0500 | [diff] [blame] | 6 | |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 7 | 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 | |
| 26 | PyObject *_PyIO_str_close; |
| 27 | PyObject *_PyIO_str_closed; |
| 28 | PyObject *_PyIO_str_decode; |
| 29 | PyObject *_PyIO_str_encode; |
| 30 | PyObject *_PyIO_str_fileno; |
| 31 | PyObject *_PyIO_str_flush; |
| 32 | PyObject *_PyIO_str_getstate; |
| 33 | PyObject *_PyIO_str_isatty; |
| 34 | PyObject *_PyIO_str_newlines; |
| 35 | PyObject *_PyIO_str_nl; |
| 36 | PyObject *_PyIO_str_read; |
| 37 | PyObject *_PyIO_str_read1; |
| 38 | PyObject *_PyIO_str_readable; |
Victor Stinner | b57f108 | 2011-05-26 00:19:38 +0200 | [diff] [blame] | 39 | PyObject *_PyIO_str_readall; |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 40 | PyObject *_PyIO_str_readinto; |
| 41 | PyObject *_PyIO_str_readline; |
| 42 | PyObject *_PyIO_str_reset; |
| 43 | PyObject *_PyIO_str_seek; |
| 44 | PyObject *_PyIO_str_seekable; |
Antoine Pitrou | e450185 | 2009-05-14 18:55:55 +0000 | [diff] [blame] | 45 | PyObject *_PyIO_str_setstate; |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 46 | PyObject *_PyIO_str_tell; |
| 47 | PyObject *_PyIO_str_truncate; |
| 48 | PyObject *_PyIO_str_writable; |
| 49 | PyObject *_PyIO_str_write; |
| 50 | |
| 51 | PyObject *_PyIO_empty_str; |
| 52 | PyObject *_PyIO_empty_bytes; |
Antoine Pitrou | e450185 | 2009-05-14 18:55:55 +0000 | [diff] [blame] | 53 | PyObject *_PyIO_zero; |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 54 | |
| 55 | |
| 56 | PyDoc_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 Araujo | fab9766 | 2012-02-26 02:14:08 +0100 | [diff] [blame] | 62 | "separation between reading and writing to streams; implementations are\n" |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 63 | "allowed to throw an IOError if they do not support a given operation.\n" |
| 64 | "\n" |
| 65 | "Extending IOBase is RawIOBase which deals simply with the reading and\n" |
Benjamin Peterson | 8f2b665 | 2009-04-05 00:46:27 +0000 | [diff] [blame] | 66 | "writing of raw bytes to a stream. FileIO subclasses RawIOBase to provide\n" |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 67 | "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 Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 94 | * The main open() function |
| 95 | */ |
| 96 | PyDoc_STRVAR(open_doc, |
Georg Brandl | e40ee50 | 2010-07-11 09:33:39 +0000 | [diff] [blame] | 97 | "open(file, mode='r', buffering=-1, encoding=None,\n" |
Ross Lagerwall | 59142db | 2011-10-31 20:34:46 +0200 | [diff] [blame] | 98 | " errors=None, newline=None, closefd=True, opener=None) -> file object\n" |
Georg Brandl | 5e8f6d1 | 2009-12-23 10:30:45 +0000 | [diff] [blame] | 99 | "\n" |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 100 | "Open file and return a stream. Raise IOError upon failure.\n" |
| 101 | "\n" |
| 102 | "file is either a text or byte string giving the name (and the path\n" |
| 103 | "if the file isn't in the current working directory) of the file to\n" |
| 104 | "be opened or an integer file descriptor of the file to be\n" |
| 105 | "wrapped. (If a file descriptor is given, it is closed when the\n" |
| 106 | "returned I/O object is closed, unless closefd is set to False.)\n" |
| 107 | "\n" |
| 108 | "mode is an optional string that specifies the mode in which the file\n" |
| 109 | "is opened. It defaults to 'r' which means open for reading in text\n" |
| 110 | "mode. Other common values are 'w' for writing (truncating the file if\n" |
Charles-François Natali | dc3044c | 2012-01-09 22:40:02 +0100 | [diff] [blame] | 111 | "it already exists), 'x' for creating and writing to a new file, and\n" |
| 112 | "'a' for appending (which on some Unix systems, means that all writes\n" |
| 113 | "append to the end of the file regardless of the current seek position).\n" |
| 114 | "In text mode, if encoding is not specified the encoding used is platform\n" |
| 115 | "dependent. (For reading and writing raw bytes use binary mode and leave\n" |
| 116 | "encoding unspecified.) The available modes are:\n" |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 117 | "\n" |
| 118 | "========= ===============================================================\n" |
| 119 | "Character Meaning\n" |
| 120 | "--------- ---------------------------------------------------------------\n" |
| 121 | "'r' open for reading (default)\n" |
| 122 | "'w' open for writing, truncating the file first\n" |
Charles-François Natali | dc3044c | 2012-01-09 22:40:02 +0100 | [diff] [blame] | 123 | "'x' create a new file and open it for writing\n" |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 124 | "'a' open for writing, appending to the end of the file if it exists\n" |
| 125 | "'b' binary mode\n" |
| 126 | "'t' text mode (default)\n" |
| 127 | "'+' open a disk file for updating (reading and writing)\n" |
| 128 | "'U' universal newline mode (for backwards compatibility; unneeded\n" |
| 129 | " for new code)\n" |
| 130 | "========= ===============================================================\n" |
| 131 | "\n" |
| 132 | "The default mode is 'rt' (open for reading text). For binary random\n" |
| 133 | "access, the mode 'w+b' opens and truncates the file to 0 bytes, while\n" |
Charles-François Natali | dc3044c | 2012-01-09 22:40:02 +0100 | [diff] [blame] | 134 | "'r+b' opens the file without truncation. The 'x' mode implies 'w' and\n" |
| 135 | "raises an `FileExistsError` if the file already exists.\n" |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 136 | "\n" |
| 137 | "Python distinguishes between files opened in binary and text modes,\n" |
| 138 | "even when the underlying operating system doesn't. Files opened in\n" |
| 139 | "binary mode (appending 'b' to the mode argument) return contents as\n" |
| 140 | "bytes objects without any decoding. In text mode (the default, or when\n" |
| 141 | "'t' is appended to the mode argument), the contents of the file are\n" |
| 142 | "returned as strings, the bytes having been first decoded using a\n" |
| 143 | "platform-dependent encoding or using the specified encoding if given.\n" |
| 144 | "\n" |
Antoine Pitrou | d5587bc | 2009-12-19 21:08:31 +0000 | [diff] [blame] | 145 | "buffering is an optional integer used to set the buffering policy.\n" |
| 146 | "Pass 0 to switch buffering off (only allowed in binary mode), 1 to select\n" |
| 147 | "line buffering (only usable in text mode), and an integer > 1 to indicate\n" |
| 148 | "the size of a fixed-size chunk buffer. When no buffering argument is\n" |
| 149 | "given, the default buffering policy works as follows:\n" |
| 150 | "\n" |
| 151 | "* Binary files are buffered in fixed-size chunks; the size of the buffer\n" |
| 152 | " is chosen using a heuristic trying to determine the underlying device's\n" |
| 153 | " \"block size\" and falling back on `io.DEFAULT_BUFFER_SIZE`.\n" |
| 154 | " On many systems, the buffer will typically be 4096 or 8192 bytes long.\n" |
| 155 | "\n" |
| 156 | "* \"Interactive\" text files (files for which isatty() returns True)\n" |
| 157 | " use line buffering. Other text files use the policy described above\n" |
| 158 | " for binary files.\n" |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 159 | "\n" |
| 160 | "encoding is the name of the encoding used to decode or encode the\n" |
| 161 | "file. This should only be used in text mode. The default encoding is\n" |
| 162 | "platform dependent, but any encoding supported by Python can be\n" |
| 163 | "passed. See the codecs module for the list of supported encodings.\n" |
| 164 | "\n" |
| 165 | "errors is an optional string that specifies how encoding errors are to\n" |
| 166 | "be handled---this argument should not be used in binary mode. Pass\n" |
| 167 | "'strict' to raise a ValueError exception if there is an encoding error\n" |
| 168 | "(the default of None has the same effect), or pass 'ignore' to ignore\n" |
| 169 | "errors. (Note that ignoring encoding errors can lead to data loss.)\n" |
| 170 | "See the documentation for codecs.register for a list of the permitted\n" |
| 171 | "encoding error strings.\n" |
| 172 | "\n" |
| 173 | "newline controls how universal newlines works (it only applies to text\n" |
| 174 | "mode). It can be None, '', '\\n', '\\r', and '\\r\\n'. It works as\n" |
| 175 | "follows:\n" |
| 176 | "\n" |
| 177 | "* On input, if newline is None, universal newlines mode is\n" |
| 178 | " enabled. Lines in the input can end in '\\n', '\\r', or '\\r\\n', and\n" |
| 179 | " these are translated into '\\n' before being returned to the\n" |
| 180 | " caller. If it is '', universal newline mode is enabled, but line\n" |
| 181 | " endings are returned to the caller untranslated. If it has any of\n" |
| 182 | " the other legal values, input lines are only terminated by the given\n" |
| 183 | " string, and the line ending is returned to the caller untranslated.\n" |
| 184 | "\n" |
| 185 | "* On output, if newline is None, any '\\n' characters written are\n" |
| 186 | " translated to the system default line separator, os.linesep. If\n" |
| 187 | " newline is '', no translation takes place. If newline is any of the\n" |
| 188 | " other legal values, any '\\n' characters written are translated to\n" |
| 189 | " the given string.\n" |
| 190 | "\n" |
| 191 | "If closefd is False, the underlying file descriptor will be kept open\n" |
| 192 | "when the file is closed. This does not work when a file name is given\n" |
| 193 | "and must be True in that case.\n" |
| 194 | "\n" |
Ross Lagerwall | 59142db | 2011-10-31 20:34:46 +0200 | [diff] [blame] | 195 | "A custom opener can be used by passing a callable as *opener*. The\n" |
| 196 | "underlying file descriptor for the file object is then obtained by\n" |
| 197 | "calling *opener* with (*file*, *flags*). *opener* must return an open\n" |
| 198 | "file descriptor (passing os.open as *opener* results in functionality\n" |
| 199 | "similar to passing None).\n" |
| 200 | "\n" |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 201 | "open() returns a file object whose type depends on the mode, and\n" |
| 202 | "through which the standard file operations such as reading and writing\n" |
| 203 | "are performed. When open() is used to open a file in a text mode ('w',\n" |
| 204 | "'r', 'wt', 'rt', etc.), it returns a TextIOWrapper. When used to open\n" |
| 205 | "a file in a binary mode, the returned class varies: in read binary\n" |
| 206 | "mode, it returns a BufferedReader; in write binary and append binary\n" |
| 207 | "modes, it returns a BufferedWriter, and in read/write mode, it returns\n" |
| 208 | "a BufferedRandom.\n" |
| 209 | "\n" |
| 210 | "It is also possible to use a string or bytearray as a file for both\n" |
| 211 | "reading and writing. For strings StringIO can be used like a file\n" |
| 212 | "opened in a text mode, and for bytes a BytesIO can be used like a file\n" |
| 213 | "opened in a binary mode.\n" |
| 214 | ); |
| 215 | |
| 216 | static PyObject * |
| 217 | io_open(PyObject *self, PyObject *args, PyObject *kwds) |
| 218 | { |
| 219 | char *kwlist[] = {"file", "mode", "buffering", |
| 220 | "encoding", "errors", "newline", |
Ross Lagerwall | 59142db | 2011-10-31 20:34:46 +0200 | [diff] [blame] | 221 | "closefd", "opener", NULL}; |
| 222 | PyObject *file, *opener = Py_None; |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 223 | char *mode = "r"; |
| 224 | int buffering = -1, closefd = 1; |
| 225 | char *encoding = NULL, *errors = NULL, *newline = NULL; |
| 226 | unsigned i; |
| 227 | |
Charles-François Natali | dc3044c | 2012-01-09 22:40:02 +0100 | [diff] [blame] | 228 | int creating = 0, reading = 0, writing = 0, appending = 0, updating = 0; |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 229 | int text = 0, binary = 0, universal = 0; |
| 230 | |
| 231 | char rawmode[5], *m; |
| 232 | int line_buffering, isatty; |
| 233 | |
| 234 | PyObject *raw, *modeobj = NULL, *buffer = NULL, *wrapper = NULL; |
| 235 | |
Martin v. Löwis | bd928fe | 2011-10-14 10:20:37 +0200 | [diff] [blame] | 236 | _Py_IDENTIFIER(isatty); |
| 237 | _Py_IDENTIFIER(fileno); |
Martin v. Löwis | 767046a | 2011-10-14 15:35:36 +0200 | [diff] [blame] | 238 | _Py_IDENTIFIER(mode); |
Martin v. Löwis | afe55bb | 2011-10-09 10:38:36 +0200 | [diff] [blame] | 239 | |
Ross Lagerwall | 59142db | 2011-10-31 20:34:46 +0200 | [diff] [blame] | 240 | if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|sizzziO:open", kwlist, |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 241 | &file, &mode, &buffering, |
| 242 | &encoding, &errors, &newline, |
Ross Lagerwall | 59142db | 2011-10-31 20:34:46 +0200 | [diff] [blame] | 243 | &closefd, &opener)) { |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 244 | return NULL; |
| 245 | } |
| 246 | |
| 247 | if (!PyUnicode_Check(file) && |
| 248 | !PyBytes_Check(file) && |
| 249 | !PyNumber_Check(file)) { |
| 250 | PyErr_Format(PyExc_TypeError, "invalid file: %R", file); |
| 251 | return NULL; |
| 252 | } |
| 253 | |
| 254 | /* Decode mode */ |
| 255 | for (i = 0; i < strlen(mode); i++) { |
| 256 | char c = mode[i]; |
| 257 | |
| 258 | switch (c) { |
Charles-François Natali | dc3044c | 2012-01-09 22:40:02 +0100 | [diff] [blame] | 259 | case 'x': |
| 260 | creating = 1; |
| 261 | break; |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 262 | case 'r': |
| 263 | reading = 1; |
| 264 | break; |
| 265 | case 'w': |
| 266 | writing = 1; |
| 267 | break; |
| 268 | case 'a': |
| 269 | appending = 1; |
| 270 | break; |
| 271 | case '+': |
| 272 | updating = 1; |
| 273 | break; |
| 274 | case 't': |
| 275 | text = 1; |
| 276 | break; |
| 277 | case 'b': |
| 278 | binary = 1; |
| 279 | break; |
| 280 | case 'U': |
| 281 | universal = 1; |
| 282 | reading = 1; |
| 283 | break; |
| 284 | default: |
| 285 | goto invalid_mode; |
| 286 | } |
| 287 | |
| 288 | /* c must not be duplicated */ |
| 289 | if (strchr(mode+i+1, c)) { |
| 290 | invalid_mode: |
| 291 | PyErr_Format(PyExc_ValueError, "invalid mode: '%s'", mode); |
| 292 | return NULL; |
| 293 | } |
| 294 | |
| 295 | } |
| 296 | |
| 297 | m = rawmode; |
Charles-François Natali | dc3044c | 2012-01-09 22:40:02 +0100 | [diff] [blame] | 298 | if (creating) *(m++) = 'x'; |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 299 | if (reading) *(m++) = 'r'; |
| 300 | if (writing) *(m++) = 'w'; |
| 301 | if (appending) *(m++) = 'a'; |
| 302 | if (updating) *(m++) = '+'; |
| 303 | *m = '\0'; |
| 304 | |
| 305 | /* Parameters validation */ |
| 306 | if (universal) { |
| 307 | if (writing || appending) { |
| 308 | PyErr_SetString(PyExc_ValueError, |
| 309 | "can't use U and writing mode at once"); |
| 310 | return NULL; |
| 311 | } |
| 312 | reading = 1; |
| 313 | } |
| 314 | |
| 315 | if (text && binary) { |
| 316 | PyErr_SetString(PyExc_ValueError, |
| 317 | "can't have text and binary mode at once"); |
| 318 | return NULL; |
| 319 | } |
| 320 | |
Charles-François Natali | dc3044c | 2012-01-09 22:40:02 +0100 | [diff] [blame] | 321 | if (creating + reading + writing + appending > 1) { |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 322 | PyErr_SetString(PyExc_ValueError, |
Charles-François Natali | dc3044c | 2012-01-09 22:40:02 +0100 | [diff] [blame] | 323 | "must have exactly one of create/read/write/append mode"); |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 324 | return NULL; |
| 325 | } |
| 326 | |
| 327 | if (binary && encoding != NULL) { |
| 328 | PyErr_SetString(PyExc_ValueError, |
| 329 | "binary mode doesn't take an encoding argument"); |
| 330 | return NULL; |
| 331 | } |
| 332 | |
| 333 | if (binary && errors != NULL) { |
| 334 | PyErr_SetString(PyExc_ValueError, |
| 335 | "binary mode doesn't take an errors argument"); |
| 336 | return NULL; |
| 337 | } |
| 338 | |
| 339 | if (binary && newline != NULL) { |
| 340 | PyErr_SetString(PyExc_ValueError, |
| 341 | "binary mode doesn't take a newline argument"); |
| 342 | return NULL; |
| 343 | } |
| 344 | |
| 345 | /* Create the Raw file stream */ |
| 346 | raw = PyObject_CallFunction((PyObject *)&PyFileIO_Type, |
Ross Lagerwall | 59142db | 2011-10-31 20:34:46 +0200 | [diff] [blame] | 347 | "OsiO", file, rawmode, closefd, opener); |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 348 | if (raw == NULL) |
| 349 | return NULL; |
| 350 | |
| 351 | modeobj = PyUnicode_FromString(mode); |
| 352 | if (modeobj == NULL) |
| 353 | goto error; |
| 354 | |
| 355 | /* buffering */ |
| 356 | { |
Martin v. Löwis | afe55bb | 2011-10-09 10:38:36 +0200 | [diff] [blame] | 357 | PyObject *res = _PyObject_CallMethodId(raw, &PyId_isatty, NULL); |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 358 | if (res == NULL) |
| 359 | goto error; |
| 360 | isatty = PyLong_AsLong(res); |
| 361 | Py_DECREF(res); |
| 362 | if (isatty == -1 && PyErr_Occurred()) |
| 363 | goto error; |
| 364 | } |
| 365 | |
| 366 | if (buffering == 1 || (buffering < 0 && isatty)) { |
| 367 | buffering = -1; |
| 368 | line_buffering = 1; |
| 369 | } |
| 370 | else |
| 371 | line_buffering = 0; |
| 372 | |
| 373 | if (buffering < 0) { |
| 374 | buffering = DEFAULT_BUFFER_SIZE; |
| 375 | #ifdef HAVE_STRUCT_STAT_ST_BLKSIZE |
| 376 | { |
| 377 | struct stat st; |
| 378 | long fileno; |
Martin v. Löwis | afe55bb | 2011-10-09 10:38:36 +0200 | [diff] [blame] | 379 | PyObject *res = _PyObject_CallMethodId(raw, &PyId_fileno, NULL); |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 380 | if (res == NULL) |
| 381 | goto error; |
| 382 | |
| 383 | fileno = PyLong_AsLong(res); |
| 384 | Py_DECREF(res); |
| 385 | if (fileno == -1 && PyErr_Occurred()) |
| 386 | goto error; |
| 387 | |
Antoine Pitrou | ea5d17d | 2010-10-27 19:45:43 +0000 | [diff] [blame] | 388 | if (fstat(fileno, &st) >= 0 && st.st_blksize > 1) |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 389 | buffering = st.st_blksize; |
| 390 | } |
| 391 | #endif |
| 392 | } |
| 393 | if (buffering < 0) { |
| 394 | PyErr_SetString(PyExc_ValueError, |
| 395 | "invalid buffering size"); |
| 396 | goto error; |
| 397 | } |
| 398 | |
| 399 | /* if not buffering, returns the raw file object */ |
| 400 | if (buffering == 0) { |
| 401 | if (!binary) { |
| 402 | PyErr_SetString(PyExc_ValueError, |
| 403 | "can't have unbuffered text I/O"); |
| 404 | goto error; |
| 405 | } |
| 406 | |
| 407 | Py_DECREF(modeobj); |
| 408 | return raw; |
| 409 | } |
| 410 | |
| 411 | /* wraps into a buffered file */ |
| 412 | { |
| 413 | PyObject *Buffered_class; |
| 414 | |
| 415 | if (updating) |
| 416 | Buffered_class = (PyObject *)&PyBufferedRandom_Type; |
Charles-François Natali | dc3044c | 2012-01-09 22:40:02 +0100 | [diff] [blame] | 417 | else if (creating || writing || appending) |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 418 | Buffered_class = (PyObject *)&PyBufferedWriter_Type; |
| 419 | else if (reading) |
| 420 | Buffered_class = (PyObject *)&PyBufferedReader_Type; |
| 421 | else { |
| 422 | PyErr_Format(PyExc_ValueError, |
| 423 | "unknown mode: '%s'", mode); |
| 424 | goto error; |
| 425 | } |
| 426 | |
| 427 | buffer = PyObject_CallFunction(Buffered_class, "Oi", raw, buffering); |
| 428 | } |
| 429 | Py_CLEAR(raw); |
| 430 | if (buffer == NULL) |
| 431 | goto error; |
| 432 | |
| 433 | |
| 434 | /* if binary, returns the buffered file */ |
| 435 | if (binary) { |
| 436 | Py_DECREF(modeobj); |
| 437 | return buffer; |
| 438 | } |
| 439 | |
| 440 | /* wraps into a TextIOWrapper */ |
| 441 | wrapper = PyObject_CallFunction((PyObject *)&PyTextIOWrapper_Type, |
| 442 | "Osssi", |
| 443 | buffer, |
| 444 | encoding, errors, newline, |
| 445 | line_buffering); |
| 446 | Py_CLEAR(buffer); |
| 447 | if (wrapper == NULL) |
| 448 | goto error; |
| 449 | |
Martin v. Löwis | 767046a | 2011-10-14 15:35:36 +0200 | [diff] [blame] | 450 | if (_PyObject_SetAttrId(wrapper, &PyId_mode, modeobj) < 0) |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 451 | goto error; |
| 452 | Py_DECREF(modeobj); |
| 453 | return wrapper; |
| 454 | |
| 455 | error: |
| 456 | Py_XDECREF(raw); |
| 457 | Py_XDECREF(modeobj); |
| 458 | Py_XDECREF(buffer); |
| 459 | Py_XDECREF(wrapper); |
| 460 | return NULL; |
| 461 | } |
| 462 | |
| 463 | /* |
| 464 | * Private helpers for the io module. |
| 465 | */ |
| 466 | |
| 467 | Py_off_t |
| 468 | PyNumber_AsOff_t(PyObject *item, PyObject *err) |
| 469 | { |
| 470 | Py_off_t result; |
| 471 | PyObject *runerr; |
| 472 | PyObject *value = PyNumber_Index(item); |
| 473 | if (value == NULL) |
| 474 | return -1; |
| 475 | |
| 476 | /* We're done if PyLong_AsSsize_t() returns without error. */ |
| 477 | result = PyLong_AsOff_t(value); |
| 478 | if (result != -1 || !(runerr = PyErr_Occurred())) |
| 479 | goto finish; |
| 480 | |
| 481 | /* Error handling code -- only manage OverflowError differently */ |
| 482 | if (!PyErr_GivenExceptionMatches(runerr, PyExc_OverflowError)) |
| 483 | goto finish; |
| 484 | |
| 485 | PyErr_Clear(); |
| 486 | /* If no error-handling desired then the default clipping |
| 487 | is sufficient. |
| 488 | */ |
| 489 | if (!err) { |
| 490 | assert(PyLong_Check(value)); |
| 491 | /* Whether or not it is less than or equal to |
| 492 | zero is determined by the sign of ob_size |
| 493 | */ |
| 494 | if (_PyLong_Sign(value) < 0) |
| 495 | result = PY_OFF_T_MIN; |
| 496 | else |
| 497 | result = PY_OFF_T_MAX; |
| 498 | } |
| 499 | else { |
| 500 | /* Otherwise replace the error with caller's error object. */ |
| 501 | PyErr_Format(err, |
| 502 | "cannot fit '%.200s' into an offset-sized integer", |
| 503 | item->ob_type->tp_name); |
| 504 | } |
| 505 | |
| 506 | finish: |
| 507 | Py_DECREF(value); |
| 508 | return result; |
| 509 | } |
| 510 | |
Benjamin Peterson | bf5ff76 | 2009-12-13 19:25:34 +0000 | [diff] [blame] | 511 | |
| 512 | /* Basically the "n" format code with the ability to turn None into -1. */ |
Brett Cannon | efb00c0 | 2012-02-29 18:31:31 -0500 | [diff] [blame] | 513 | int |
Benjamin Peterson | bf5ff76 | 2009-12-13 19:25:34 +0000 | [diff] [blame] | 514 | _PyIO_ConvertSsize_t(PyObject *obj, void *result) { |
| 515 | Py_ssize_t limit; |
| 516 | if (obj == Py_None) { |
| 517 | limit = -1; |
| 518 | } |
| 519 | else if (PyNumber_Check(obj)) { |
| 520 | limit = PyNumber_AsSsize_t(obj, PyExc_OverflowError); |
| 521 | if (limit == -1 && PyErr_Occurred()) |
| 522 | return 0; |
| 523 | } |
| 524 | else { |
| 525 | PyErr_Format(PyExc_TypeError, |
| 526 | "integer argument expected, got '%.200s'", |
| 527 | Py_TYPE(obj)->tp_name); |
| 528 | return 0; |
| 529 | } |
| 530 | *((Py_ssize_t *)result) = limit; |
| 531 | return 1; |
| 532 | } |
| 533 | |
| 534 | |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 535 | static int |
| 536 | iomodule_traverse(PyObject *mod, visitproc visit, void *arg) { |
| 537 | _PyIO_State *state = IO_MOD_STATE(mod); |
| 538 | if (!state->initialized) |
| 539 | return 0; |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 540 | if (state->locale_module != NULL) { |
| 541 | Py_VISIT(state->locale_module); |
| 542 | } |
| 543 | Py_VISIT(state->unsupported_operation); |
| 544 | return 0; |
| 545 | } |
| 546 | |
Benjamin Peterson | bf5ff76 | 2009-12-13 19:25:34 +0000 | [diff] [blame] | 547 | |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 548 | static int |
| 549 | iomodule_clear(PyObject *mod) { |
| 550 | _PyIO_State *state = IO_MOD_STATE(mod); |
| 551 | if (!state->initialized) |
| 552 | return 0; |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 553 | if (state->locale_module != NULL) |
| 554 | Py_CLEAR(state->locale_module); |
| 555 | Py_CLEAR(state->unsupported_operation); |
| 556 | return 0; |
| 557 | } |
| 558 | |
| 559 | static void |
| 560 | iomodule_free(PyObject *mod) { |
| 561 | iomodule_clear(mod); |
| 562 | } |
| 563 | |
Benjamin Peterson | bf5ff76 | 2009-12-13 19:25:34 +0000 | [diff] [blame] | 564 | |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 565 | /* |
| 566 | * Module definition |
| 567 | */ |
| 568 | |
| 569 | static PyMethodDef module_methods[] = { |
| 570 | {"open", (PyCFunction)io_open, METH_VARARGS|METH_KEYWORDS, open_doc}, |
| 571 | {NULL, NULL} |
| 572 | }; |
| 573 | |
| 574 | struct PyModuleDef _PyIO_Module = { |
| 575 | PyModuleDef_HEAD_INIT, |
| 576 | "io", |
| 577 | module_doc, |
| 578 | sizeof(_PyIO_State), |
| 579 | module_methods, |
| 580 | NULL, |
| 581 | iomodule_traverse, |
| 582 | iomodule_clear, |
| 583 | (freefunc)iomodule_free, |
| 584 | }; |
| 585 | |
| 586 | PyMODINIT_FUNC |
| 587 | PyInit__io(void) |
| 588 | { |
| 589 | PyObject *m = PyModule_Create(&_PyIO_Module); |
| 590 | _PyIO_State *state = NULL; |
| 591 | if (m == NULL) |
| 592 | return NULL; |
| 593 | state = IO_MOD_STATE(m); |
| 594 | state->initialized = 0; |
| 595 | |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 596 | #define ADD_TYPE(type, name) \ |
| 597 | if (PyType_Ready(type) < 0) \ |
| 598 | goto fail; \ |
| 599 | Py_INCREF(type); \ |
| 600 | if (PyModule_AddObject(m, name, (PyObject *)type) < 0) { \ |
| 601 | Py_DECREF(type); \ |
| 602 | goto fail; \ |
| 603 | } |
| 604 | |
| 605 | /* DEFAULT_BUFFER_SIZE */ |
| 606 | if (PyModule_AddIntMacro(m, DEFAULT_BUFFER_SIZE) < 0) |
| 607 | goto fail; |
| 608 | |
| 609 | /* UnsupportedOperation inherits from ValueError and IOError */ |
| 610 | state->unsupported_operation = PyObject_CallFunction( |
| 611 | (PyObject *)&PyType_Type, "s(OO){}", |
| 612 | "UnsupportedOperation", PyExc_ValueError, PyExc_IOError); |
| 613 | if (state->unsupported_operation == NULL) |
| 614 | goto fail; |
| 615 | Py_INCREF(state->unsupported_operation); |
| 616 | if (PyModule_AddObject(m, "UnsupportedOperation", |
| 617 | state->unsupported_operation) < 0) |
| 618 | goto fail; |
| 619 | |
Antoine Pitrou | 6b4883d | 2011-10-12 02:54:14 +0200 | [diff] [blame] | 620 | /* BlockingIOError, for compatibility */ |
| 621 | Py_INCREF(PyExc_BlockingIOError); |
| 622 | if (PyModule_AddObject(m, "BlockingIOError", |
| 623 | (PyObject *) PyExc_BlockingIOError) < 0) |
| 624 | goto fail; |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 625 | |
| 626 | /* Concrete base types of the IO ABCs. |
| 627 | (the ABCs themselves are declared through inheritance in io.py) |
| 628 | */ |
| 629 | ADD_TYPE(&PyIOBase_Type, "_IOBase"); |
| 630 | ADD_TYPE(&PyRawIOBase_Type, "_RawIOBase"); |
| 631 | ADD_TYPE(&PyBufferedIOBase_Type, "_BufferedIOBase"); |
| 632 | ADD_TYPE(&PyTextIOBase_Type, "_TextIOBase"); |
| 633 | |
| 634 | /* Implementation of concrete IO objects. */ |
| 635 | /* FileIO */ |
| 636 | PyFileIO_Type.tp_base = &PyRawIOBase_Type; |
| 637 | ADD_TYPE(&PyFileIO_Type, "FileIO"); |
| 638 | |
| 639 | /* BytesIO */ |
| 640 | PyBytesIO_Type.tp_base = &PyBufferedIOBase_Type; |
| 641 | ADD_TYPE(&PyBytesIO_Type, "BytesIO"); |
Antoine Pitrou | 972ee13 | 2010-09-06 18:48:21 +0000 | [diff] [blame] | 642 | if (PyType_Ready(&_PyBytesIOBuffer_Type) < 0) |
| 643 | goto fail; |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 644 | |
| 645 | /* StringIO */ |
| 646 | PyStringIO_Type.tp_base = &PyTextIOBase_Type; |
| 647 | ADD_TYPE(&PyStringIO_Type, "StringIO"); |
| 648 | |
| 649 | /* BufferedReader */ |
| 650 | PyBufferedReader_Type.tp_base = &PyBufferedIOBase_Type; |
| 651 | ADD_TYPE(&PyBufferedReader_Type, "BufferedReader"); |
| 652 | |
| 653 | /* BufferedWriter */ |
| 654 | PyBufferedWriter_Type.tp_base = &PyBufferedIOBase_Type; |
| 655 | ADD_TYPE(&PyBufferedWriter_Type, "BufferedWriter"); |
| 656 | |
| 657 | /* BufferedRWPair */ |
| 658 | PyBufferedRWPair_Type.tp_base = &PyBufferedIOBase_Type; |
| 659 | ADD_TYPE(&PyBufferedRWPair_Type, "BufferedRWPair"); |
| 660 | |
| 661 | /* BufferedRandom */ |
| 662 | PyBufferedRandom_Type.tp_base = &PyBufferedIOBase_Type; |
| 663 | ADD_TYPE(&PyBufferedRandom_Type, "BufferedRandom"); |
| 664 | |
| 665 | /* TextIOWrapper */ |
| 666 | PyTextIOWrapper_Type.tp_base = &PyTextIOBase_Type; |
| 667 | ADD_TYPE(&PyTextIOWrapper_Type, "TextIOWrapper"); |
| 668 | |
| 669 | /* IncrementalNewlineDecoder */ |
| 670 | ADD_TYPE(&PyIncrementalNewlineDecoder_Type, "IncrementalNewlineDecoder"); |
| 671 | |
| 672 | /* Interned strings */ |
Antoine Pitrou | fc1b6f0 | 2012-01-18 16:13:56 +0100 | [diff] [blame] | 673 | #define ADD_INTERNED(name) \ |
| 674 | if (!_PyIO_str_ ## name && \ |
| 675 | !(_PyIO_str_ ## name = PyUnicode_InternFromString(# name))) \ |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 676 | goto fail; |
Antoine Pitrou | fc1b6f0 | 2012-01-18 16:13:56 +0100 | [diff] [blame] | 677 | |
| 678 | ADD_INTERNED(close) |
| 679 | ADD_INTERNED(closed) |
| 680 | ADD_INTERNED(decode) |
| 681 | ADD_INTERNED(encode) |
| 682 | ADD_INTERNED(fileno) |
| 683 | ADD_INTERNED(flush) |
| 684 | ADD_INTERNED(getstate) |
| 685 | ADD_INTERNED(isatty) |
| 686 | ADD_INTERNED(newlines) |
| 687 | ADD_INTERNED(read) |
| 688 | ADD_INTERNED(read1) |
| 689 | ADD_INTERNED(readable) |
Antoine Pitrou | bb5b92d | 2012-01-18 16:19:19 +0100 | [diff] [blame] | 690 | ADD_INTERNED(readall) |
Antoine Pitrou | fc1b6f0 | 2012-01-18 16:13:56 +0100 | [diff] [blame] | 691 | ADD_INTERNED(readinto) |
| 692 | ADD_INTERNED(readline) |
| 693 | ADD_INTERNED(reset) |
| 694 | ADD_INTERNED(seek) |
| 695 | ADD_INTERNED(seekable) |
| 696 | ADD_INTERNED(setstate) |
| 697 | ADD_INTERNED(tell) |
| 698 | ADD_INTERNED(truncate) |
| 699 | ADD_INTERNED(write) |
| 700 | ADD_INTERNED(writable) |
| 701 | |
| 702 | if (!_PyIO_str_nl && |
| 703 | !(_PyIO_str_nl = PyUnicode_InternFromString("\n"))) |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 704 | goto fail; |
Antoine Pitrou | fc1b6f0 | 2012-01-18 16:13:56 +0100 | [diff] [blame] | 705 | |
| 706 | if (!_PyIO_empty_str && |
| 707 | !(_PyIO_empty_str = PyUnicode_FromStringAndSize(NULL, 0))) |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 708 | goto fail; |
Antoine Pitrou | fc1b6f0 | 2012-01-18 16:13:56 +0100 | [diff] [blame] | 709 | if (!_PyIO_empty_bytes && |
| 710 | !(_PyIO_empty_bytes = PyBytes_FromStringAndSize(NULL, 0))) |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 711 | goto fail; |
Antoine Pitrou | fc1b6f0 | 2012-01-18 16:13:56 +0100 | [diff] [blame] | 712 | if (!_PyIO_zero && |
| 713 | !(_PyIO_zero = PyLong_FromLong(0L))) |
Antoine Pitrou | e450185 | 2009-05-14 18:55:55 +0000 | [diff] [blame] | 714 | goto fail; |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 715 | |
| 716 | state->initialized = 1; |
| 717 | |
| 718 | return m; |
| 719 | |
| 720 | fail: |
Benjamin Peterson | 4fa88fa | 2009-03-04 00:14:51 +0000 | [diff] [blame] | 721 | Py_XDECREF(state->unsupported_operation); |
| 722 | Py_DECREF(m); |
| 723 | return NULL; |
| 724 | } |