blob: 2f63c374d1e2421bdba45fcd1d5c67d4a8012631 [file] [log] [blame]
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001/* File object implementation */
2
Martin v. Löwis18e16552006-02-15 17:27:45 +00003#define PY_SSIZE_T_CLEAN
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004#include "Python.h"
Guido van Rossumb6775db1994-08-01 11:34:53 +00005#include "structmember.h"
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00006
Martin v. Löwis0e8bd7e2006-06-10 12:23:46 +00007#ifdef HAVE_SYS_TYPES_H
Guido van Rossum41498431999-01-07 22:09:51 +00008#include <sys/types.h>
Martin v. Löwis0e8bd7e2006-06-10 12:23:46 +00009#endif /* HAVE_SYS_TYPES_H */
Guido van Rossum41498431999-01-07 22:09:51 +000010
Martin v. Löwis6238d2b2002-06-30 15:26:10 +000011#ifdef MS_WINDOWS
Guido van Rossumb8199141997-05-06 15:23:24 +000012#define fileno _fileno
Tim Petersfb05db22002-03-11 00:24:00 +000013/* can simulate truncate with Win32 API functions; see file_truncate */
Guido van Rossumb8199141997-05-06 15:23:24 +000014#define HAVE_FTRUNCATE
Tim Peters7a1f9172002-07-14 22:14:19 +000015#define WIN32_LEAN_AND_MEAN
Tim Petersfb05db22002-03-11 00:24:00 +000016#include <windows.h>
Guido van Rossumb8199141997-05-06 15:23:24 +000017#endif
18
Andrew MacIntyrec4874392002-02-26 11:36:35 +000019#if defined(PYOS_OS2) && defined(PYCC_GCC)
20#include <io.h>
21#endif
22
Gregory P. Smithdd96db62008-06-09 04:58:54 +000023#define BUF(v) PyString_AS_STRING((PyStringObject *)v)
Guido van Rossumce5ba841991-03-06 13:06:18 +000024
Andrew M. Kuchling00b6a5c2010-02-22 23:10:52 +000025#ifdef HAVE_ERRNO_H
Guido van Rossumf1dc5661993-07-05 10:31:29 +000026#include <errno.h>
Guido van Rossumff7e83d1999-08-27 20:39:37 +000027#endif
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000028
Jack Jansen7b8c7542002-04-14 20:12:41 +000029#ifdef HAVE_GETC_UNLOCKED
30#define GETC(f) getc_unlocked(f)
31#define FLOCKFILE(f) flockfile(f)
32#define FUNLOCKFILE(f) funlockfile(f)
33#else
34#define GETC(f) getc(f)
35#define FLOCKFILE(f)
36#define FUNLOCKFILE(f)
37#endif
38
Jack Jansen7b8c7542002-04-14 20:12:41 +000039/* Bits in f_newlinetypes */
Antoine Pitrouc83ea132010-05-09 14:46:46 +000040#define NEWLINE_UNKNOWN 0 /* No newline seen, yet */
41#define NEWLINE_CR 1 /* \r newline seen */
42#define NEWLINE_LF 2 /* \n newline seen */
43#define NEWLINE_CRLF 4 /* \r\n newline seen */
Trent Mickf29f47b2000-08-11 19:02:59 +000044
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +000045/*
46 * These macros release the GIL while preventing the f_close() function being
47 * called in the interval between them. For that purpose, a running total of
48 * the number of currently running unlocked code sections is kept in
49 * the unlocked_count field of the PyFileObject. The close() method raises
50 * an IOError if that field is non-zero. See issue #815646, #595601.
51 */
52
53#define FILE_BEGIN_ALLOW_THREADS(fobj) \
54{ \
Antoine Pitrouc83ea132010-05-09 14:46:46 +000055 fobj->unlocked_count++; \
56 Py_BEGIN_ALLOW_THREADS
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +000057
58#define FILE_END_ALLOW_THREADS(fobj) \
Antoine Pitrouc83ea132010-05-09 14:46:46 +000059 Py_END_ALLOW_THREADS \
60 fobj->unlocked_count--; \
61 assert(fobj->unlocked_count >= 0); \
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +000062}
63
64#define FILE_ABORT_ALLOW_THREADS(fobj) \
Antoine Pitrouc83ea132010-05-09 14:46:46 +000065 Py_BLOCK_THREADS \
66 fobj->unlocked_count--; \
67 assert(fobj->unlocked_count >= 0);
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +000068
Anthony Baxterac6bd462006-04-13 02:06:09 +000069#ifdef __cplusplus
70extern "C" {
71#endif
72
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000073FILE *
Fred Drakefd99de62000-07-09 05:02:18 +000074PyFile_AsFile(PyObject *f)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000075{
Antoine Pitrouc83ea132010-05-09 14:46:46 +000076 if (f == NULL || !PyFile_Check(f))
77 return NULL;
78 else
79 return ((PyFileObject *)f)->f_fp;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000080}
81
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +000082void PyFile_IncUseCount(PyFileObject *fobj)
83{
Antoine Pitrouc83ea132010-05-09 14:46:46 +000084 fobj->unlocked_count++;
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +000085}
86
87void PyFile_DecUseCount(PyFileObject *fobj)
88{
Antoine Pitrouc83ea132010-05-09 14:46:46 +000089 fobj->unlocked_count--;
90 assert(fobj->unlocked_count >= 0);
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +000091}
92
Guido van Rossumc0b618a1997-05-02 03:12:38 +000093PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +000094PyFile_Name(PyObject *f)
Guido van Rossumdb3165e1993-10-18 17:06:59 +000095{
Antoine Pitrouc83ea132010-05-09 14:46:46 +000096 if (f == NULL || !PyFile_Check(f))
97 return NULL;
98 else
99 return ((PyFileObject *)f)->f_name;
Guido van Rossumdb3165e1993-10-18 17:06:59 +0000100}
101
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +0000102/* This is a safe wrapper around PyObject_Print to print to the FILE
103 of a PyFileObject. PyObject_Print releases the GIL but knows nothing
104 about PyFileObject. */
105static int
106file_PyObject_Print(PyObject *op, PyFileObject *f, int flags)
107{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000108 int result;
109 PyFile_IncUseCount(f);
110 result = PyObject_Print(op, f->f_fp, flags);
111 PyFile_DecUseCount(f);
112 return result;
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +0000113}
114
Neil Schemenauered19b882002-03-23 02:06:50 +0000115/* On Unix, fopen will succeed for directories.
116 In Python, there should be no file objects referring to
117 directories, so we need a check. */
118
119static PyFileObject*
120dircheck(PyFileObject* f)
121{
122#if defined(HAVE_FSTAT) && defined(S_IFDIR) && defined(EISDIR)
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000123 struct stat buf;
124 if (f->f_fp == NULL)
125 return f;
126 if (fstat(fileno(f->f_fp), &buf) == 0 &&
127 S_ISDIR(buf.st_mode)) {
128 char *msg = strerror(EISDIR);
129 PyObject *exc = PyObject_CallFunction(PyExc_IOError, "(isO)",
130 EISDIR, msg, f->f_name);
131 PyErr_SetObject(PyExc_IOError, exc);
132 Py_XDECREF(exc);
133 return NULL;
134 }
Neil Schemenauered19b882002-03-23 02:06:50 +0000135#endif
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000136 return f;
Neil Schemenauered19b882002-03-23 02:06:50 +0000137}
138
Tim Peters59c9a642001-09-13 05:38:56 +0000139
140static PyObject *
Nicholas Bastinabce8a62004-03-21 20:24:07 +0000141fill_file_fields(PyFileObject *f, FILE *fp, PyObject *name, char *mode,
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000142 int (*close)(FILE *))
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000143{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000144 assert(name != NULL);
145 assert(f != NULL);
146 assert(PyFile_Check(f));
147 assert(f->f_fp == NULL);
Tim Peters44410012001-09-14 03:26:08 +0000148
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000149 Py_DECREF(f->f_name);
150 Py_DECREF(f->f_mode);
151 Py_DECREF(f->f_encoding);
152 Py_DECREF(f->f_errors);
Nicholas Bastinabce8a62004-03-21 20:24:07 +0000153
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000154 Py_INCREF(name);
155 f->f_name = name;
Nicholas Bastinabce8a62004-03-21 20:24:07 +0000156
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000157 f->f_mode = PyString_FromString(mode);
Tim Peters44410012001-09-14 03:26:08 +0000158
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000159 f->f_close = close;
160 f->f_softspace = 0;
161 f->f_binary = strchr(mode,'b') != NULL;
162 f->f_buf = NULL;
163 f->f_univ_newline = (strchr(mode, 'U') != NULL);
164 f->f_newlinetypes = NEWLINE_UNKNOWN;
165 f->f_skipnextlf = 0;
166 Py_INCREF(Py_None);
167 f->f_encoding = Py_None;
168 Py_INCREF(Py_None);
169 f->f_errors = Py_None;
170 f->readable = f->writable = 0;
171 if (strchr(mode, 'r') != NULL || f->f_univ_newline)
172 f->readable = 1;
173 if (strchr(mode, 'w') != NULL || strchr(mode, 'a') != NULL)
174 f->writable = 1;
175 if (strchr(mode, '+') != NULL)
176 f->readable = f->writable = 1;
Tim Petersf1827cf2003-09-07 03:30:18 +0000177
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000178 if (f->f_mode == NULL)
179 return NULL;
180 f->f_fp = fp;
181 f = dircheck(f);
182 return (PyObject *) f;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000183}
184
Kristján Valur Jónssonfd4c8722009-02-04 10:05:25 +0000185#if defined _MSC_VER && _MSC_VER >= 1400 && defined(__STDC_SECURE_LIB__)
186#define Py_VERIFY_WINNT
187/* The CRT on windows compiled with Visual Studio 2005 and higher may
188 * assert if given invalid mode strings. This is all fine and well
189 * in static languages like C where the mode string is typcially hard
190 * coded. But in Python, were we pass in the mode string from the user,
191 * we need to verify it first manually
192 */
193static int _PyVerify_Mode_WINNT(const char *mode)
194{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000195 /* See if mode string is valid on Windows to avoid hard assertions */
196 /* remove leading spacese */
197 int singles = 0;
198 int pairs = 0;
199 int encoding = 0;
200 const char *s, *c;
Kristján Valur Jónssonfd4c8722009-02-04 10:05:25 +0000201
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000202 while(*mode == ' ') /* strip initial spaces */
203 ++mode;
204 if (!strchr("rwa", *mode)) /* must start with one of these */
205 return 0;
206 while (*++mode) {
207 if (*mode == ' ' || *mode == 'N') /* ignore spaces and N */
208 continue;
209 s = "+TD"; /* each of this can appear only once */
210 c = strchr(s, *mode);
211 if (c) {
212 ptrdiff_t idx = s-c;
213 if (singles & (1<<idx))
214 return 0;
215 singles |= (1<<idx);
216 continue;
217 }
218 s = "btcnSR"; /* only one of each letter in the pairs allowed */
219 c = strchr(s, *mode);
220 if (c) {
221 ptrdiff_t idx = (s-c)/2;
222 if (pairs & (1<<idx))
223 return 0;
224 pairs |= (1<<idx);
225 continue;
226 }
227 if (*mode == ',') {
228 encoding = 1;
229 break;
230 }
231 return 0; /* found an invalid char */
232 }
Kristján Valur Jónssonfd4c8722009-02-04 10:05:25 +0000233
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000234 if (encoding) {
235 char *e[] = {"UTF-8", "UTF-16LE", "UNICODE"};
236 while (*mode == ' ')
237 ++mode;
238 /* find 'ccs =' */
239 if (strncmp(mode, "ccs", 3))
240 return 0;
241 mode += 3;
242 while (*mode == ' ')
243 ++mode;
244 if (*mode != '=')
245 return 0;
246 while (*mode == ' ')
247 ++mode;
248 for(encoding = 0; encoding<_countof(e); ++encoding) {
249 size_t l = strlen(e[encoding]);
250 if (!strncmp(mode, e[encoding], l)) {
251 mode += l; /* found a valid encoding */
252 break;
253 }
254 }
255 if (encoding == _countof(e))
256 return 0;
257 }
258 /* skip trailing spaces */
259 while (*mode == ' ')
260 ++mode;
Kristján Valur Jónssonfd4c8722009-02-04 10:05:25 +0000261
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000262 return *mode == '\0'; /* must be at the end of the string */
Kristján Valur Jónssonfd4c8722009-02-04 10:05:25 +0000263}
264#endif
265
Skip Montanarobbf12ba2005-05-20 03:07:06 +0000266/* check for known incorrect mode strings - problem is, platforms are
267 free to accept any mode characters they like and are supposed to
268 ignore stuff they don't understand... write or append mode with
Georg Brandl7b90e162006-05-18 07:01:27 +0000269 universal newline support is expressly forbidden by PEP 278.
270 Additionally, remove the 'U' from the mode string as platforms
Kristján Valur Jónsson0a440d42007-04-26 09:15:08 +0000271 won't know what it is. Non-zero return signals an exception */
272int
273_PyFile_SanitizeMode(char *mode)
Skip Montanarobbf12ba2005-05-20 03:07:06 +0000274{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000275 char *upos;
276 size_t len = strlen(mode);
Skip Montanarobbf12ba2005-05-20 03:07:06 +0000277
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000278 if (!len) {
279 PyErr_SetString(PyExc_ValueError, "empty mode string");
280 return -1;
281 }
Skip Montanarobbf12ba2005-05-20 03:07:06 +0000282
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000283 upos = strchr(mode, 'U');
284 if (upos) {
285 memmove(upos, upos+1, len-(upos-mode)); /* incl null char */
Skip Montanarobbf12ba2005-05-20 03:07:06 +0000286
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000287 if (mode[0] == 'w' || mode[0] == 'a') {
288 PyErr_Format(PyExc_ValueError, "universal newline "
289 "mode can only be used with modes "
290 "starting with 'r'");
291 return -1;
292 }
Georg Brandl7b90e162006-05-18 07:01:27 +0000293
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000294 if (mode[0] != 'r') {
295 memmove(mode+1, mode, strlen(mode)+1);
296 mode[0] = 'r';
297 }
Georg Brandl7b90e162006-05-18 07:01:27 +0000298
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000299 if (!strchr(mode, 'b')) {
300 memmove(mode+2, mode+1, strlen(mode));
301 mode[1] = 'b';
302 }
303 } else if (mode[0] != 'r' && mode[0] != 'w' && mode[0] != 'a') {
304 PyErr_Format(PyExc_ValueError, "mode string must begin with "
305 "one of 'r', 'w', 'a' or 'U', not '%.200s'", mode);
306 return -1;
307 }
Kristján Valur Jónssonfd4c8722009-02-04 10:05:25 +0000308#ifdef Py_VERIFY_WINNT
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000309 /* additional checks on NT with visual studio 2005 and higher */
310 if (!_PyVerify_Mode_WINNT(mode)) {
311 PyErr_Format(PyExc_ValueError, "Invalid mode ('%.50s')", mode);
312 return -1;
313 }
Kristján Valur Jónssonfd4c8722009-02-04 10:05:25 +0000314#endif
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000315 return 0;
Skip Montanarobbf12ba2005-05-20 03:07:06 +0000316}
317
Tim Peters59c9a642001-09-13 05:38:56 +0000318static PyObject *
319open_the_file(PyFileObject *f, char *name, char *mode)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000320{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000321 char *newmode;
322 assert(f != NULL);
323 assert(PyFile_Check(f));
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000324#ifdef MS_WINDOWS
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000325 /* windows ignores the passed name in order to support Unicode */
326 assert(f->f_name != NULL);
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000327#else
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000328 assert(name != NULL);
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000329#endif
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000330 assert(mode != NULL);
331 assert(f->f_fp == NULL);
Tim Peters59c9a642001-09-13 05:38:56 +0000332
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000333 /* probably need to replace 'U' by 'rb' */
334 newmode = PyMem_MALLOC(strlen(mode) + 3);
335 if (!newmode) {
336 PyErr_NoMemory();
337 return NULL;
338 }
339 strcpy(newmode, mode);
Georg Brandl7b90e162006-05-18 07:01:27 +0000340
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000341 if (_PyFile_SanitizeMode(newmode)) {
342 f = NULL;
343 goto cleanup;
344 }
Skip Montanarobbf12ba2005-05-20 03:07:06 +0000345
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000346 /* rexec.py can't stop a user from getting the file() constructor --
347 all they have to do is get *any* file object f, and then do
348 type(f). Here we prevent them from doing damage with it. */
349 if (PyEval_GetRestricted()) {
350 PyErr_SetString(PyExc_IOError,
351 "file() constructor not accessible in restricted mode");
352 f = NULL;
353 goto cleanup;
354 }
355 errno = 0;
Skip Montanaro51ffac62004-06-11 04:49:03 +0000356
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000357#ifdef MS_WINDOWS
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000358 if (PyUnicode_Check(f->f_name)) {
359 PyObject *wmode;
360 wmode = PyUnicode_DecodeASCII(newmode, strlen(newmode), NULL);
361 if (f->f_name && wmode) {
362 FILE_BEGIN_ALLOW_THREADS(f)
363 /* PyUnicode_AS_UNICODE OK without thread
364 lock as it is a simple dereference. */
365 f->f_fp = _wfopen(PyUnicode_AS_UNICODE(f->f_name),
366 PyUnicode_AS_UNICODE(wmode));
367 FILE_END_ALLOW_THREADS(f)
368 }
369 Py_XDECREF(wmode);
370 }
Skip Montanaro51ffac62004-06-11 04:49:03 +0000371#endif
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000372 if (NULL == f->f_fp && NULL != name) {
373 FILE_BEGIN_ALLOW_THREADS(f)
374 f->f_fp = fopen(name, newmode);
375 FILE_END_ALLOW_THREADS(f)
376 }
Skip Montanaro51ffac62004-06-11 04:49:03 +0000377
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000378 if (f->f_fp == NULL) {
Kristján Valur Jónsson74c3ea02006-07-03 14:59:05 +0000379#if defined _MSC_VER && (_MSC_VER < 1400 || !defined(__STDC_SECURE_LIB__))
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000380 /* MSVC 6 (Microsoft) leaves errno at 0 for bad mode strings,
381 * across all Windows flavors. When it sets EINVAL varies
382 * across Windows flavors, the exact conditions aren't
383 * documented, and the answer lies in the OS's implementation
384 * of Win32's CreateFile function (whose source is secret).
385 * Seems the best we can do is map EINVAL to ENOENT.
386 * Starting with Visual Studio .NET 2005, EINVAL is correctly
387 * set by our CRT error handler (set in exceptions.c.)
388 */
389 if (errno == 0) /* bad mode string */
390 errno = EINVAL;
391 else if (errno == EINVAL) /* unknown, but not a mode string */
392 errno = ENOENT;
Tim Peters2ea91112002-04-08 04:13:12 +0000393#endif
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000394 /* EINVAL is returned when an invalid filename or
395 * an invalid mode is supplied. */
396 if (errno == EINVAL) {
397 PyObject *v;
398 char message[100];
399 PyOS_snprintf(message, 100,
400 "invalid mode ('%.50s') or filename", mode);
401 v = Py_BuildValue("(isO)", errno, message, f->f_name);
402 if (v != NULL) {
403 PyErr_SetObject(PyExc_IOError, v);
404 Py_DECREF(v);
405 }
406 }
407 else
408 PyErr_SetFromErrnoWithFilenameObject(PyExc_IOError, f->f_name);
409 f = NULL;
410 }
411 if (f != NULL)
412 f = dircheck(f);
Georg Brandl7b90e162006-05-18 07:01:27 +0000413
414cleanup:
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000415 PyMem_FREE(newmode);
Georg Brandl7b90e162006-05-18 07:01:27 +0000416
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000417 return (PyObject *)f;
Tim Peters59c9a642001-09-13 05:38:56 +0000418}
419
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +0000420static PyObject *
421close_the_file(PyFileObject *f)
422{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000423 int sts = 0;
424 int (*local_close)(FILE *);
425 FILE *local_fp = f->f_fp;
Antoine Pitrou638cee62010-10-28 14:50:57 +0000426 char *local_setbuf = f->f_setbuf;
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000427 if (local_fp != NULL) {
428 local_close = f->f_close;
429 if (local_close != NULL && f->unlocked_count > 0) {
Benjamin Petersona72d15c2017-09-13 21:20:29 -0700430 if (Py_REFCNT(f) > 0) {
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000431 PyErr_SetString(PyExc_IOError,
432 "close() called during concurrent "
Serhiy Storchaka6401e562017-11-10 12:58:55 +0200433 "operation on the same file object");
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000434 } else {
435 /* This should not happen unless someone is
436 * carelessly playing with the PyFileObject
437 * struct fields and/or its associated FILE
438 * pointer. */
439 PyErr_SetString(PyExc_SystemError,
440 "PyFileObject locking error in "
Serhiy Storchaka6401e562017-11-10 12:58:55 +0200441 "destructor (refcnt <= 0 at close)");
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000442 }
443 return NULL;
444 }
445 /* NULL out the FILE pointer before releasing the GIL, because
446 * it will not be valid anymore after the close() function is
447 * called. */
448 f->f_fp = NULL;
449 if (local_close != NULL) {
Antoine Pitrou638cee62010-10-28 14:50:57 +0000450 /* Issue #9295: must temporarily reset f_setbuf so that another
451 thread doesn't free it when running file_close() concurrently.
452 Otherwise this close() will crash when flushing the buffer. */
453 f->f_setbuf = NULL;
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000454 Py_BEGIN_ALLOW_THREADS
455 errno = 0;
456 sts = (*local_close)(local_fp);
457 Py_END_ALLOW_THREADS
Antoine Pitrou638cee62010-10-28 14:50:57 +0000458 f->f_setbuf = local_setbuf;
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000459 if (sts == EOF)
460 return PyErr_SetFromErrno(PyExc_IOError);
461 if (sts != 0)
462 return PyInt_FromLong((long)sts);
463 }
464 }
465 Py_RETURN_NONE;
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +0000466}
467
Tim Peters59c9a642001-09-13 05:38:56 +0000468PyObject *
469PyFile_FromFile(FILE *fp, char *name, char *mode, int (*close)(FILE *))
470{
Victor Stinner63c22fa2011-09-23 19:37:03 +0200471 PyFileObject *f;
472 PyObject *o_name;
473
474 f = (PyFileObject *)PyFile_Type.tp_new(&PyFile_Type, NULL, NULL);
475 if (f == NULL)
476 return NULL;
477 o_name = PyString_FromString(name);
478 if (o_name == NULL) {
479 if (close != NULL && fp != NULL)
480 close(fp);
481 Py_DECREF(f);
482 return NULL;
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000483 }
Victor Stinner63c22fa2011-09-23 19:37:03 +0200484 if (fill_file_fields(f, fp, o_name, mode, close) == NULL) {
485 Py_DECREF(f);
486 Py_DECREF(o_name);
487 return NULL;
488 }
489 Py_DECREF(o_name);
490 return (PyObject *)f;
Tim Peters59c9a642001-09-13 05:38:56 +0000491}
492
493PyObject *
494PyFile_FromString(char *name, char *mode)
495{
Antoine Pitrou02a38012012-04-05 14:07:52 +0200496 extern int fclose(FILE *);
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000497 PyFileObject *f;
Tim Peters59c9a642001-09-13 05:38:56 +0000498
Antoine Pitrou02a38012012-04-05 14:07:52 +0200499 f = (PyFileObject *)PyFile_FromFile((FILE *)NULL, name, mode, fclose);
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000500 if (f != NULL) {
501 if (open_the_file(f, name, mode) == NULL) {
502 Py_DECREF(f);
503 f = NULL;
504 }
505 }
506 return (PyObject *)f;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000507}
508
Guido van Rossumb6775db1994-08-01 11:34:53 +0000509void
Fred Drakefd99de62000-07-09 05:02:18 +0000510PyFile_SetBufSize(PyObject *f, int bufsize)
Guido van Rossumb6775db1994-08-01 11:34:53 +0000511{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000512 PyFileObject *file = (PyFileObject *)f;
513 if (bufsize >= 0) {
514 int type;
515 switch (bufsize) {
516 case 0:
517 type = _IONBF;
518 break;
Martin v. Löwis1e3bdf62003-09-04 19:01:46 +0000519#ifdef HAVE_SETVBUF
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000520 case 1:
521 type = _IOLBF;
522 bufsize = BUFSIZ;
523 break;
Martin v. Löwis1e3bdf62003-09-04 19:01:46 +0000524#endif
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000525 default:
526 type = _IOFBF;
Martin v. Löwis1e3bdf62003-09-04 19:01:46 +0000527#ifndef HAVE_SETVBUF
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000528 bufsize = BUFSIZ;
Martin v. Löwis1e3bdf62003-09-04 19:01:46 +0000529#endif
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000530 break;
531 }
532 fflush(file->f_fp);
533 if (type == _IONBF) {
534 PyMem_Free(file->f_setbuf);
535 file->f_setbuf = NULL;
536 } else {
537 file->f_setbuf = (char *)PyMem_Realloc(file->f_setbuf,
538 bufsize);
539 }
Martin v. Löwis1e3bdf62003-09-04 19:01:46 +0000540#ifdef HAVE_SETVBUF
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000541 setvbuf(file->f_fp, file->f_setbuf, type, bufsize);
Guido van Rossumf8b4de01998-03-06 15:32:40 +0000542#else /* !HAVE_SETVBUF */
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000543 setbuf(file->f_fp, file->f_setbuf);
Guido van Rossumf8b4de01998-03-06 15:32:40 +0000544#endif /* !HAVE_SETVBUF */
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000545 }
Guido van Rossumb6775db1994-08-01 11:34:53 +0000546}
547
Martin v. Löwis5467d4c2003-05-10 07:10:12 +0000548/* Set the encoding used to output Unicode strings.
Martin v. Löwis99815892008-06-01 07:20:46 +0000549 Return 1 on success, 0 on failure. */
Martin v. Löwis5467d4c2003-05-10 07:10:12 +0000550
551int
552PyFile_SetEncoding(PyObject *f, const char *enc)
553{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000554 return PyFile_SetEncodingAndErrors(f, enc, NULL);
Martin v. Löwis99815892008-06-01 07:20:46 +0000555}
556
557int
558PyFile_SetEncodingAndErrors(PyObject *f, const char *enc, char* errors)
559{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000560 PyFileObject *file = (PyFileObject*)f;
561 PyObject *str, *oerrors;
Thomas Woutersafea5292007-01-23 13:42:00 +0000562
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000563 assert(PyFile_Check(f));
564 str = PyString_FromString(enc);
565 if (!str)
566 return 0;
567 if (errors) {
568 oerrors = PyString_FromString(errors);
569 if (!oerrors) {
570 Py_DECREF(str);
571 return 0;
572 }
573 } else {
574 oerrors = Py_None;
575 Py_INCREF(Py_None);
576 }
Serhiy Storchaka763a61c2016-04-10 18:05:12 +0300577 Py_SETREF(file->f_encoding, str);
578 Py_SETREF(file->f_errors, oerrors);
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000579 return 1;
Martin v. Löwis5467d4c2003-05-10 07:10:12 +0000580}
581
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000582static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000583err_closed(void)
Guido van Rossumd7297e61992-07-06 14:19:26 +0000584{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000585 PyErr_SetString(PyExc_ValueError, "I/O operation on closed file");
586 return NULL;
Guido van Rossumd7297e61992-07-06 14:19:26 +0000587}
588
Antoine Pitroubb445a12010-02-05 17:05:54 +0000589static PyObject *
590err_mode(char *action)
591{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000592 PyErr_Format(PyExc_IOError, "File not open for %s", action);
593 return NULL;
Antoine Pitroubb445a12010-02-05 17:05:54 +0000594}
595
Thomas Woutersc45251a2006-02-12 11:53:32 +0000596/* Refuse regular file I/O if there's data in the iteration-buffer.
597 * Mixing them would cause data to arrive out of order, as the read*
598 * methods don't use the iteration buffer. */
599static PyObject *
600err_iterbuffered(void)
601{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000602 PyErr_SetString(PyExc_ValueError,
603 "Mixing iteration and read methods would lose data");
604 return NULL;
Thomas Woutersc45251a2006-02-12 11:53:32 +0000605}
606
Neal Norwitzd8b995f2002-08-06 21:50:54 +0000607static void drop_readahead(PyFileObject *);
Guido van Rossum7a6e9592002-08-06 15:55:28 +0000608
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000609/* Methods */
610
611static void
Fred Drakefd99de62000-07-09 05:02:18 +0000612file_dealloc(PyFileObject *f)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000613{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000614 PyObject *ret;
615 if (f->weakreflist != NULL)
616 PyObject_ClearWeakRefs((PyObject *) f);
617 ret = close_the_file(f);
618 if (!ret) {
619 PySys_WriteStderr("close failed in file object destructor:\n");
620 PyErr_Print();
621 }
622 else {
623 Py_DECREF(ret);
624 }
625 PyMem_Free(f->f_setbuf);
626 Py_XDECREF(f->f_name);
627 Py_XDECREF(f->f_mode);
628 Py_XDECREF(f->f_encoding);
629 Py_XDECREF(f->f_errors);
630 drop_readahead(f);
631 Py_TYPE(f)->tp_free((PyObject *)f);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000632}
633
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000634static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000635file_repr(PyFileObject *f)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000636{
Ezio Melotti11f8b682012-03-12 01:17:02 +0200637 PyObject *ret = NULL;
638 PyObject *name = NULL;
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000639 if (PyUnicode_Check(f->f_name)) {
Martin v. Löwis0073f2e2002-11-21 23:52:35 +0000640#ifdef Py_USING_UNICODE
Ezio Melottieace3a72012-03-12 01:28:45 +0200641 const char *name_str;
Ezio Melotti11f8b682012-03-12 01:17:02 +0200642 name = PyUnicode_AsUnicodeEscapeString(f->f_name);
Ezio Melottieace3a72012-03-12 01:28:45 +0200643 name_str = name ? PyString_AsString(name) : "?";
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000644 ret = PyString_FromFormat("<%s file u'%s', mode '%s' at %p>",
645 f->f_fp == NULL ? "closed" : "open",
646 name_str,
647 PyString_AsString(f->f_mode),
648 f);
649 Py_XDECREF(name);
650 return ret;
Martin v. Löwis0073f2e2002-11-21 23:52:35 +0000651#endif
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000652 } else {
Ezio Melotti11f8b682012-03-12 01:17:02 +0200653 name = PyObject_Repr(f->f_name);
654 if (name == NULL)
655 return NULL;
656 ret = PyString_FromFormat("<%s file %s, mode '%s' at %p>",
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000657 f->f_fp == NULL ? "closed" : "open",
Ezio Melotti11f8b682012-03-12 01:17:02 +0200658 PyString_AsString(name),
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000659 PyString_AsString(f->f_mode),
660 f);
Ezio Melotti11f8b682012-03-12 01:17:02 +0200661 Py_XDECREF(name);
662 return ret;
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000663 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000664}
665
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000666static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000667file_close(PyFileObject *f)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000668{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000669 PyObject *sts = close_the_file(f);
Antoine Pitrou83137c22010-05-17 19:56:59 +0000670 if (sts) {
671 PyMem_Free(f->f_setbuf);
672 f->f_setbuf = NULL;
673 }
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000674 return sts;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000675}
676
Trent Mickf29f47b2000-08-11 19:02:59 +0000677
Guido van Rossumb8552162001-09-05 14:58:11 +0000678/* Our very own off_t-like type, 64-bit if possible */
679#if !defined(HAVE_LARGEFILE_SUPPORT)
680typedef off_t Py_off_t;
681#elif SIZEOF_OFF_T >= 8
682typedef off_t Py_off_t;
683#elif SIZEOF_FPOS_T >= 8
Guido van Rossum4f53da02001-03-01 18:26:53 +0000684typedef fpos_t Py_off_t;
685#else
Guido van Rossumb8552162001-09-05 14:58:11 +0000686#error "Large file support, but neither off_t nor fpos_t is large enough."
Guido van Rossum4f53da02001-03-01 18:26:53 +0000687#endif
688
689
Trent Mickf29f47b2000-08-11 19:02:59 +0000690/* a portable fseek() function
691 return 0 on success, non-zero on failure (with errno set) */
Guido van Rossumf68d8e52001-04-14 17:55:09 +0000692static int
Guido van Rossum4f53da02001-03-01 18:26:53 +0000693_portable_fseek(FILE *fp, Py_off_t offset, int whence)
Trent Mickf29f47b2000-08-11 19:02:59 +0000694{
Guido van Rossumb8552162001-09-05 14:58:11 +0000695#if !defined(HAVE_LARGEFILE_SUPPORT)
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000696 return fseek(fp, offset, whence);
Guido van Rossumb8552162001-09-05 14:58:11 +0000697#elif defined(HAVE_FSEEKO) && SIZEOF_OFF_T >= 8
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000698 return fseeko(fp, offset, whence);
Trent Mickf29f47b2000-08-11 19:02:59 +0000699#elif defined(HAVE_FSEEK64)
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000700 return fseek64(fp, offset, whence);
Fred Drakedb810ac2000-10-06 20:42:33 +0000701#elif defined(__BEOS__)
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000702 return _fseek(fp, offset, whence);
Guido van Rossumb8552162001-09-05 14:58:11 +0000703#elif SIZEOF_FPOS_T >= 8
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000704 /* lacking a 64-bit capable fseek(), use a 64-bit capable fsetpos()
705 and fgetpos() to implement fseek()*/
706 fpos_t pos;
707 switch (whence) {
708 case SEEK_END:
Guido van Rossum8b4e43e2001-09-10 20:43:35 +0000709#ifdef MS_WINDOWS
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000710 fflush(fp);
711 if (_lseeki64(fileno(fp), 0, 2) == -1)
712 return -1;
Guido van Rossum8b4e43e2001-09-10 20:43:35 +0000713#else
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000714 if (fseek(fp, 0, SEEK_END) != 0)
715 return -1;
Guido van Rossum8b4e43e2001-09-10 20:43:35 +0000716#endif
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000717 /* fall through */
718 case SEEK_CUR:
719 if (fgetpos(fp, &pos) != 0)
720 return -1;
721 offset += pos;
722 break;
723 /* case SEEK_SET: break; */
724 }
725 return fsetpos(fp, &offset);
Trent Mickf29f47b2000-08-11 19:02:59 +0000726#else
Guido van Rossumb8552162001-09-05 14:58:11 +0000727#error "Large file support, but no way to fseek."
Trent Mickf29f47b2000-08-11 19:02:59 +0000728#endif
729}
730
731
732/* a portable ftell() function
733 Return -1 on failure with errno set appropriately, current file
734 position on success */
Guido van Rossumf68d8e52001-04-14 17:55:09 +0000735static Py_off_t
Fred Drake8ce159a2000-08-31 05:18:54 +0000736_portable_ftell(FILE* fp)
Trent Mickf29f47b2000-08-11 19:02:59 +0000737{
Guido van Rossumb8552162001-09-05 14:58:11 +0000738#if !defined(HAVE_LARGEFILE_SUPPORT)
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000739 return ftell(fp);
Guido van Rossumb8552162001-09-05 14:58:11 +0000740#elif defined(HAVE_FTELLO) && SIZEOF_OFF_T >= 8
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000741 return ftello(fp);
Guido van Rossumb8552162001-09-05 14:58:11 +0000742#elif defined(HAVE_FTELL64)
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000743 return ftell64(fp);
Guido van Rossumb8552162001-09-05 14:58:11 +0000744#elif SIZEOF_FPOS_T >= 8
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000745 fpos_t pos;
746 if (fgetpos(fp, &pos) != 0)
747 return -1;
748 return pos;
Trent Mickf29f47b2000-08-11 19:02:59 +0000749#else
Guido van Rossumb8552162001-09-05 14:58:11 +0000750#error "Large file support, but no way to ftell."
Trent Mickf29f47b2000-08-11 19:02:59 +0000751#endif
752}
753
754
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000755static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000756file_seek(PyFileObject *f, PyObject *args)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000757{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000758 int whence;
759 int ret;
760 Py_off_t offset;
761 PyObject *offobj, *off_index;
Tim Peters86821b22001-01-07 21:19:34 +0000762
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000763 if (f->f_fp == NULL)
764 return err_closed();
Serhiy Storchaka6401e562017-11-10 12:58:55 +0200765 if (f->unlocked_count > 0) {
766 PyErr_SetString(PyExc_IOError,
767 "seek() called during concurrent "
768 "operation on the same file object");
769 return NULL;
770 }
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000771 drop_readahead(f);
772 whence = 0;
773 if (!PyArg_ParseTuple(args, "O|i:seek", &offobj, &whence))
774 return NULL;
775 off_index = PyNumber_Index(offobj);
776 if (!off_index) {
777 if (!PyFloat_Check(offobj))
778 return NULL;
779 /* Deprecated in 2.6 */
780 PyErr_Clear();
781 if (PyErr_WarnEx(PyExc_DeprecationWarning,
782 "integer argument expected, got float",
783 1) < 0)
784 return NULL;
785 off_index = offobj;
786 Py_INCREF(offobj);
787 }
Guido van Rossum3c9fe0c1999-01-06 18:51:17 +0000788#if !defined(HAVE_LARGEFILE_SUPPORT)
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000789 offset = PyInt_AsLong(off_index);
Guido van Rossum3c9fe0c1999-01-06 18:51:17 +0000790#else
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000791 offset = PyLong_Check(off_index) ?
792 PyLong_AsLongLong(off_index) : PyInt_AsLong(off_index);
Guido van Rossum3c9fe0c1999-01-06 18:51:17 +0000793#endif
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000794 Py_DECREF(off_index);
795 if (PyErr_Occurred())
796 return NULL;
Tim Peters86821b22001-01-07 21:19:34 +0000797
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000798 FILE_BEGIN_ALLOW_THREADS(f)
799 errno = 0;
800 ret = _portable_fseek(f->f_fp, offset, whence);
801 FILE_END_ALLOW_THREADS(f)
Trent Mickf29f47b2000-08-11 19:02:59 +0000802
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000803 if (ret != 0) {
804 PyErr_SetFromErrno(PyExc_IOError);
805 clearerr(f->f_fp);
806 return NULL;
807 }
808 f->f_skipnextlf = 0;
809 Py_INCREF(Py_None);
810 return Py_None;
Guido van Rossumce5ba841991-03-06 13:06:18 +0000811}
812
Trent Mickf29f47b2000-08-11 19:02:59 +0000813
Guido van Rossumd7047b31995-01-02 19:07:15 +0000814#ifdef HAVE_FTRUNCATE
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000815static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000816file_truncate(PyFileObject *f, PyObject *args)
Guido van Rossumd7047b31995-01-02 19:07:15 +0000817{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000818 Py_off_t newsize;
819 PyObject *newsizeobj = NULL;
820 Py_off_t initialpos;
821 int ret;
Tim Peters86821b22001-01-07 21:19:34 +0000822
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000823 if (f->f_fp == NULL)
824 return err_closed();
825 if (!f->writable)
826 return err_mode("writing");
827 if (!PyArg_UnpackTuple(args, "truncate", 0, 1, &newsizeobj))
828 return NULL;
Tim Petersfb05db22002-03-11 00:24:00 +0000829
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000830 /* Get current file position. If the file happens to be open for
831 * update and the last operation was an input operation, C doesn't
832 * define what the later fflush() will do, but we promise truncate()
833 * won't change the current position (and fflush() *does* change it
834 * then at least on Windows). The easiest thing is to capture
835 * current pos now and seek back to it at the end.
836 */
837 FILE_BEGIN_ALLOW_THREADS(f)
838 errno = 0;
839 initialpos = _portable_ftell(f->f_fp);
840 FILE_END_ALLOW_THREADS(f)
841 if (initialpos == -1)
842 goto onioerror;
Tim Petersf1827cf2003-09-07 03:30:18 +0000843
Martin Panter8d496ad2016-06-02 10:35:44 +0000844 /* Set newsize to current position if newsizeobj NULL, else to the
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000845 * specified value.
846 */
847 if (newsizeobj != NULL) {
Guido van Rossum3c9fe0c1999-01-06 18:51:17 +0000848#if !defined(HAVE_LARGEFILE_SUPPORT)
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000849 newsize = PyInt_AsLong(newsizeobj);
Guido van Rossum3c9fe0c1999-01-06 18:51:17 +0000850#else
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000851 newsize = PyLong_Check(newsizeobj) ?
852 PyLong_AsLongLong(newsizeobj) :
853 PyInt_AsLong(newsizeobj);
Guido van Rossum3c9fe0c1999-01-06 18:51:17 +0000854#endif
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000855 if (PyErr_Occurred())
856 return NULL;
857 }
858 else /* default to current position */
859 newsize = initialpos;
Tim Petersfb05db22002-03-11 00:24:00 +0000860
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000861 /* Flush the stream. We're mixing stream-level I/O with lower-level
862 * I/O, and a flush may be necessary to synch both platform views
863 * of the current file state.
864 */
865 FILE_BEGIN_ALLOW_THREADS(f)
866 errno = 0;
867 ret = fflush(f->f_fp);
868 FILE_END_ALLOW_THREADS(f)
869 if (ret != 0)
870 goto onioerror;
Trent Mickf29f47b2000-08-11 19:02:59 +0000871
Martin v. Löwis6238d2b2002-06-30 15:26:10 +0000872#ifdef MS_WINDOWS
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000873 /* MS _chsize doesn't work if newsize doesn't fit in 32 bits,
874 so don't even try using it. */
875 {
876 HANDLE hFile;
Tim Petersfb05db22002-03-11 00:24:00 +0000877
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000878 /* Have to move current pos to desired endpoint on Windows. */
879 FILE_BEGIN_ALLOW_THREADS(f)
880 errno = 0;
881 ret = _portable_fseek(f->f_fp, newsize, SEEK_SET) != 0;
882 FILE_END_ALLOW_THREADS(f)
883 if (ret)
884 goto onioerror;
Tim Petersfb05db22002-03-11 00:24:00 +0000885
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000886 /* Truncate. Note that this may grow the file! */
887 FILE_BEGIN_ALLOW_THREADS(f)
888 errno = 0;
889 hFile = (HANDLE)_get_osfhandle(fileno(f->f_fp));
890 ret = hFile == (HANDLE)-1;
891 if (ret == 0) {
892 ret = SetEndOfFile(hFile) == 0;
893 if (ret)
894 errno = EACCES;
895 }
896 FILE_END_ALLOW_THREADS(f)
897 if (ret)
898 goto onioerror;
899 }
Trent Mickf29f47b2000-08-11 19:02:59 +0000900#else
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000901 FILE_BEGIN_ALLOW_THREADS(f)
902 errno = 0;
903 ret = ftruncate(fileno(f->f_fp), newsize);
904 FILE_END_ALLOW_THREADS(f)
905 if (ret != 0)
906 goto onioerror;
Martin v. Löwis6238d2b2002-06-30 15:26:10 +0000907#endif /* !MS_WINDOWS */
Tim Peters86821b22001-01-07 21:19:34 +0000908
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000909 /* Restore original file position. */
910 FILE_BEGIN_ALLOW_THREADS(f)
911 errno = 0;
912 ret = _portable_fseek(f->f_fp, initialpos, SEEK_SET) != 0;
913 FILE_END_ALLOW_THREADS(f)
914 if (ret)
915 goto onioerror;
Tim Petersf1827cf2003-09-07 03:30:18 +0000916
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000917 Py_INCREF(Py_None);
918 return Py_None;
Trent Mickf29f47b2000-08-11 19:02:59 +0000919
920onioerror:
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000921 PyErr_SetFromErrno(PyExc_IOError);
922 clearerr(f->f_fp);
923 return NULL;
Guido van Rossumd7047b31995-01-02 19:07:15 +0000924}
925#endif /* HAVE_FTRUNCATE */
926
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000927static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000928file_tell(PyFileObject *f)
Guido van Rossumce5ba841991-03-06 13:06:18 +0000929{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000930 Py_off_t pos;
Trent Mickf29f47b2000-08-11 19:02:59 +0000931
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000932 if (f->f_fp == NULL)
933 return err_closed();
934 FILE_BEGIN_ALLOW_THREADS(f)
935 errno = 0;
936 pos = _portable_ftell(f->f_fp);
937 FILE_END_ALLOW_THREADS(f)
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +0000938
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000939 if (pos == -1) {
940 PyErr_SetFromErrno(PyExc_IOError);
941 clearerr(f->f_fp);
942 return NULL;
943 }
944 if (f->f_skipnextlf) {
945 int c;
946 c = GETC(f->f_fp);
947 if (c == '\n') {
948 f->f_newlinetypes |= NEWLINE_CRLF;
949 pos++;
950 f->f_skipnextlf = 0;
951 } else if (c != EOF) ungetc(c, f->f_fp);
952 }
Guido van Rossum3c9fe0c1999-01-06 18:51:17 +0000953#if !defined(HAVE_LARGEFILE_SUPPORT)
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000954 return PyInt_FromLong(pos);
Guido van Rossum3c9fe0c1999-01-06 18:51:17 +0000955#else
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000956 return PyLong_FromLongLong(pos);
Guido van Rossum3c9fe0c1999-01-06 18:51:17 +0000957#endif
Guido van Rossumce5ba841991-03-06 13:06:18 +0000958}
959
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000960static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000961file_fileno(PyFileObject *f)
Guido van Rossumed233a51992-06-23 09:07:03 +0000962{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000963 if (f->f_fp == NULL)
964 return err_closed();
965 return PyInt_FromLong((long) fileno(f->f_fp));
Guido van Rossumed233a51992-06-23 09:07:03 +0000966}
967
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000968static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000969file_flush(PyFileObject *f)
Guido van Rossumce5ba841991-03-06 13:06:18 +0000970{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000971 int res;
Tim Peters86821b22001-01-07 21:19:34 +0000972
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000973 if (f->f_fp == NULL)
974 return err_closed();
975 FILE_BEGIN_ALLOW_THREADS(f)
976 errno = 0;
977 res = fflush(f->f_fp);
978 FILE_END_ALLOW_THREADS(f)
979 if (res != 0) {
980 PyErr_SetFromErrno(PyExc_IOError);
981 clearerr(f->f_fp);
982 return NULL;
983 }
984 Py_INCREF(Py_None);
985 return Py_None;
Guido van Rossumce5ba841991-03-06 13:06:18 +0000986}
987
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000988static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000989file_isatty(PyFileObject *f)
Guido van Rossuma1ab7fa1991-06-04 19:37:39 +0000990{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000991 long res;
992 if (f->f_fp == NULL)
993 return err_closed();
994 FILE_BEGIN_ALLOW_THREADS(f)
995 res = isatty((int)fileno(f->f_fp));
996 FILE_END_ALLOW_THREADS(f)
997 return PyBool_FromLong(res);
Guido van Rossuma1ab7fa1991-06-04 19:37:39 +0000998}
999
Guido van Rossumff7e83d1999-08-27 20:39:37 +00001000
Guido van Rossum5449b6e1997-05-09 22:27:31 +00001001#if BUFSIZ < 8192
1002#define SMALLCHUNK 8192
1003#else
1004#define SMALLCHUNK BUFSIZ
1005#endif
1006
Guido van Rossum5449b6e1997-05-09 22:27:31 +00001007static size_t
Fred Drakefd99de62000-07-09 05:02:18 +00001008new_buffersize(PyFileObject *f, size_t currentsize)
Guido van Rossum5449b6e1997-05-09 22:27:31 +00001009{
1010#ifdef HAVE_FSTAT
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001011 off_t pos, end;
1012 struct stat st;
1013 if (fstat(fileno(f->f_fp), &st) == 0) {
1014 end = st.st_size;
1015 /* The following is not a bug: we really need to call lseek()
1016 *and* ftell(). The reason is that some stdio libraries
1017 mistakenly flush their buffer when ftell() is called and
1018 the lseek() call it makes fails, thereby throwing away
1019 data that cannot be recovered in any way. To avoid this,
1020 we first test lseek(), and only call ftell() if lseek()
1021 works. We can't use the lseek() value either, because we
1022 need to take the amount of buffered data into account.
1023 (Yet another reason why stdio stinks. :-) */
1024 pos = lseek(fileno(f->f_fp), 0L, SEEK_CUR);
1025 if (pos >= 0) {
1026 pos = ftell(f->f_fp);
1027 }
1028 if (pos < 0)
1029 clearerr(f->f_fp);
1030 if (end > pos && pos >= 0)
1031 return currentsize + end - pos + 1;
1032 /* Add 1 so if the file were to grow we'd notice. */
1033 }
Guido van Rossum5449b6e1997-05-09 22:27:31 +00001034#endif
Nadeem Vawda36248152011-10-13 13:52:46 +02001035 /* Expand the buffer by an amount proportional to the current size,
1036 giving us amortized linear-time behavior. Use a less-than-double
1037 growth factor to avoid excessive allocation. */
1038 return currentsize + (currentsize >> 3) + 6;
Guido van Rossum5449b6e1997-05-09 22:27:31 +00001039}
1040
Gustavo Niemeyer786ddb22002-12-16 18:12:53 +00001041#if defined(EWOULDBLOCK) && defined(EAGAIN) && EWOULDBLOCK != EAGAIN
1042#define BLOCKED_ERRNO(x) ((x) == EWOULDBLOCK || (x) == EAGAIN)
1043#else
1044#ifdef EWOULDBLOCK
1045#define BLOCKED_ERRNO(x) ((x) == EWOULDBLOCK)
1046#else
1047#ifdef EAGAIN
1048#define BLOCKED_ERRNO(x) ((x) == EAGAIN)
1049#else
1050#define BLOCKED_ERRNO(x) 0
1051#endif
1052#endif
1053#endif
1054
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001055static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +00001056file_read(PyFileObject *f, PyObject *args)
Guido van Rossumce5ba841991-03-06 13:06:18 +00001057{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001058 long bytesrequested = -1;
1059 size_t bytesread, buffersize, chunksize;
1060 PyObject *v;
Tim Peters86821b22001-01-07 21:19:34 +00001061
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001062 if (f->f_fp == NULL)
1063 return err_closed();
1064 if (!f->readable)
1065 return err_mode("reading");
1066 /* refuse to mix with f.next() */
1067 if (f->f_buf != NULL &&
1068 (f->f_bufend - f->f_bufptr) > 0 &&
1069 f->f_buf[0] != '\0')
1070 return err_iterbuffered();
1071 if (!PyArg_ParseTuple(args, "|l:read", &bytesrequested))
1072 return NULL;
1073 if (bytesrequested < 0)
1074 buffersize = new_buffersize(f, (size_t)0);
1075 else
1076 buffersize = bytesrequested;
1077 if (buffersize > PY_SSIZE_T_MAX) {
1078 PyErr_SetString(PyExc_OverflowError,
1079 "requested number of bytes is more than a Python string can hold");
1080 return NULL;
1081 }
1082 v = PyString_FromStringAndSize((char *)NULL, buffersize);
1083 if (v == NULL)
1084 return NULL;
1085 bytesread = 0;
1086 for (;;) {
Gregory P. Smithb2ac4d62012-06-25 20:57:36 -07001087 int interrupted;
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001088 FILE_BEGIN_ALLOW_THREADS(f)
1089 errno = 0;
1090 chunksize = Py_UniversalNewlineFread(BUF(v) + bytesread,
1091 buffersize - bytesread, f->f_fp, (PyObject *)f);
Gregory P. Smithb2ac4d62012-06-25 20:57:36 -07001092 interrupted = ferror(f->f_fp) && errno == EINTR;
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001093 FILE_END_ALLOW_THREADS(f)
Gregory P. Smithb2ac4d62012-06-25 20:57:36 -07001094 if (interrupted) {
1095 clearerr(f->f_fp);
1096 if (PyErr_CheckSignals()) {
1097 Py_DECREF(v);
1098 return NULL;
1099 }
1100 }
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001101 if (chunksize == 0) {
Gregory P. Smithb2ac4d62012-06-25 20:57:36 -07001102 if (interrupted)
1103 continue;
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001104 if (!ferror(f->f_fp))
1105 break;
1106 clearerr(f->f_fp);
1107 /* When in non-blocking mode, data shouldn't
1108 * be discarded if a blocking signal was
1109 * received. That will also happen if
1110 * chunksize != 0, but bytesread < buffersize. */
1111 if (bytesread > 0 && BLOCKED_ERRNO(errno))
1112 break;
1113 PyErr_SetFromErrno(PyExc_IOError);
1114 Py_DECREF(v);
1115 return NULL;
1116 }
1117 bytesread += chunksize;
Gregory P. Smithb2ac4d62012-06-25 20:57:36 -07001118 if (bytesread < buffersize && !interrupted) {
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001119 clearerr(f->f_fp);
1120 break;
1121 }
1122 if (bytesrequested < 0) {
1123 buffersize = new_buffersize(f, buffersize);
1124 if (_PyString_Resize(&v, buffersize) < 0)
1125 return NULL;
1126 } else {
1127 /* Got what was requested. */
1128 break;
1129 }
1130 }
1131 if (bytesread != buffersize && _PyString_Resize(&v, bytesread))
1132 return NULL;
1133 return v;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001134}
1135
Guido van Rossumfdf95dd1997-05-05 22:15:02 +00001136static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +00001137file_readinto(PyFileObject *f, PyObject *args)
Guido van Rossumfdf95dd1997-05-05 22:15:02 +00001138{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001139 char *ptr;
1140 Py_ssize_t ntodo;
1141 Py_ssize_t ndone, nnow;
1142 Py_buffer pbuf;
Tim Peters86821b22001-01-07 21:19:34 +00001143
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001144 if (f->f_fp == NULL)
1145 return err_closed();
1146 if (!f->readable)
1147 return err_mode("reading");
1148 /* refuse to mix with f.next() */
1149 if (f->f_buf != NULL &&
1150 (f->f_bufend - f->f_bufptr) > 0 &&
1151 f->f_buf[0] != '\0')
1152 return err_iterbuffered();
1153 if (!PyArg_ParseTuple(args, "w*", &pbuf))
1154 return NULL;
1155 ptr = pbuf.buf;
1156 ntodo = pbuf.len;
1157 ndone = 0;
1158 while (ntodo > 0) {
Gregory P. Smithb2ac4d62012-06-25 20:57:36 -07001159 int interrupted;
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001160 FILE_BEGIN_ALLOW_THREADS(f)
1161 errno = 0;
1162 nnow = Py_UniversalNewlineFread(ptr+ndone, ntodo, f->f_fp,
1163 (PyObject *)f);
Gregory P. Smithb2ac4d62012-06-25 20:57:36 -07001164 interrupted = ferror(f->f_fp) && errno == EINTR;
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001165 FILE_END_ALLOW_THREADS(f)
Gregory P. Smithb2ac4d62012-06-25 20:57:36 -07001166 if (interrupted) {
1167 clearerr(f->f_fp);
1168 if (PyErr_CheckSignals()) {
1169 PyBuffer_Release(&pbuf);
1170 return NULL;
1171 }
1172 }
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001173 if (nnow == 0) {
Gregory P. Smithb2ac4d62012-06-25 20:57:36 -07001174 if (interrupted)
1175 continue;
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001176 if (!ferror(f->f_fp))
1177 break;
1178 PyErr_SetFromErrno(PyExc_IOError);
1179 clearerr(f->f_fp);
1180 PyBuffer_Release(&pbuf);
1181 return NULL;
1182 }
1183 ndone += nnow;
1184 ntodo -= nnow;
1185 }
1186 PyBuffer_Release(&pbuf);
1187 return PyInt_FromSsize_t(ndone);
Guido van Rossumfdf95dd1997-05-05 22:15:02 +00001188}
1189
Tim Peters86821b22001-01-07 21:19:34 +00001190/**************************************************************************
Tim Petersf29b64d2001-01-15 06:33:19 +00001191Routine to get next line using platform fgets().
Tim Peters86821b22001-01-07 21:19:34 +00001192
1193Under MSVC 6:
1194
Tim Peters1c733232001-01-08 04:02:07 +00001195+ MS threadsafe getc is very slow (multiple layers of function calls before+
1196 after each character, to lock+unlock the stream).
1197+ The stream-locking functions are MS-internal -- can't access them from user
1198 code.
1199+ There's nothing Tim could find in the MS C or platform SDK libraries that
1200 can worm around this.
Tim Peters86821b22001-01-07 21:19:34 +00001201+ MS fgets locks/unlocks only once per line; it's the only hook we have.
1202
1203So we use fgets for speed(!), despite that it's painful.
1204
1205MS realloc is also slow.
1206
Tim Petersf29b64d2001-01-15 06:33:19 +00001207Reports from other platforms on this method vs getc_unlocked (which MS doesn't
1208have):
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001209 Linux a wash
1210 Solaris a wash
1211 Tru64 Unix getline_via_fgets significantly faster
Tim Peters86821b22001-01-07 21:19:34 +00001212
Tim Petersf29b64d2001-01-15 06:33:19 +00001213CAUTION: The C std isn't clear about this: in those cases where fgets
1214writes something into the buffer, can it write into any position beyond the
1215required trailing null byte? MSVC 6 fgets does not, and no platform is (yet)
1216known on which it does; and it would be a strange way to code fgets. Still,
1217getline_via_fgets may not work correctly if it does. The std test
1218test_bufio.py should fail if platform fgets() routinely writes beyond the
1219trailing null byte. #define DONT_USE_FGETS_IN_GETLINE to disable this code.
Tim Peters86821b22001-01-07 21:19:34 +00001220**************************************************************************/
1221
Tim Petersf29b64d2001-01-15 06:33:19 +00001222/* Use this routine if told to, or by default on non-get_unlocked()
1223 * platforms unless told not to. Yikes! Let's spell that out:
1224 * On a platform with getc_unlocked():
1225 * By default, use getc_unlocked().
1226 * If you want to use fgets() instead, #define USE_FGETS_IN_GETLINE.
1227 * On a platform without getc_unlocked():
1228 * By default, use fgets().
1229 * If you don't want to use fgets(), #define DONT_USE_FGETS_IN_GETLINE.
1230 */
1231#if !defined(USE_FGETS_IN_GETLINE) && !defined(HAVE_GETC_UNLOCKED)
1232#define USE_FGETS_IN_GETLINE
Tim Peters86821b22001-01-07 21:19:34 +00001233#endif
1234
Tim Petersf29b64d2001-01-15 06:33:19 +00001235#if defined(DONT_USE_FGETS_IN_GETLINE) && defined(USE_FGETS_IN_GETLINE)
1236#undef USE_FGETS_IN_GETLINE
1237#endif
1238
1239#ifdef USE_FGETS_IN_GETLINE
Tim Peters86821b22001-01-07 21:19:34 +00001240static PyObject*
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +00001241getline_via_fgets(PyFileObject *f, FILE *fp)
Tim Peters86821b22001-01-07 21:19:34 +00001242{
Tim Peters15b83852001-01-08 00:53:12 +00001243/* INITBUFSIZE is the maximum line length that lets us get away with the fast
Tim Peters142297a2001-01-15 10:36:56 +00001244 * no-realloc, one-fgets()-call path. Boosting it isn't free, because we have
1245 * to fill this much of the buffer with a known value in order to figure out
1246 * how much of the buffer fgets() overwrites. So if INITBUFSIZE is larger
1247 * than "most" lines, we waste time filling unused buffer slots. 100 is
1248 * surely adequate for most peoples' email archives, chewing over source code,
1249 * etc -- "regular old text files".
1250 * MAXBUFSIZE is the maximum line length that lets us get away with the less
1251 * fast (but still zippy) no-realloc, two-fgets()-call path. See above for
1252 * cautions about boosting that. 300 was chosen because the worst real-life
1253 * text-crunching job reported on Python-Dev was a mail-log crawler where over
1254 * half the lines were 254 chars.
Tim Peters15b83852001-01-08 00:53:12 +00001255 */
Tim Peters142297a2001-01-15 10:36:56 +00001256#define INITBUFSIZE 100
1257#define MAXBUFSIZE 300
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001258 char* p; /* temp */
1259 char buf[MAXBUFSIZE];
1260 PyObject* v; /* the string object result */
1261 char* pvfree; /* address of next free slot */
1262 char* pvend; /* address one beyond last free slot */
1263 size_t nfree; /* # of free buffer slots; pvend-pvfree */
1264 size_t total_v_size; /* total # of slots in buffer */
1265 size_t increment; /* amount to increment the buffer */
1266 size_t prev_v_size;
Tim Peters86821b22001-01-07 21:19:34 +00001267
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001268 /* Optimize for normal case: avoid _PyString_Resize if at all
1269 * possible via first reading into stack buffer "buf".
1270 */
1271 total_v_size = INITBUFSIZE; /* start small and pray */
1272 pvfree = buf;
1273 for (;;) {
1274 FILE_BEGIN_ALLOW_THREADS(f)
1275 pvend = buf + total_v_size;
1276 nfree = pvend - pvfree;
1277 memset(pvfree, '\n', nfree);
1278 assert(nfree < INT_MAX); /* Should be atmost MAXBUFSIZE */
1279 p = fgets(pvfree, (int)nfree, fp);
1280 FILE_END_ALLOW_THREADS(f)
Tim Peters15b83852001-01-08 00:53:12 +00001281
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001282 if (p == NULL) {
1283 clearerr(fp);
1284 if (PyErr_CheckSignals())
1285 return NULL;
1286 v = PyString_FromStringAndSize(buf, pvfree - buf);
1287 return v;
1288 }
1289 /* fgets read *something* */
1290 p = memchr(pvfree, '\n', nfree);
1291 if (p != NULL) {
1292 /* Did the \n come from fgets or from us?
1293 * Since fgets stops at the first \n, and then writes
1294 * \0, if it's from fgets a \0 must be next. But if
1295 * that's so, it could not have come from us, since
1296 * the \n's we filled the buffer with have only more
1297 * \n's to the right.
1298 */
1299 if (p+1 < pvend && *(p+1) == '\0') {
1300 /* It's from fgets: we win! In particular,
1301 * we haven't done any mallocs yet, and can
1302 * build the final result on the first try.
1303 */
1304 ++p; /* include \n from fgets */
1305 }
1306 else {
1307 /* Must be from us: fgets didn't fill the
1308 * buffer and didn't find a newline, so it
1309 * must be the last and newline-free line of
1310 * the file.
1311 */
1312 assert(p > pvfree && *(p-1) == '\0');
1313 --p; /* don't include \0 from fgets */
1314 }
1315 v = PyString_FromStringAndSize(buf, p - buf);
1316 return v;
1317 }
1318 /* yuck: fgets overwrote all the newlines, i.e. the entire
1319 * buffer. So this line isn't over yet, or maybe it is but
1320 * we're exactly at EOF. If we haven't already, try using the
1321 * rest of the stack buffer.
1322 */
1323 assert(*(pvend-1) == '\0');
1324 if (pvfree == buf) {
1325 pvfree = pvend - 1; /* overwrite trailing null */
1326 total_v_size = MAXBUFSIZE;
1327 }
1328 else
1329 break;
1330 }
Tim Peters142297a2001-01-15 10:36:56 +00001331
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001332 /* The stack buffer isn't big enough; malloc a string object and read
1333 * into its buffer.
1334 */
1335 total_v_size = MAXBUFSIZE << 1;
1336 v = PyString_FromStringAndSize((char*)NULL, (int)total_v_size);
1337 if (v == NULL)
1338 return v;
1339 /* copy over everything except the last null byte */
1340 memcpy(BUF(v), buf, MAXBUFSIZE-1);
1341 pvfree = BUF(v) + MAXBUFSIZE - 1;
Tim Peters86821b22001-01-07 21:19:34 +00001342
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001343 /* Keep reading stuff into v; if it ever ends successfully, break
1344 * after setting p one beyond the end of the line. The code here is
1345 * very much like the code above, except reads into v's buffer; see
1346 * the code above for detailed comments about the logic.
1347 */
1348 for (;;) {
1349 FILE_BEGIN_ALLOW_THREADS(f)
1350 pvend = BUF(v) + total_v_size;
1351 nfree = pvend - pvfree;
1352 memset(pvfree, '\n', nfree);
1353 assert(nfree < INT_MAX);
1354 p = fgets(pvfree, (int)nfree, fp);
1355 FILE_END_ALLOW_THREADS(f)
Tim Peters86821b22001-01-07 21:19:34 +00001356
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001357 if (p == NULL) {
1358 clearerr(fp);
1359 if (PyErr_CheckSignals()) {
1360 Py_DECREF(v);
1361 return NULL;
1362 }
1363 p = pvfree;
1364 break;
1365 }
1366 p = memchr(pvfree, '\n', nfree);
1367 if (p != NULL) {
1368 if (p+1 < pvend && *(p+1) == '\0') {
1369 /* \n came from fgets */
1370 ++p;
1371 break;
1372 }
1373 /* \n came from us; last line of file, no newline */
1374 assert(p > pvfree && *(p-1) == '\0');
1375 --p;
1376 break;
1377 }
1378 /* expand buffer and try again */
1379 assert(*(pvend-1) == '\0');
1380 increment = total_v_size >> 2; /* mild exponential growth */
1381 prev_v_size = total_v_size;
1382 total_v_size += increment;
1383 /* check for overflow */
1384 if (total_v_size <= prev_v_size ||
1385 total_v_size > PY_SSIZE_T_MAX) {
1386 PyErr_SetString(PyExc_OverflowError,
1387 "line is longer than a Python string can hold");
1388 Py_DECREF(v);
1389 return NULL;
1390 }
1391 if (_PyString_Resize(&v, (int)total_v_size) < 0)
1392 return NULL;
1393 /* overwrite the trailing null byte */
1394 pvfree = BUF(v) + (prev_v_size - 1);
1395 }
1396 if (BUF(v) + total_v_size != p && _PyString_Resize(&v, p - BUF(v)))
1397 return NULL;
1398 return v;
Tim Peters86821b22001-01-07 21:19:34 +00001399#undef INITBUFSIZE
Tim Peters142297a2001-01-15 10:36:56 +00001400#undef MAXBUFSIZE
Tim Peters86821b22001-01-07 21:19:34 +00001401}
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001402#endif /* ifdef USE_FGETS_IN_GETLINE */
Guido van Rossumfdf95dd1997-05-05 22:15:02 +00001403
Guido van Rossum0bd24411991-04-04 15:21:57 +00001404/* Internal routine to get a line.
1405 Size argument interpretation:
1406 > 0: max length;
Guido van Rossum86282062001-01-08 01:26:47 +00001407 <= 0: read arbitrary line
Guido van Rossumce5ba841991-03-06 13:06:18 +00001408*/
1409
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001410static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +00001411get_line(PyFileObject *f, int n)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001412{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001413 FILE *fp = f->f_fp;
1414 int c;
1415 char *buf, *end;
1416 size_t total_v_size; /* total # of slots in buffer */
1417 size_t used_v_size; /* # used slots in buffer */
1418 size_t increment; /* amount to increment the buffer */
1419 PyObject *v;
1420 int newlinetypes = f->f_newlinetypes;
1421 int skipnextlf = f->f_skipnextlf;
1422 int univ_newline = f->f_univ_newline;
Guido van Rossum0bd24411991-04-04 15:21:57 +00001423
Jack Jansen7b8c7542002-04-14 20:12:41 +00001424#if defined(USE_FGETS_IN_GETLINE)
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001425 if (n <= 0 && !univ_newline )
1426 return getline_via_fgets(f, fp);
Tim Peters86821b22001-01-07 21:19:34 +00001427#endif
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001428 total_v_size = n > 0 ? n : 100;
1429 v = PyString_FromStringAndSize((char *)NULL, total_v_size);
1430 if (v == NULL)
1431 return NULL;
1432 buf = BUF(v);
1433 end = buf + total_v_size;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001434
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001435 for (;;) {
1436 FILE_BEGIN_ALLOW_THREADS(f)
1437 FLOCKFILE(fp);
1438 if (univ_newline) {
1439 c = 'x'; /* Shut up gcc warning */
1440 while ( buf != end && (c = GETC(fp)) != EOF ) {
1441 if (skipnextlf ) {
1442 skipnextlf = 0;
1443 if (c == '\n') {
1444 /* Seeing a \n here with
1445 * skipnextlf true means we
1446 * saw a \r before.
1447 */
1448 newlinetypes |= NEWLINE_CRLF;
1449 c = GETC(fp);
1450 if (c == EOF) break;
1451 } else {
1452 newlinetypes |= NEWLINE_CR;
1453 }
1454 }
1455 if (c == '\r') {
1456 skipnextlf = 1;
1457 c = '\n';
1458 } else if ( c == '\n')
1459 newlinetypes |= NEWLINE_LF;
1460 *buf++ = c;
1461 if (c == '\n') break;
1462 }
Gregory P. Smithb2ac4d62012-06-25 20:57:36 -07001463 if (c == EOF) {
1464 if (ferror(fp) && errno == EINTR) {
1465 FUNLOCKFILE(fp);
1466 FILE_ABORT_ALLOW_THREADS(f)
1467 f->f_newlinetypes = newlinetypes;
1468 f->f_skipnextlf = skipnextlf;
1469
1470 if (PyErr_CheckSignals()) {
1471 Py_DECREF(v);
1472 return NULL;
1473 }
1474 /* We executed Python signal handlers and got no exception.
1475 * Now back to reading the line where we left off. */
1476 clearerr(fp);
1477 continue;
1478 }
1479 if (skipnextlf)
1480 newlinetypes |= NEWLINE_CR;
1481 }
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001482 } else /* If not universal newlines use the normal loop */
1483 while ((c = GETC(fp)) != EOF &&
1484 (*buf++ = c) != '\n' &&
1485 buf != end)
1486 ;
1487 FUNLOCKFILE(fp);
1488 FILE_END_ALLOW_THREADS(f)
1489 f->f_newlinetypes = newlinetypes;
1490 f->f_skipnextlf = skipnextlf;
1491 if (c == '\n')
1492 break;
1493 if (c == EOF) {
1494 if (ferror(fp)) {
Gregory P. Smithb2ac4d62012-06-25 20:57:36 -07001495 if (errno == EINTR) {
1496 if (PyErr_CheckSignals()) {
1497 Py_DECREF(v);
1498 return NULL;
1499 }
1500 /* We executed Python signal handlers and got no exception.
1501 * Now back to reading the line where we left off. */
1502 clearerr(fp);
1503 continue;
1504 }
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001505 PyErr_SetFromErrno(PyExc_IOError);
1506 clearerr(fp);
1507 Py_DECREF(v);
1508 return NULL;
1509 }
1510 clearerr(fp);
1511 if (PyErr_CheckSignals()) {
1512 Py_DECREF(v);
1513 return NULL;
1514 }
1515 break;
1516 }
1517 /* Must be because buf == end */
1518 if (n > 0)
1519 break;
1520 used_v_size = total_v_size;
1521 increment = total_v_size >> 2; /* mild exponential growth */
1522 total_v_size += increment;
1523 if (total_v_size > PY_SSIZE_T_MAX) {
1524 PyErr_SetString(PyExc_OverflowError,
1525 "line is longer than a Python string can hold");
1526 Py_DECREF(v);
1527 return NULL;
1528 }
1529 if (_PyString_Resize(&v, total_v_size) < 0)
1530 return NULL;
1531 buf = BUF(v) + used_v_size;
1532 end = BUF(v) + total_v_size;
1533 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001534
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001535 used_v_size = buf - BUF(v);
1536 if (used_v_size != total_v_size && _PyString_Resize(&v, used_v_size))
1537 return NULL;
1538 return v;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001539}
1540
Guido van Rossum0bd24411991-04-04 15:21:57 +00001541/* External C interface */
1542
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001543PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +00001544PyFile_GetLine(PyObject *f, int n)
Guido van Rossum0bd24411991-04-04 15:21:57 +00001545{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001546 PyObject *result;
Guido van Rossum4ddf0a02001-01-07 20:51:39 +00001547
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001548 if (f == NULL) {
1549 PyErr_BadInternalCall();
1550 return NULL;
1551 }
Guido van Rossum4ddf0a02001-01-07 20:51:39 +00001552
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001553 if (PyFile_Check(f)) {
1554 PyFileObject *fo = (PyFileObject *)f;
1555 if (fo->f_fp == NULL)
1556 return err_closed();
1557 if (!fo->readable)
1558 return err_mode("reading");
1559 /* refuse to mix with f.next() */
1560 if (fo->f_buf != NULL &&
1561 (fo->f_bufend - fo->f_bufptr) > 0 &&
1562 fo->f_buf[0] != '\0')
1563 return err_iterbuffered();
1564 result = get_line(fo, n);
1565 }
1566 else {
1567 PyObject *reader;
1568 PyObject *args;
Guido van Rossum4ddf0a02001-01-07 20:51:39 +00001569
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001570 reader = PyObject_GetAttrString(f, "readline");
1571 if (reader == NULL)
1572 return NULL;
1573 if (n <= 0)
1574 args = PyTuple_New(0);
1575 else
1576 args = Py_BuildValue("(i)", n);
1577 if (args == NULL) {
1578 Py_DECREF(reader);
1579 return NULL;
1580 }
1581 result = PyEval_CallObject(reader, args);
1582 Py_DECREF(reader);
1583 Py_DECREF(args);
1584 if (result != NULL && !PyString_Check(result) &&
1585 !PyUnicode_Check(result)) {
1586 Py_DECREF(result);
1587 result = NULL;
1588 PyErr_SetString(PyExc_TypeError,
1589 "object.readline() returned non-string");
1590 }
1591 }
Guido van Rossum4ddf0a02001-01-07 20:51:39 +00001592
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001593 if (n < 0 && result != NULL && PyString_Check(result)) {
1594 char *s = PyString_AS_STRING(result);
1595 Py_ssize_t len = PyString_GET_SIZE(result);
1596 if (len == 0) {
1597 Py_DECREF(result);
1598 result = NULL;
1599 PyErr_SetString(PyExc_EOFError,
1600 "EOF when reading a line");
1601 }
1602 else if (s[len-1] == '\n') {
1603 if (result->ob_refcnt == 1) {
1604 if (_PyString_Resize(&result, len-1))
1605 return NULL;
1606 }
1607 else {
1608 PyObject *v;
1609 v = PyString_FromStringAndSize(s, len-1);
1610 Py_DECREF(result);
1611 result = v;
1612 }
1613 }
1614 }
Martin v. Löwisaf6a27a2003-01-03 19:16:14 +00001615#ifdef Py_USING_UNICODE
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001616 if (n < 0 && result != NULL && PyUnicode_Check(result)) {
1617 Py_UNICODE *s = PyUnicode_AS_UNICODE(result);
1618 Py_ssize_t len = PyUnicode_GET_SIZE(result);
1619 if (len == 0) {
1620 Py_DECREF(result);
1621 result = NULL;
1622 PyErr_SetString(PyExc_EOFError,
1623 "EOF when reading a line");
1624 }
1625 else if (s[len-1] == '\n') {
1626 if (result->ob_refcnt == 1)
1627 PyUnicode_Resize(&result, len-1);
1628 else {
1629 PyObject *v;
1630 v = PyUnicode_FromUnicode(s, len-1);
1631 Py_DECREF(result);
1632 result = v;
1633 }
1634 }
1635 }
Martin v. Löwisaf6a27a2003-01-03 19:16:14 +00001636#endif
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001637 return result;
Guido van Rossum0bd24411991-04-04 15:21:57 +00001638}
1639
1640/* Python method */
1641
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001642static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +00001643file_readline(PyFileObject *f, PyObject *args)
Guido van Rossum0bd24411991-04-04 15:21:57 +00001644{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001645 int n = -1;
Guido van Rossum0bd24411991-04-04 15:21:57 +00001646
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001647 if (f->f_fp == NULL)
1648 return err_closed();
1649 if (!f->readable)
1650 return err_mode("reading");
1651 /* refuse to mix with f.next() */
1652 if (f->f_buf != NULL &&
1653 (f->f_bufend - f->f_bufptr) > 0 &&
1654 f->f_buf[0] != '\0')
1655 return err_iterbuffered();
1656 if (!PyArg_ParseTuple(args, "|i:readline", &n))
1657 return NULL;
1658 if (n == 0)
1659 return PyString_FromString("");
1660 if (n < 0)
1661 n = 0;
1662 return get_line(f, n);
Guido van Rossum0bd24411991-04-04 15:21:57 +00001663}
1664
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001665static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +00001666file_readlines(PyFileObject *f, PyObject *args)
Guido van Rossumce5ba841991-03-06 13:06:18 +00001667{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001668 long sizehint = 0;
1669 PyObject *list = NULL;
1670 PyObject *line;
1671 char small_buffer[SMALLCHUNK];
1672 char *buffer = small_buffer;
1673 size_t buffersize = SMALLCHUNK;
1674 PyObject *big_buffer = NULL;
1675 size_t nfilled = 0;
1676 size_t nread;
1677 size_t totalread = 0;
1678 char *p, *q, *end;
1679 int err;
Gregory P. Smithb2ac4d62012-06-25 20:57:36 -07001680 int shortread = 0; /* bool, did the previous read come up short? */
Guido van Rossum0bd24411991-04-04 15:21:57 +00001681
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001682 if (f->f_fp == NULL)
1683 return err_closed();
1684 if (!f->readable)
1685 return err_mode("reading");
1686 /* refuse to mix with f.next() */
1687 if (f->f_buf != NULL &&
1688 (f->f_bufend - f->f_bufptr) > 0 &&
1689 f->f_buf[0] != '\0')
1690 return err_iterbuffered();
1691 if (!PyArg_ParseTuple(args, "|l:readlines", &sizehint))
1692 return NULL;
1693 if ((list = PyList_New(0)) == NULL)
1694 return NULL;
1695 for (;;) {
1696 if (shortread)
1697 nread = 0;
1698 else {
1699 FILE_BEGIN_ALLOW_THREADS(f)
1700 errno = 0;
1701 nread = Py_UniversalNewlineFread(buffer+nfilled,
1702 buffersize-nfilled, f->f_fp, (PyObject *)f);
1703 FILE_END_ALLOW_THREADS(f)
1704 shortread = (nread < buffersize-nfilled);
1705 }
1706 if (nread == 0) {
1707 sizehint = 0;
1708 if (!ferror(f->f_fp))
1709 break;
Gregory P. Smithb2ac4d62012-06-25 20:57:36 -07001710 if (errno == EINTR) {
1711 if (PyErr_CheckSignals()) {
1712 goto error;
1713 }
1714 clearerr(f->f_fp);
1715 shortread = 0;
1716 continue;
1717 }
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001718 PyErr_SetFromErrno(PyExc_IOError);
1719 clearerr(f->f_fp);
1720 goto error;
1721 }
1722 totalread += nread;
1723 p = (char *)memchr(buffer+nfilled, '\n', nread);
1724 if (p == NULL) {
1725 /* Need a larger buffer to fit this line */
1726 nfilled += nread;
1727 buffersize *= 2;
1728 if (buffersize > PY_SSIZE_T_MAX) {
1729 PyErr_SetString(PyExc_OverflowError,
1730 "line is longer than a Python string can hold");
1731 goto error;
1732 }
1733 if (big_buffer == NULL) {
1734 /* Create the big buffer */
1735 big_buffer = PyString_FromStringAndSize(
1736 NULL, buffersize);
1737 if (big_buffer == NULL)
1738 goto error;
1739 buffer = PyString_AS_STRING(big_buffer);
1740 memcpy(buffer, small_buffer, nfilled);
1741 }
1742 else {
1743 /* Grow the big buffer */
1744 if ( _PyString_Resize(&big_buffer, buffersize) < 0 )
1745 goto error;
1746 buffer = PyString_AS_STRING(big_buffer);
1747 }
1748 continue;
1749 }
1750 end = buffer+nfilled+nread;
1751 q = buffer;
1752 do {
1753 /* Process complete lines */
1754 p++;
1755 line = PyString_FromStringAndSize(q, p-q);
1756 if (line == NULL)
1757 goto error;
1758 err = PyList_Append(list, line);
1759 Py_DECREF(line);
1760 if (err != 0)
1761 goto error;
1762 q = p;
1763 p = (char *)memchr(q, '\n', end-q);
1764 } while (p != NULL);
1765 /* Move the remaining incomplete line to the start */
1766 nfilled = end-q;
1767 memmove(buffer, q, nfilled);
1768 if (sizehint > 0)
1769 if (totalread >= (size_t)sizehint)
1770 break;
1771 }
1772 if (nfilled != 0) {
1773 /* Partial last line */
1774 line = PyString_FromStringAndSize(buffer, nfilled);
1775 if (line == NULL)
1776 goto error;
1777 if (sizehint > 0) {
1778 /* Need to complete the last line */
1779 PyObject *rest = get_line(f, 0);
1780 if (rest == NULL) {
1781 Py_DECREF(line);
1782 goto error;
1783 }
1784 PyString_Concat(&line, rest);
1785 Py_DECREF(rest);
1786 if (line == NULL)
1787 goto error;
1788 }
1789 err = PyList_Append(list, line);
1790 Py_DECREF(line);
1791 if (err != 0)
1792 goto error;
1793 }
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +00001794
1795cleanup:
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001796 Py_XDECREF(big_buffer);
1797 return list;
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +00001798
1799error:
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001800 Py_CLEAR(list);
1801 goto cleanup;
Guido van Rossumce5ba841991-03-06 13:06:18 +00001802}
1803
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001804static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +00001805file_write(PyFileObject *f, PyObject *args)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001806{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001807 Py_buffer pbuf;
Victor Stinnercaafd772010-09-08 10:51:01 +00001808 const char *s;
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001809 Py_ssize_t n, n2;
Victor Stinnercaafd772010-09-08 10:51:01 +00001810 PyObject *encoded = NULL;
Serhiy Storchaka78ad6582013-12-17 17:32:20 +02001811 int err_flag = 0, err;
Victor Stinnercaafd772010-09-08 10:51:01 +00001812
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001813 if (f->f_fp == NULL)
1814 return err_closed();
1815 if (!f->writable)
1816 return err_mode("writing");
1817 if (f->f_binary) {
1818 if (!PyArg_ParseTuple(args, "s*", &pbuf))
1819 return NULL;
1820 s = pbuf.buf;
1821 n = pbuf.len;
Victor Stinnercaafd772010-09-08 10:51:01 +00001822 }
1823 else {
Victor Stinnercaafd772010-09-08 10:51:01 +00001824 PyObject *text;
1825 if (!PyArg_ParseTuple(args, "O", &text))
1826 return NULL;
1827
1828 if (PyString_Check(text)) {
1829 s = PyString_AS_STRING(text);
1830 n = PyString_GET_SIZE(text);
Benjamin Peterson5ca88d22013-01-01 23:04:16 -06001831#ifdef Py_USING_UNICODE
Victor Stinnercaafd772010-09-08 10:51:01 +00001832 } else if (PyUnicode_Check(text)) {
Benjamin Peterson5ca88d22013-01-01 23:04:16 -06001833 const char *encoding, *errors;
Victor Stinnercaafd772010-09-08 10:51:01 +00001834 if (f->f_encoding != Py_None)
1835 encoding = PyString_AS_STRING(f->f_encoding);
1836 else
1837 encoding = PyUnicode_GetDefaultEncoding();
1838 if (f->f_errors != Py_None)
1839 errors = PyString_AS_STRING(f->f_errors);
1840 else
1841 errors = "strict";
1842 encoded = PyUnicode_AsEncodedString(text, encoding, errors);
1843 if (encoded == NULL)
1844 return NULL;
1845 s = PyString_AS_STRING(encoded);
1846 n = PyString_GET_SIZE(encoded);
Benjamin Peterson5ca88d22013-01-01 23:04:16 -06001847#endif
Victor Stinnercaafd772010-09-08 10:51:01 +00001848 } else {
1849 if (PyObject_AsCharBuffer(text, &s, &n))
1850 return NULL;
1851 }
1852 }
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001853 f->f_softspace = 0;
1854 FILE_BEGIN_ALLOW_THREADS(f)
1855 errno = 0;
1856 n2 = fwrite(s, 1, n, f->f_fp);
Serhiy Storchaka78ad6582013-12-17 17:32:20 +02001857 if (n2 != n || ferror(f->f_fp)) {
1858 err_flag = 1;
Serhiy Storchaka6d562312013-12-17 14:40:06 +02001859 err = errno;
Serhiy Storchaka78ad6582013-12-17 17:32:20 +02001860 }
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001861 FILE_END_ALLOW_THREADS(f)
Victor Stinnercaafd772010-09-08 10:51:01 +00001862 Py_XDECREF(encoded);
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001863 if (f->f_binary)
1864 PyBuffer_Release(&pbuf);
Serhiy Storchaka78ad6582013-12-17 17:32:20 +02001865 if (err_flag) {
Serhiy Storchaka6d562312013-12-17 14:40:06 +02001866 errno = err;
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001867 PyErr_SetFromErrno(PyExc_IOError);
1868 clearerr(f->f_fp);
1869 return NULL;
1870 }
1871 Py_INCREF(Py_None);
1872 return Py_None;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001873}
1874
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001875static PyObject *
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001876file_writelines(PyFileObject *f, PyObject *seq)
Guido van Rossum5a2a6831993-10-25 09:59:04 +00001877{
Guido van Rossumee70ad12000-03-13 16:27:06 +00001878#define CHUNKSIZE 1000
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001879 PyObject *list, *line;
1880 PyObject *it; /* iter(seq) */
1881 PyObject *result;
1882 int index, islist;
1883 Py_ssize_t i, j, nwritten, len;
Guido van Rossumee70ad12000-03-13 16:27:06 +00001884
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001885 assert(seq != NULL);
1886 if (f->f_fp == NULL)
1887 return err_closed();
1888 if (!f->writable)
1889 return err_mode("writing");
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001890
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001891 result = NULL;
1892 list = NULL;
1893 islist = PyList_Check(seq);
1894 if (islist)
1895 it = NULL;
1896 else {
1897 it = PyObject_GetIter(seq);
1898 if (it == NULL) {
1899 PyErr_SetString(PyExc_TypeError,
1900 "writelines() requires an iterable argument");
1901 return NULL;
1902 }
1903 /* From here on, fail by going to error, to reclaim "it". */
1904 list = PyList_New(CHUNKSIZE);
1905 if (list == NULL)
1906 goto error;
1907 }
Guido van Rossumee70ad12000-03-13 16:27:06 +00001908
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001909 /* Strategy: slurp CHUNKSIZE lines into a private list,
1910 checking that they are all strings, then write that list
1911 without holding the interpreter lock, then come back for more. */
1912 for (index = 0; ; index += CHUNKSIZE) {
1913 if (islist) {
1914 Py_XDECREF(list);
1915 list = PyList_GetSlice(seq, index, index+CHUNKSIZE);
1916 if (list == NULL)
1917 goto error;
1918 j = PyList_GET_SIZE(list);
1919 }
1920 else {
1921 for (j = 0; j < CHUNKSIZE; j++) {
1922 line = PyIter_Next(it);
1923 if (line == NULL) {
1924 if (PyErr_Occurred())
1925 goto error;
1926 break;
1927 }
1928 PyList_SetItem(list, j, line);
1929 }
Benjamin Petersonbf775542010-10-16 19:20:12 +00001930 /* The iterator might have closed the file on us. */
1931 if (f->f_fp == NULL) {
1932 err_closed();
1933 goto error;
1934 }
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001935 }
1936 if (j == 0)
1937 break;
Guido van Rossumee70ad12000-03-13 16:27:06 +00001938
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001939 /* Check that all entries are indeed strings. If not,
1940 apply the same rules as for file.write() and
1941 convert the results to strings. This is slow, but
1942 seems to be the only way since all conversion APIs
1943 could potentially execute Python code. */
1944 for (i = 0; i < j; i++) {
1945 PyObject *v = PyList_GET_ITEM(list, i);
1946 if (!PyString_Check(v)) {
1947 const char *buffer;
Antoine Pitroub0acc1b2014-05-08 19:26:04 +02001948 int res;
1949 if (f->f_binary) {
1950 res = PyObject_AsReadBuffer(v, (const void**)&buffer, &len);
1951 } else {
1952 res = PyObject_AsCharBuffer(v, &buffer, &len);
1953 }
1954 if (res) {
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001955 PyErr_SetString(PyExc_TypeError,
1956 "writelines() argument must be a sequence of strings");
1957 goto error;
1958 }
1959 line = PyString_FromStringAndSize(buffer,
1960 len);
1961 if (line == NULL)
1962 goto error;
1963 Py_DECREF(v);
1964 PyList_SET_ITEM(list, i, line);
1965 }
1966 }
Marc-André Lemburg6ef68b52000-08-25 22:39:50 +00001967
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001968 /* Since we are releasing the global lock, the
1969 following code may *not* execute Python code. */
1970 f->f_softspace = 0;
1971 FILE_BEGIN_ALLOW_THREADS(f)
1972 errno = 0;
1973 for (i = 0; i < j; i++) {
1974 line = PyList_GET_ITEM(list, i);
1975 len = PyString_GET_SIZE(line);
1976 nwritten = fwrite(PyString_AS_STRING(line),
1977 1, len, f->f_fp);
1978 if (nwritten != len) {
1979 FILE_ABORT_ALLOW_THREADS(f)
1980 PyErr_SetFromErrno(PyExc_IOError);
1981 clearerr(f->f_fp);
1982 goto error;
1983 }
1984 }
1985 FILE_END_ALLOW_THREADS(f)
Guido van Rossumee70ad12000-03-13 16:27:06 +00001986
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001987 if (j < CHUNKSIZE)
1988 break;
1989 }
Guido van Rossumee70ad12000-03-13 16:27:06 +00001990
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001991 Py_INCREF(Py_None);
1992 result = Py_None;
Guido van Rossumee70ad12000-03-13 16:27:06 +00001993 error:
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001994 Py_XDECREF(list);
1995 Py_XDECREF(it);
1996 return result;
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001997#undef CHUNKSIZE
Guido van Rossum5a2a6831993-10-25 09:59:04 +00001998}
1999
Guido van Rossum7a6e9592002-08-06 15:55:28 +00002000static PyObject *
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00002001file_self(PyFileObject *f)
Guido van Rossum7a6e9592002-08-06 15:55:28 +00002002{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002003 if (f->f_fp == NULL)
2004 return err_closed();
2005 Py_INCREF(f);
2006 return (PyObject *)f;
Guido van Rossum7a6e9592002-08-06 15:55:28 +00002007}
2008
Georg Brandl98b40ad2006-06-08 14:50:21 +00002009static PyObject *
Georg Brandla9916b52008-05-17 22:11:54 +00002010file_xreadlines(PyFileObject *f)
2011{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002012 if (PyErr_WarnPy3k("f.xreadlines() not supported in 3.x, "
2013 "try 'for line in f' instead", 1) < 0)
2014 return NULL;
2015 return file_self(f);
Georg Brandla9916b52008-05-17 22:11:54 +00002016}
2017
2018static PyObject *
Georg Brandlad61bc82008-02-23 15:11:18 +00002019file_exit(PyObject *f, PyObject *args)
Georg Brandl98b40ad2006-06-08 14:50:21 +00002020{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002021 PyObject *ret = PyObject_CallMethod(f, "close", NULL);
2022 if (!ret)
2023 /* If error occurred, pass through */
2024 return NULL;
2025 Py_DECREF(ret);
2026 /* We cannot return the result of close since a true
2027 * value will be interpreted as "yes, swallow the
2028 * exception if one was raised inside the with block". */
2029 Py_RETURN_NONE;
Georg Brandl98b40ad2006-06-08 14:50:21 +00002030}
2031
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002032PyDoc_STRVAR(readline_doc,
Tim Petersefc3a3a2001-09-20 07:55:22 +00002033"readline([size]) -> next line from the file, as a string.\n"
2034"\n"
2035"Retain newline. A non-negative size argument limits the maximum\n"
2036"number of bytes to return (an incomplete line may be returned then).\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002037"Return an empty string at EOF.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00002038
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002039PyDoc_STRVAR(read_doc,
Tim Petersefc3a3a2001-09-20 07:55:22 +00002040"read([size]) -> read at most size bytes, returned as a string.\n"
2041"\n"
Gustavo Niemeyer786ddb22002-12-16 18:12:53 +00002042"If the size argument is negative or omitted, read until EOF is reached.\n"
2043"Notice that when in non-blocking mode, less data than what was requested\n"
2044"may be returned, even if no size parameter was given.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00002045
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002046PyDoc_STRVAR(write_doc,
Tim Petersefc3a3a2001-09-20 07:55:22 +00002047"write(str) -> None. Write string str to file.\n"
2048"\n"
2049"Note that due to buffering, flush() or close() may be needed before\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002050"the file on disk reflects the data written.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00002051
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002052PyDoc_STRVAR(fileno_doc,
Tim Petersefc3a3a2001-09-20 07:55:22 +00002053"fileno() -> integer \"file descriptor\".\n"
2054"\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002055"This is needed for lower-level file interfaces, such os.read().");
Tim Petersefc3a3a2001-09-20 07:55:22 +00002056
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002057PyDoc_STRVAR(seek_doc,
Tim Petersefc3a3a2001-09-20 07:55:22 +00002058"seek(offset[, whence]) -> None. Move to new file position.\n"
2059"\n"
2060"Argument offset is a byte count. Optional argument whence defaults to\n"
2061"0 (offset from start of file, offset should be >= 0); other values are 1\n"
2062"(move relative to current position, positive or negative), and 2 (move\n"
2063"relative to end of file, usually negative, although many platforms allow\n"
Martin v. Löwis849a9722003-10-18 09:38:01 +00002064"seeking beyond the end of a file). If the file is opened in text mode,\n"
2065"only offsets returned by tell() are legal. Use of other offsets causes\n"
2066"undefined behavior."
Tim Petersefc3a3a2001-09-20 07:55:22 +00002067"\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002068"Note that not all file objects are seekable.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00002069
Guido van Rossumd7047b31995-01-02 19:07:15 +00002070#ifdef HAVE_FTRUNCATE
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002071PyDoc_STRVAR(truncate_doc,
Tim Petersefc3a3a2001-09-20 07:55:22 +00002072"truncate([size]) -> None. Truncate the file to at most size bytes.\n"
2073"\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002074"Size defaults to the current file position, as returned by tell().");
Guido van Rossumd7047b31995-01-02 19:07:15 +00002075#endif
Tim Petersefc3a3a2001-09-20 07:55:22 +00002076
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002077PyDoc_STRVAR(tell_doc,
2078"tell() -> current file position, an integer (may be a long integer).");
Tim Petersefc3a3a2001-09-20 07:55:22 +00002079
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002080PyDoc_STRVAR(readinto_doc,
2081"readinto() -> Undocumented. Don't use this; it may go away.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00002082
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002083PyDoc_STRVAR(readlines_doc,
Tim Petersefc3a3a2001-09-20 07:55:22 +00002084"readlines([size]) -> list of strings, each a line from the file.\n"
2085"\n"
2086"Call readline() repeatedly and return a list of the lines so read.\n"
2087"The optional size argument, if given, is an approximate bound on the\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002088"total number of bytes in the lines returned.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00002089
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002090PyDoc_STRVAR(xreadlines_doc,
Guido van Rossum7a6e9592002-08-06 15:55:28 +00002091"xreadlines() -> returns self.\n"
Tim Petersefc3a3a2001-09-20 07:55:22 +00002092"\n"
Guido van Rossum7a6e9592002-08-06 15:55:28 +00002093"For backward compatibility. File objects now include the performance\n"
2094"optimizations previously implemented in the xreadlines module.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00002095
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002096PyDoc_STRVAR(writelines_doc,
Tim Peters2c9aa5e2001-09-23 04:06:05 +00002097"writelines(sequence_of_strings) -> None. Write the strings to the file.\n"
Tim Petersefc3a3a2001-09-20 07:55:22 +00002098"\n"
Tim Peters2c9aa5e2001-09-23 04:06:05 +00002099"Note that newlines are not added. The sequence can be any iterable object\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002100"producing strings. This is equivalent to calling write() for each string.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00002101
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002102PyDoc_STRVAR(flush_doc,
2103"flush() -> None. Flush the internal I/O buffer.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00002104
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002105PyDoc_STRVAR(close_doc,
Tim Petersefc3a3a2001-09-20 07:55:22 +00002106"close() -> None or (perhaps) an integer. Close the file.\n"
2107"\n"
Guido van Rossum77f6a652002-04-03 22:41:51 +00002108"Sets data attribute .closed to True. A closed file cannot be used for\n"
Tim Petersefc3a3a2001-09-20 07:55:22 +00002109"further I/O operations. close() may be called more than once without\n"
2110"error. Some kinds of file objects (for example, opened by popen())\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002111"may return an exit status upon closing.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00002112
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002113PyDoc_STRVAR(isatty_doc,
2114"isatty() -> true or false. True if the file is connected to a tty device.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00002115
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00002116PyDoc_STRVAR(enter_doc,
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002117 "__enter__() -> self.");
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00002118
Georg Brandl98b40ad2006-06-08 14:50:21 +00002119PyDoc_STRVAR(exit_doc,
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002120 "__exit__(*excinfo) -> None. Closes the file.");
Georg Brandl98b40ad2006-06-08 14:50:21 +00002121
Tim Petersefc3a3a2001-09-20 07:55:22 +00002122static PyMethodDef file_methods[] = {
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002123 {"readline", (PyCFunction)file_readline, METH_VARARGS, readline_doc},
2124 {"read", (PyCFunction)file_read, METH_VARARGS, read_doc},
2125 {"write", (PyCFunction)file_write, METH_VARARGS, write_doc},
2126 {"fileno", (PyCFunction)file_fileno, METH_NOARGS, fileno_doc},
2127 {"seek", (PyCFunction)file_seek, METH_VARARGS, seek_doc},
Tim Petersefc3a3a2001-09-20 07:55:22 +00002128#ifdef HAVE_FTRUNCATE
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002129 {"truncate", (PyCFunction)file_truncate, METH_VARARGS, truncate_doc},
Tim Petersefc3a3a2001-09-20 07:55:22 +00002130#endif
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002131 {"tell", (PyCFunction)file_tell, METH_NOARGS, tell_doc},
2132 {"readinto", (PyCFunction)file_readinto, METH_VARARGS, readinto_doc},
2133 {"readlines", (PyCFunction)file_readlines, METH_VARARGS, readlines_doc},
2134 {"xreadlines",(PyCFunction)file_xreadlines, METH_NOARGS, xreadlines_doc},
2135 {"writelines",(PyCFunction)file_writelines, METH_O, writelines_doc},
2136 {"flush", (PyCFunction)file_flush, METH_NOARGS, flush_doc},
2137 {"close", (PyCFunction)file_close, METH_NOARGS, close_doc},
2138 {"isatty", (PyCFunction)file_isatty, METH_NOARGS, isatty_doc},
2139 {"__enter__", (PyCFunction)file_self, METH_NOARGS, enter_doc},
2140 {"__exit__", (PyCFunction)file_exit, METH_VARARGS, exit_doc},
2141 {NULL, NULL} /* sentinel */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002142};
2143
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002144#define OFF(x) offsetof(PyFileObject, x)
Guido van Rossumb6775db1994-08-01 11:34:53 +00002145
Guido van Rossum6f799372001-09-20 20:46:19 +00002146static PyMemberDef file_memberlist[] = {
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002147 {"mode", T_OBJECT, OFF(f_mode), RO,
2148 "file mode ('r', 'U', 'w', 'a', possibly with 'b' or '+' added)"},
2149 {"name", T_OBJECT, OFF(f_name), RO,
2150 "file name"},
2151 {"encoding", T_OBJECT, OFF(f_encoding), RO,
2152 "file encoding"},
2153 {"errors", T_OBJECT, OFF(f_errors), RO,
2154 "Unicode error handler"},
2155 /* getattr(f, "closed") is implemented without this table */
2156 {NULL} /* Sentinel */
Guido van Rossumb6775db1994-08-01 11:34:53 +00002157};
2158
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002159static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00002160get_closed(PyFileObject *f, void *closure)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002161{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002162 return PyBool_FromLong((long)(f->f_fp == 0));
Guido van Rossumb6775db1994-08-01 11:34:53 +00002163}
Jack Jansen7b8c7542002-04-14 20:12:41 +00002164static PyObject *
2165get_newlines(PyFileObject *f, void *closure)
2166{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002167 switch (f->f_newlinetypes) {
2168 case NEWLINE_UNKNOWN:
2169 Py_INCREF(Py_None);
2170 return Py_None;
2171 case NEWLINE_CR:
2172 return PyString_FromString("\r");
2173 case NEWLINE_LF:
2174 return PyString_FromString("\n");
2175 case NEWLINE_CR|NEWLINE_LF:
2176 return Py_BuildValue("(ss)", "\r", "\n");
2177 case NEWLINE_CRLF:
2178 return PyString_FromString("\r\n");
2179 case NEWLINE_CR|NEWLINE_CRLF:
2180 return Py_BuildValue("(ss)", "\r", "\r\n");
2181 case NEWLINE_LF|NEWLINE_CRLF:
2182 return Py_BuildValue("(ss)", "\n", "\r\n");
2183 case NEWLINE_CR|NEWLINE_LF|NEWLINE_CRLF:
2184 return Py_BuildValue("(sss)", "\r", "\n", "\r\n");
2185 default:
2186 PyErr_Format(PyExc_SystemError,
2187 "Unknown newlines value 0x%x\n",
2188 f->f_newlinetypes);
2189 return NULL;
2190 }
Jack Jansen7b8c7542002-04-14 20:12:41 +00002191}
Guido van Rossumb6775db1994-08-01 11:34:53 +00002192
Georg Brandl65bb42d2008-03-21 20:38:24 +00002193static PyObject *
2194get_softspace(PyFileObject *f, void *closure)
2195{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002196 if (PyErr_WarnPy3k("file.softspace not supported in 3.x", 1) < 0)
2197 return NULL;
2198 return PyInt_FromLong(f->f_softspace);
Georg Brandl65bb42d2008-03-21 20:38:24 +00002199}
2200
2201static int
2202set_softspace(PyFileObject *f, PyObject *value)
2203{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002204 int new;
2205 if (PyErr_WarnPy3k("file.softspace not supported in 3.x", 1) < 0)
2206 return -1;
Georg Brandl65bb42d2008-03-21 20:38:24 +00002207
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002208 if (value == NULL) {
2209 PyErr_SetString(PyExc_TypeError,
2210 "can't delete softspace attribute");
2211 return -1;
2212 }
Georg Brandl65bb42d2008-03-21 20:38:24 +00002213
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002214 new = PyInt_AsLong(value);
2215 if (new == -1 && PyErr_Occurred())
2216 return -1;
2217 f->f_softspace = new;
2218 return 0;
Georg Brandl65bb42d2008-03-21 20:38:24 +00002219}
2220
Guido van Rossum32d34c82001-09-20 21:45:26 +00002221static PyGetSetDef file_getsetlist[] = {
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002222 {"closed", (getter)get_closed, NULL, "True if the file is closed"},
2223 {"newlines", (getter)get_newlines, NULL,
2224 "end-of-line convention used in this file"},
2225 {"softspace", (getter)get_softspace, (setter)set_softspace,
2226 "flag indicating that a space needs to be printed; used by print"},
2227 {0},
Tim Peters6d6c1a32001-08-02 04:15:00 +00002228};
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002229
Neal Norwitzd8b995f2002-08-06 21:50:54 +00002230static void
Guido van Rossum7a6e9592002-08-06 15:55:28 +00002231drop_readahead(PyFileObject *f)
Guido van Rossum65967252001-04-21 13:20:18 +00002232{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002233 if (f->f_buf != NULL) {
2234 PyMem_Free(f->f_buf);
2235 f->f_buf = NULL;
2236 }
Guido van Rossum65967252001-04-21 13:20:18 +00002237}
2238
Tim Petersf1827cf2003-09-07 03:30:18 +00002239/* Make sure that file has a readahead buffer with at least one byte
2240 (unless at EOF) and no more than bufsize. Returns negative value on
Georg Brandled02eb62006-03-31 20:31:02 +00002241 error, will set MemoryError if bufsize bytes cannot be allocated. */
Neal Norwitzd8b995f2002-08-06 21:50:54 +00002242static int
Benjamin Peterson95bc0e42014-09-30 21:17:15 -04002243readahead(PyFileObject *f, Py_ssize_t bufsize)
Neal Norwitzd8b995f2002-08-06 21:50:54 +00002244{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002245 Py_ssize_t chunksize;
Guido van Rossum7a6e9592002-08-06 15:55:28 +00002246
Serhiy Storchaka6401e562017-11-10 12:58:55 +02002247 assert(f->unlocked_count == 0);
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002248 if (f->f_buf != NULL) {
2249 if( (f->f_bufend - f->f_bufptr) >= 1)
2250 return 0;
2251 else
2252 drop_readahead(f);
2253 }
2254 if ((f->f_buf = (char *)PyMem_Malloc(bufsize)) == NULL) {
2255 PyErr_NoMemory();
2256 return -1;
2257 }
2258 FILE_BEGIN_ALLOW_THREADS(f)
2259 errno = 0;
2260 chunksize = Py_UniversalNewlineFread(
2261 f->f_buf, bufsize, f->f_fp, (PyObject *)f);
2262 FILE_END_ALLOW_THREADS(f)
2263 if (chunksize == 0) {
2264 if (ferror(f->f_fp)) {
2265 PyErr_SetFromErrno(PyExc_IOError);
2266 clearerr(f->f_fp);
2267 drop_readahead(f);
2268 return -1;
2269 }
2270 }
2271 f->f_bufptr = f->f_buf;
2272 f->f_bufend = f->f_buf + chunksize;
2273 return 0;
Guido van Rossum7a6e9592002-08-06 15:55:28 +00002274}
2275
2276/* Used by file_iternext. The returned string will start with 'skip'
Tim Petersf1827cf2003-09-07 03:30:18 +00002277 uninitialized bytes followed by the remainder of the line. Don't be
2278 horrified by the recursive call: maximum recursion depth is limited by
Guido van Rossum7a6e9592002-08-06 15:55:28 +00002279 logarithmic buffer growth to about 50 even when reading a 1gb line. */
2280
Gregory P. Smithdd96db62008-06-09 04:58:54 +00002281static PyStringObject *
Benjamin Peterson95bc0e42014-09-30 21:17:15 -04002282readahead_get_line_skip(PyFileObject *f, Py_ssize_t skip, Py_ssize_t bufsize)
Neal Norwitzd8b995f2002-08-06 21:50:54 +00002283{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002284 PyStringObject* s;
2285 char *bufptr;
2286 char *buf;
2287 Py_ssize_t len;
Guido van Rossum7a6e9592002-08-06 15:55:28 +00002288
Serhiy Storchaka6401e562017-11-10 12:58:55 +02002289 if (f->unlocked_count > 0) {
2290 PyErr_SetString(PyExc_IOError,
2291 "next() called during concurrent "
2292 "operation on the same file object");
2293 return NULL;
2294 }
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002295 if (f->f_buf == NULL)
2296 if (readahead(f, bufsize) < 0)
2297 return NULL;
Guido van Rossum7a6e9592002-08-06 15:55:28 +00002298
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002299 len = f->f_bufend - f->f_bufptr;
2300 if (len == 0)
2301 return (PyStringObject *)
2302 PyString_FromStringAndSize(NULL, skip);
2303 bufptr = (char *)memchr(f->f_bufptr, '\n', len);
2304 if (bufptr != NULL) {
2305 bufptr++; /* Count the '\n' */
2306 len = bufptr - f->f_bufptr;
2307 s = (PyStringObject *)
Benjamin Peterson95bc0e42014-09-30 21:17:15 -04002308 PyString_FromStringAndSize(NULL, skip + len);
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002309 if (s == NULL)
2310 return NULL;
Benjamin Peterson95bc0e42014-09-30 21:17:15 -04002311 memcpy(PyString_AS_STRING(s) + skip, f->f_bufptr, len);
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002312 f->f_bufptr = bufptr;
2313 if (bufptr == f->f_bufend)
2314 drop_readahead(f);
2315 } else {
2316 bufptr = f->f_bufptr;
2317 buf = f->f_buf;
2318 f->f_buf = NULL; /* Force new readahead buffer */
Benjamin Peterson95bc0e42014-09-30 21:17:15 -04002319 assert(len <= PY_SSIZE_T_MAX - skip);
2320 s = readahead_get_line_skip(f, skip + len, bufsize + (bufsize>>2));
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002321 if (s == NULL) {
2322 PyMem_Free(buf);
2323 return NULL;
2324 }
Benjamin Peterson95bc0e42014-09-30 21:17:15 -04002325 memcpy(PyString_AS_STRING(s) + skip, bufptr, len);
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002326 PyMem_Free(buf);
2327 }
2328 return s;
Guido van Rossum7a6e9592002-08-06 15:55:28 +00002329}
2330
2331/* A larger buffer size may actually decrease performance. */
2332#define READAHEAD_BUFSIZE 8192
2333
2334static PyObject *
2335file_iternext(PyFileObject *f)
2336{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002337 PyStringObject* l;
Guido van Rossum7a6e9592002-08-06 15:55:28 +00002338
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002339 if (f->f_fp == NULL)
2340 return err_closed();
2341 if (!f->readable)
2342 return err_mode("reading");
Guido van Rossum7a6e9592002-08-06 15:55:28 +00002343
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002344 l = readahead_get_line_skip(f, 0, READAHEAD_BUFSIZE);
2345 if (l == NULL || PyString_GET_SIZE(l) == 0) {
2346 Py_XDECREF(l);
2347 return NULL;
2348 }
2349 return (PyObject *)l;
Guido van Rossum7a6e9592002-08-06 15:55:28 +00002350}
2351
2352
Tim Peters59c9a642001-09-13 05:38:56 +00002353static PyObject *
2354file_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
2355{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002356 PyObject *self;
2357 static PyObject *not_yet_string;
Tim Peters44410012001-09-14 03:26:08 +00002358
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002359 assert(type != NULL && type->tp_alloc != NULL);
Tim Peters44410012001-09-14 03:26:08 +00002360
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002361 if (not_yet_string == NULL) {
2362 not_yet_string = PyString_InternFromString("<uninitialized file>");
2363 if (not_yet_string == NULL)
2364 return NULL;
2365 }
Tim Peters44410012001-09-14 03:26:08 +00002366
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002367 self = type->tp_alloc(type, 0);
2368 if (self != NULL) {
2369 /* Always fill in the name and mode, so that nobody else
2370 needs to special-case NULLs there. */
2371 Py_INCREF(not_yet_string);
2372 ((PyFileObject *)self)->f_name = not_yet_string;
2373 Py_INCREF(not_yet_string);
2374 ((PyFileObject *)self)->f_mode = not_yet_string;
2375 Py_INCREF(Py_None);
2376 ((PyFileObject *)self)->f_encoding = Py_None;
2377 Py_INCREF(Py_None);
2378 ((PyFileObject *)self)->f_errors = Py_None;
2379 ((PyFileObject *)self)->weakreflist = NULL;
2380 ((PyFileObject *)self)->unlocked_count = 0;
2381 }
2382 return self;
Tim Peters44410012001-09-14 03:26:08 +00002383}
2384
2385static int
2386file_init(PyObject *self, PyObject *args, PyObject *kwds)
2387{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002388 PyFileObject *foself = (PyFileObject *)self;
2389 int ret = 0;
2390 static char *kwlist[] = {"name", "mode", "buffering", 0};
2391 char *name = NULL;
2392 char *mode = "r";
2393 int bufsize = -1;
2394 int wideargument = 0;
Hirokazu Yamamoto5c3dd9a2009-06-29 15:52:21 +00002395#ifdef MS_WINDOWS
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002396 PyObject *po;
Hirokazu Yamamoto5c3dd9a2009-06-29 15:52:21 +00002397#endif
Tim Peters44410012001-09-14 03:26:08 +00002398
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002399 assert(PyFile_Check(self));
2400 if (foself->f_fp != NULL) {
2401 /* Have to close the existing file first. */
2402 PyObject *closeresult = file_close(foself);
2403 if (closeresult == NULL)
2404 return -1;
2405 Py_DECREF(closeresult);
2406 }
Tim Peters59c9a642001-09-13 05:38:56 +00002407
Hirokazu Yamamotob24bb272009-05-17 02:52:09 +00002408#ifdef MS_WINDOWS
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002409 if (PyArg_ParseTupleAndKeywords(args, kwds, "U|si:file",
Serhiy Storchaka3c9ce742016-07-01 23:34:44 +03002410 kwlist, &po, &mode, &bufsize) &&
2411 wcslen(PyUnicode_AS_UNICODE(po)) == (size_t)PyUnicode_GET_SIZE(po)) {
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002412 wideargument = 1;
2413 if (fill_file_fields(foself, NULL, po, mode,
2414 fclose) == NULL)
2415 goto Error;
2416 } else {
2417 /* Drop the argument parsing error as narrow
2418 strings are also valid. */
2419 PyErr_Clear();
2420 }
Mark Hammondc2e85bd2002-10-03 05:10:39 +00002421#endif
2422
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002423 if (!wideargument) {
2424 PyObject *o_name;
Nicholas Bastinabce8a62004-03-21 20:24:07 +00002425
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002426 if (!PyArg_ParseTupleAndKeywords(args, kwds, "et|si:file", kwlist,
2427 Py_FileSystemDefaultEncoding,
2428 &name,
2429 &mode, &bufsize))
2430 return -1;
Nicholas Bastinabce8a62004-03-21 20:24:07 +00002431
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002432 /* We parse again to get the name as a PyObject */
2433 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|si:file",
2434 kwlist, &o_name, &mode,
2435 &bufsize))
2436 goto Error;
Nicholas Bastinabce8a62004-03-21 20:24:07 +00002437
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002438 if (fill_file_fields(foself, NULL, o_name, mode,
2439 fclose) == NULL)
2440 goto Error;
2441 }
2442 if (open_the_file(foself, name, mode) == NULL)
2443 goto Error;
2444 foself->f_setbuf = NULL;
2445 PyFile_SetBufSize(self, bufsize);
2446 goto Done;
Tim Peters44410012001-09-14 03:26:08 +00002447
2448Error:
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002449 ret = -1;
2450 /* fall through */
Tim Peters44410012001-09-14 03:26:08 +00002451Done:
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002452 PyMem_Free(name); /* free the encoded string */
2453 return ret;
Tim Peters59c9a642001-09-13 05:38:56 +00002454}
2455
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002456PyDoc_VAR(file_doc) =
2457PyDoc_STR(
Tim Peters59c9a642001-09-13 05:38:56 +00002458"file(name[, mode[, buffering]]) -> file object\n"
2459"\n"
2460"Open a file. The mode can be 'r', 'w' or 'a' for reading (default),\n"
2461"writing or appending. The file will be created if it doesn't exist\n"
2462"when opened for writing or appending; it will be truncated when\n"
2463"opened for writing. Add a 'b' to the mode for binary files.\n"
2464"Add a '+' to the mode to allow simultaneous reading and writing.\n"
2465"If the buffering argument is given, 0 means unbuffered, 1 means line\n"
Skip Montanaro4e3ebe02007-12-08 14:37:43 +00002466"buffered, and larger numbers specify the buffer size. The preferred way\n"
2467"to open a file is with the builtin open() function.\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002468)
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002469PyDoc_STR(
Barry Warsaw4be55b52002-05-22 20:37:53 +00002470"Add a 'U' to mode to open the file for input with universal newline\n"
2471"support. Any line ending in the input file will be seen as a '\\n'\n"
2472"in Python. Also, a file so opened gains the attribute 'newlines';\n"
2473"the value for this attribute is one of None (no newline read yet),\n"
2474"'\\r', '\\n', '\\r\\n' or a tuple containing all the newline types seen.\n"
2475"\n"
2476"'U' cannot be combined with 'w' or '+' mode.\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002477);
Tim Peters59c9a642001-09-13 05:38:56 +00002478
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002479PyTypeObject PyFile_Type = {
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002480 PyVarObject_HEAD_INIT(&PyType_Type, 0)
2481 "file",
2482 sizeof(PyFileObject),
2483 0,
2484 (destructor)file_dealloc, /* tp_dealloc */
2485 0, /* tp_print */
2486 0, /* tp_getattr */
2487 0, /* tp_setattr */
2488 0, /* tp_compare */
2489 (reprfunc)file_repr, /* tp_repr */
2490 0, /* tp_as_number */
2491 0, /* tp_as_sequence */
2492 0, /* tp_as_mapping */
2493 0, /* tp_hash */
2494 0, /* tp_call */
2495 0, /* tp_str */
2496 PyObject_GenericGetAttr, /* tp_getattro */
2497 /* softspace is writable: we must supply tp_setattro */
2498 PyObject_GenericSetAttr, /* tp_setattro */
2499 0, /* tp_as_buffer */
2500 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_WEAKREFS, /* tp_flags */
2501 file_doc, /* tp_doc */
2502 0, /* tp_traverse */
2503 0, /* tp_clear */
2504 0, /* tp_richcompare */
2505 offsetof(PyFileObject, weakreflist), /* tp_weaklistoffset */
2506 (getiterfunc)file_self, /* tp_iter */
2507 (iternextfunc)file_iternext, /* tp_iternext */
2508 file_methods, /* tp_methods */
2509 file_memberlist, /* tp_members */
2510 file_getsetlist, /* tp_getset */
2511 0, /* tp_base */
2512 0, /* tp_dict */
2513 0, /* tp_descr_get */
2514 0, /* tp_descr_set */
2515 0, /* tp_dictoffset */
2516 file_init, /* tp_init */
2517 PyType_GenericAlloc, /* tp_alloc */
2518 file_new, /* tp_new */
2519 PyObject_Del, /* tp_free */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002520};
Guido van Rossumeb183da1991-04-04 10:44:06 +00002521
2522/* Interface for the 'soft space' between print items. */
2523
2524int
Fred Drakefd99de62000-07-09 05:02:18 +00002525PyFile_SoftSpace(PyObject *f, int newflag)
Guido van Rossumeb183da1991-04-04 10:44:06 +00002526{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002527 long oldflag = 0;
2528 if (f == NULL) {
2529 /* Do nothing */
2530 }
2531 else if (PyFile_Check(f)) {
2532 oldflag = ((PyFileObject *)f)->f_softspace;
2533 ((PyFileObject *)f)->f_softspace = newflag;
2534 }
2535 else {
2536 PyObject *v;
2537 v = PyObject_GetAttrString(f, "softspace");
2538 if (v == NULL)
2539 PyErr_Clear();
2540 else {
2541 if (PyInt_Check(v))
2542 oldflag = PyInt_AsLong(v);
2543 assert(oldflag < INT_MAX);
2544 Py_DECREF(v);
2545 }
2546 v = PyInt_FromLong((long)newflag);
2547 if (v == NULL)
2548 PyErr_Clear();
2549 else {
2550 if (PyObject_SetAttrString(f, "softspace", v) != 0)
2551 PyErr_Clear();
2552 Py_DECREF(v);
2553 }
2554 }
2555 return (int)oldflag;
Guido van Rossumeb183da1991-04-04 10:44:06 +00002556}
Guido van Rossum3165fe61992-09-25 21:59:05 +00002557
2558/* Interfaces to write objects/strings to file-like objects */
2559
2560int
Fred Drakefd99de62000-07-09 05:02:18 +00002561PyFile_WriteObject(PyObject *v, PyObject *f, int flags)
Guido van Rossum3165fe61992-09-25 21:59:05 +00002562{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002563 PyObject *writer, *value, *args, *result;
2564 if (f == NULL) {
2565 PyErr_SetString(PyExc_TypeError, "writeobject with NULL file");
2566 return -1;
2567 }
2568 else if (PyFile_Check(f)) {
2569 PyFileObject *fobj = (PyFileObject *) f;
Fred Drake086a0f72004-03-19 15:22:36 +00002570#ifdef Py_USING_UNICODE
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002571 PyObject *enc = fobj->f_encoding;
2572 int result;
Fred Drake086a0f72004-03-19 15:22:36 +00002573#endif
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002574 if (fobj->f_fp == NULL) {
2575 err_closed();
2576 return -1;
2577 }
Martin v. Löwis5467d4c2003-05-10 07:10:12 +00002578#ifdef Py_USING_UNICODE
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002579 if ((flags & Py_PRINT_RAW) &&
2580 PyUnicode_Check(v) && enc != Py_None) {
2581 char *cenc = PyString_AS_STRING(enc);
2582 char *errors = fobj->f_errors == Py_None ?
2583 "strict" : PyString_AS_STRING(fobj->f_errors);
2584 value = PyUnicode_AsEncodedString(v, cenc, errors);
2585 if (value == NULL)
2586 return -1;
2587 } else {
2588 value = v;
2589 Py_INCREF(value);
2590 }
2591 result = file_PyObject_Print(value, fobj, flags);
2592 Py_DECREF(value);
2593 return result;
Martin v. Löwis5467d4c2003-05-10 07:10:12 +00002594#else
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002595 return file_PyObject_Print(v, fobj, flags);
Martin v. Löwis5467d4c2003-05-10 07:10:12 +00002596#endif
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002597 }
2598 writer = PyObject_GetAttrString(f, "write");
2599 if (writer == NULL)
2600 return -1;
2601 if (flags & Py_PRINT_RAW) {
2602 if (PyUnicode_Check(v)) {
2603 value = v;
2604 Py_INCREF(value);
2605 } else
2606 value = PyObject_Str(v);
2607 }
2608 else
2609 value = PyObject_Repr(v);
2610 if (value == NULL) {
2611 Py_DECREF(writer);
2612 return -1;
2613 }
2614 args = PyTuple_Pack(1, value);
2615 if (args == NULL) {
2616 Py_DECREF(value);
2617 Py_DECREF(writer);
2618 return -1;
2619 }
2620 result = PyEval_CallObject(writer, args);
2621 Py_DECREF(args);
2622 Py_DECREF(value);
2623 Py_DECREF(writer);
2624 if (result == NULL)
2625 return -1;
2626 Py_DECREF(result);
2627 return 0;
Guido van Rossum3165fe61992-09-25 21:59:05 +00002628}
2629
Guido van Rossum27a60b11997-05-22 22:25:11 +00002630int
Tim Petersc1bbcb82001-11-28 22:13:25 +00002631PyFile_WriteString(const char *s, PyObject *f)
Guido van Rossum3165fe61992-09-25 21:59:05 +00002632{
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +00002633
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002634 if (f == NULL) {
2635 /* Should be caused by a pre-existing error */
2636 if (!PyErr_Occurred())
2637 PyErr_SetString(PyExc_SystemError,
2638 "null file for PyFile_WriteString");
2639 return -1;
2640 }
2641 else if (PyFile_Check(f)) {
2642 PyFileObject *fobj = (PyFileObject *) f;
2643 FILE *fp = PyFile_AsFile(f);
2644 if (fp == NULL) {
2645 err_closed();
2646 return -1;
2647 }
2648 FILE_BEGIN_ALLOW_THREADS(fobj)
2649 fputs(s, fp);
2650 FILE_END_ALLOW_THREADS(fobj)
2651 return 0;
2652 }
2653 else if (!PyErr_Occurred()) {
2654 PyObject *v = PyString_FromString(s);
2655 int err;
2656 if (v == NULL)
2657 return -1;
2658 err = PyFile_WriteObject(v, f, Py_PRINT_RAW);
2659 Py_DECREF(v);
2660 return err;
2661 }
2662 else
2663 return -1;
Guido van Rossum3165fe61992-09-25 21:59:05 +00002664}
Andrew M. Kuchling06051ed2000-07-13 23:56:54 +00002665
2666/* Try to get a file-descriptor from a Python object. If the object
2667 is an integer or long integer, its value is returned. If not, the
2668 object's fileno() method is called if it exists; the method must return
2669 an integer or long integer, which is returned as the file descriptor value.
2670 -1 is returned on failure.
2671*/
2672
2673int PyObject_AsFileDescriptor(PyObject *o)
2674{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002675 int fd;
2676 PyObject *meth;
Andrew M. Kuchling06051ed2000-07-13 23:56:54 +00002677
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002678 if (PyInt_Check(o)) {
Serhiy Storchaka74f49ab2013-01-19 12:55:39 +02002679 fd = _PyInt_AsInt(o);
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002680 }
2681 else if (PyLong_Check(o)) {
Serhiy Storchaka74f49ab2013-01-19 12:55:39 +02002682 fd = _PyLong_AsInt(o);
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002683 }
2684 else if ((meth = PyObject_GetAttrString(o, "fileno")) != NULL)
2685 {
2686 PyObject *fno = PyEval_CallObject(meth, NULL);
2687 Py_DECREF(meth);
2688 if (fno == NULL)
2689 return -1;
Tim Peters86821b22001-01-07 21:19:34 +00002690
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002691 if (PyInt_Check(fno)) {
Serhiy Storchaka74f49ab2013-01-19 12:55:39 +02002692 fd = _PyInt_AsInt(fno);
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002693 Py_DECREF(fno);
2694 }
2695 else if (PyLong_Check(fno)) {
Serhiy Storchaka74f49ab2013-01-19 12:55:39 +02002696 fd = _PyLong_AsInt(fno);
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002697 Py_DECREF(fno);
2698 }
2699 else {
2700 PyErr_SetString(PyExc_TypeError,
2701 "fileno() returned a non-integer");
2702 Py_DECREF(fno);
2703 return -1;
2704 }
2705 }
2706 else {
2707 PyErr_SetString(PyExc_TypeError,
Serhiy Storchaka6401e562017-11-10 12:58:55 +02002708 "argument must be an int, or have a fileno() method");
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002709 return -1;
2710 }
Andrew M. Kuchling06051ed2000-07-13 23:56:54 +00002711
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002712 if (fd < 0) {
2713 PyErr_Format(PyExc_ValueError,
2714 "file descriptor cannot be a negative integer (%i)",
2715 fd);
2716 return -1;
2717 }
2718 return fd;
Andrew M. Kuchling06051ed2000-07-13 23:56:54 +00002719}
Jack Jansen7b8c7542002-04-14 20:12:41 +00002720
Jack Jansen7b8c7542002-04-14 20:12:41 +00002721/* From here on we need access to the real fgets and fread */
2722#undef fgets
2723#undef fread
2724
2725/*
2726** Py_UniversalNewlineFgets is an fgets variation that understands
2727** all of \r, \n and \r\n conventions.
2728** The stream should be opened in binary mode.
2729** If fobj is NULL the routine always does newline conversion, and
2730** it may peek one char ahead to gobble the second char in \r\n.
2731** If fobj is non-NULL it must be a PyFileObject. In this case there
2732** is no readahead but in stead a flag is used to skip a following
2733** \n on the next read. Also, if the file is open in binary mode
2734** the whole conversion is skipped. Finally, the routine keeps track of
2735** the different types of newlines seen.
2736** Note that we need no error handling: fgets() treats error and eof
2737** identically.
2738*/
2739char *
2740Py_UniversalNewlineFgets(char *buf, int n, FILE *stream, PyObject *fobj)
2741{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002742 char *p = buf;
2743 int c;
2744 int newlinetypes = 0;
2745 int skipnextlf = 0;
2746 int univ_newline = 1;
Tim Peters058b1412002-04-21 07:29:14 +00002747
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002748 if (fobj) {
2749 if (!PyFile_Check(fobj)) {
2750 errno = ENXIO; /* What can you do... */
2751 return NULL;
2752 }
2753 univ_newline = ((PyFileObject *)fobj)->f_univ_newline;
2754 if ( !univ_newline )
2755 return fgets(buf, n, stream);
2756 newlinetypes = ((PyFileObject *)fobj)->f_newlinetypes;
2757 skipnextlf = ((PyFileObject *)fobj)->f_skipnextlf;
2758 }
2759 FLOCKFILE(stream);
2760 c = 'x'; /* Shut up gcc warning */
2761 while (--n > 0 && (c = GETC(stream)) != EOF ) {
2762 if (skipnextlf ) {
2763 skipnextlf = 0;
2764 if (c == '\n') {
2765 /* Seeing a \n here with skipnextlf true
2766 ** means we saw a \r before.
2767 */
2768 newlinetypes |= NEWLINE_CRLF;
2769 c = GETC(stream);
2770 if (c == EOF) break;
2771 } else {
2772 /*
2773 ** Note that c == EOF also brings us here,
2774 ** so we're okay if the last char in the file
2775 ** is a CR.
2776 */
2777 newlinetypes |= NEWLINE_CR;
2778 }
2779 }
2780 if (c == '\r') {
2781 /* A \r is translated into a \n, and we skip
2782 ** an adjacent \n, if any. We don't set the
2783 ** newlinetypes flag until we've seen the next char.
2784 */
2785 skipnextlf = 1;
2786 c = '\n';
2787 } else if ( c == '\n') {
2788 newlinetypes |= NEWLINE_LF;
2789 }
2790 *p++ = c;
2791 if (c == '\n') break;
2792 }
2793 if ( c == EOF && skipnextlf )
2794 newlinetypes |= NEWLINE_CR;
2795 FUNLOCKFILE(stream);
2796 *p = '\0';
2797 if (fobj) {
2798 ((PyFileObject *)fobj)->f_newlinetypes = newlinetypes;
2799 ((PyFileObject *)fobj)->f_skipnextlf = skipnextlf;
2800 } else if ( skipnextlf ) {
2801 /* If we have no file object we cannot save the
2802 ** skipnextlf flag. We have to readahead, which
2803 ** will cause a pause if we're reading from an
2804 ** interactive stream, but that is very unlikely
2805 ** unless we're doing something silly like
2806 ** execfile("/dev/tty").
2807 */
2808 c = GETC(stream);
2809 if ( c != '\n' )
2810 ungetc(c, stream);
2811 }
2812 if (p == buf)
2813 return NULL;
2814 return buf;
Jack Jansen7b8c7542002-04-14 20:12:41 +00002815}
2816
2817/*
2818** Py_UniversalNewlineFread is an fread variation that understands
2819** all of \r, \n and \r\n conventions.
2820** The stream should be opened in binary mode.
2821** fobj must be a PyFileObject. In this case there
2822** is no readahead but in stead a flag is used to skip a following
2823** \n on the next read. Also, if the file is open in binary mode
2824** the whole conversion is skipped. Finally, the routine keeps track of
2825** the different types of newlines seen.
2826*/
2827size_t
Tim Peters058b1412002-04-21 07:29:14 +00002828Py_UniversalNewlineFread(char *buf, size_t n,
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002829 FILE *stream, PyObject *fobj)
Jack Jansen7b8c7542002-04-14 20:12:41 +00002830{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002831 char *dst = buf;
2832 PyFileObject *f = (PyFileObject *)fobj;
2833 int newlinetypes, skipnextlf;
Tim Peters058b1412002-04-21 07:29:14 +00002834
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002835 assert(buf != NULL);
2836 assert(stream != NULL);
Tim Peters058b1412002-04-21 07:29:14 +00002837
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002838 if (!fobj || !PyFile_Check(fobj)) {
2839 errno = ENXIO; /* What can you do... */
2840 return 0;
2841 }
2842 if (!f->f_univ_newline)
2843 return fread(buf, 1, n, stream);
2844 newlinetypes = f->f_newlinetypes;
2845 skipnextlf = f->f_skipnextlf;
2846 /* Invariant: n is the number of bytes remaining to be filled
2847 * in the buffer.
2848 */
2849 while (n) {
2850 size_t nread;
2851 int shortread;
2852 char *src = dst;
Tim Peters058b1412002-04-21 07:29:14 +00002853
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002854 nread = fread(dst, 1, n, stream);
2855 assert(nread <= n);
2856 if (nread == 0)
2857 break;
Neal Norwitzcb3319f2003-02-09 01:10:02 +00002858
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002859 n -= nread; /* assuming 1 byte out for each in; will adjust */
2860 shortread = n != 0; /* true iff EOF or error */
2861 while (nread--) {
2862 char c = *src++;
2863 if (c == '\r') {
2864 /* Save as LF and set flag to skip next LF. */
2865 *dst++ = '\n';
2866 skipnextlf = 1;
2867 }
2868 else if (skipnextlf && c == '\n') {
2869 /* Skip LF, and remember we saw CR LF. */
2870 skipnextlf = 0;
2871 newlinetypes |= NEWLINE_CRLF;
2872 ++n;
2873 }
2874 else {
2875 /* Normal char to be stored in buffer. Also
2876 * update the newlinetypes flag if either this
2877 * is an LF or the previous char was a CR.
2878 */
2879 if (c == '\n')
2880 newlinetypes |= NEWLINE_LF;
2881 else if (skipnextlf)
2882 newlinetypes |= NEWLINE_CR;
2883 *dst++ = c;
2884 skipnextlf = 0;
2885 }
2886 }
2887 if (shortread) {
2888 /* If this is EOF, update type flags. */
2889 if (skipnextlf && feof(stream))
2890 newlinetypes |= NEWLINE_CR;
2891 break;
2892 }
2893 }
2894 f->f_newlinetypes = newlinetypes;
2895 f->f_skipnextlf = skipnextlf;
2896 return dst - buf;
Jack Jansen7b8c7542002-04-14 20:12:41 +00002897}
Anthony Baxterac6bd462006-04-13 02:06:09 +00002898
2899#ifdef __cplusplus
2900}
2901#endif