blob: 270b28264a8f46e115202892888efc44aa514ac4 [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;
Nir Soffer830daae2017-12-07 22:25:39 +0200124 int res;
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000125 if (f->f_fp == NULL)
126 return f;
Nir Soffer830daae2017-12-07 22:25:39 +0200127
128 Py_BEGIN_ALLOW_THREADS
129 res = fstat(fileno(f->f_fp), &buf);
130 Py_END_ALLOW_THREADS
131
132 if (res == 0 && S_ISDIR(buf.st_mode)) {
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000133 char *msg = strerror(EISDIR);
134 PyObject *exc = PyObject_CallFunction(PyExc_IOError, "(isO)",
135 EISDIR, msg, f->f_name);
136 PyErr_SetObject(PyExc_IOError, exc);
137 Py_XDECREF(exc);
138 return NULL;
139 }
Neil Schemenauered19b882002-03-23 02:06:50 +0000140#endif
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000141 return f;
Neil Schemenauered19b882002-03-23 02:06:50 +0000142}
143
Tim Peters59c9a642001-09-13 05:38:56 +0000144
145static PyObject *
Nicholas Bastinabce8a62004-03-21 20:24:07 +0000146fill_file_fields(PyFileObject *f, FILE *fp, PyObject *name, char *mode,
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000147 int (*close)(FILE *))
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000148{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000149 assert(name != NULL);
150 assert(f != NULL);
151 assert(PyFile_Check(f));
152 assert(f->f_fp == NULL);
Tim Peters44410012001-09-14 03:26:08 +0000153
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000154 Py_DECREF(f->f_name);
155 Py_DECREF(f->f_mode);
156 Py_DECREF(f->f_encoding);
157 Py_DECREF(f->f_errors);
Nicholas Bastinabce8a62004-03-21 20:24:07 +0000158
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000159 Py_INCREF(name);
160 f->f_name = name;
Nicholas Bastinabce8a62004-03-21 20:24:07 +0000161
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000162 f->f_mode = PyString_FromString(mode);
Tim Peters44410012001-09-14 03:26:08 +0000163
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000164 f->f_close = close;
165 f->f_softspace = 0;
166 f->f_binary = strchr(mode,'b') != NULL;
167 f->f_buf = NULL;
168 f->f_univ_newline = (strchr(mode, 'U') != NULL);
169 f->f_newlinetypes = NEWLINE_UNKNOWN;
170 f->f_skipnextlf = 0;
171 Py_INCREF(Py_None);
172 f->f_encoding = Py_None;
173 Py_INCREF(Py_None);
174 f->f_errors = Py_None;
175 f->readable = f->writable = 0;
176 if (strchr(mode, 'r') != NULL || f->f_univ_newline)
177 f->readable = 1;
178 if (strchr(mode, 'w') != NULL || strchr(mode, 'a') != NULL)
179 f->writable = 1;
180 if (strchr(mode, '+') != NULL)
181 f->readable = f->writable = 1;
Tim Petersf1827cf2003-09-07 03:30:18 +0000182
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000183 if (f->f_mode == NULL)
184 return NULL;
185 f->f_fp = fp;
186 f = dircheck(f);
187 return (PyObject *) f;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000188}
189
Kristján Valur Jónssonfd4c8722009-02-04 10:05:25 +0000190#if defined _MSC_VER && _MSC_VER >= 1400 && defined(__STDC_SECURE_LIB__)
191#define Py_VERIFY_WINNT
192/* The CRT on windows compiled with Visual Studio 2005 and higher may
193 * assert if given invalid mode strings. This is all fine and well
194 * in static languages like C where the mode string is typcially hard
195 * coded. But in Python, were we pass in the mode string from the user,
196 * we need to verify it first manually
197 */
198static int _PyVerify_Mode_WINNT(const char *mode)
199{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000200 /* See if mode string is valid on Windows to avoid hard assertions */
201 /* remove leading spacese */
202 int singles = 0;
203 int pairs = 0;
204 int encoding = 0;
205 const char *s, *c;
Kristján Valur Jónssonfd4c8722009-02-04 10:05:25 +0000206
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000207 while(*mode == ' ') /* strip initial spaces */
208 ++mode;
209 if (!strchr("rwa", *mode)) /* must start with one of these */
210 return 0;
211 while (*++mode) {
212 if (*mode == ' ' || *mode == 'N') /* ignore spaces and N */
213 continue;
214 s = "+TD"; /* each of this can appear only once */
215 c = strchr(s, *mode);
216 if (c) {
217 ptrdiff_t idx = s-c;
218 if (singles & (1<<idx))
219 return 0;
220 singles |= (1<<idx);
221 continue;
222 }
223 s = "btcnSR"; /* only one of each letter in the pairs allowed */
224 c = strchr(s, *mode);
225 if (c) {
226 ptrdiff_t idx = (s-c)/2;
227 if (pairs & (1<<idx))
228 return 0;
229 pairs |= (1<<idx);
230 continue;
231 }
232 if (*mode == ',') {
233 encoding = 1;
234 break;
235 }
236 return 0; /* found an invalid char */
237 }
Kristján Valur Jónssonfd4c8722009-02-04 10:05:25 +0000238
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000239 if (encoding) {
240 char *e[] = {"UTF-8", "UTF-16LE", "UNICODE"};
241 while (*mode == ' ')
242 ++mode;
243 /* find 'ccs =' */
244 if (strncmp(mode, "ccs", 3))
245 return 0;
246 mode += 3;
247 while (*mode == ' ')
248 ++mode;
249 if (*mode != '=')
250 return 0;
251 while (*mode == ' ')
252 ++mode;
253 for(encoding = 0; encoding<_countof(e); ++encoding) {
254 size_t l = strlen(e[encoding]);
255 if (!strncmp(mode, e[encoding], l)) {
256 mode += l; /* found a valid encoding */
257 break;
258 }
259 }
260 if (encoding == _countof(e))
261 return 0;
262 }
263 /* skip trailing spaces */
264 while (*mode == ' ')
265 ++mode;
Kristján Valur Jónssonfd4c8722009-02-04 10:05:25 +0000266
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000267 return *mode == '\0'; /* must be at the end of the string */
Kristján Valur Jónssonfd4c8722009-02-04 10:05:25 +0000268}
269#endif
270
Skip Montanarobbf12ba2005-05-20 03:07:06 +0000271/* check for known incorrect mode strings - problem is, platforms are
272 free to accept any mode characters they like and are supposed to
273 ignore stuff they don't understand... write or append mode with
Georg Brandl7b90e162006-05-18 07:01:27 +0000274 universal newline support is expressly forbidden by PEP 278.
275 Additionally, remove the 'U' from the mode string as platforms
Kristján Valur Jónsson0a440d42007-04-26 09:15:08 +0000276 won't know what it is. Non-zero return signals an exception */
277int
278_PyFile_SanitizeMode(char *mode)
Skip Montanarobbf12ba2005-05-20 03:07:06 +0000279{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000280 char *upos;
281 size_t len = strlen(mode);
Skip Montanarobbf12ba2005-05-20 03:07:06 +0000282
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000283 if (!len) {
284 PyErr_SetString(PyExc_ValueError, "empty mode string");
285 return -1;
286 }
Skip Montanarobbf12ba2005-05-20 03:07:06 +0000287
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000288 upos = strchr(mode, 'U');
289 if (upos) {
290 memmove(upos, upos+1, len-(upos-mode)); /* incl null char */
Skip Montanarobbf12ba2005-05-20 03:07:06 +0000291
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000292 if (mode[0] == 'w' || mode[0] == 'a') {
293 PyErr_Format(PyExc_ValueError, "universal newline "
294 "mode can only be used with modes "
295 "starting with 'r'");
296 return -1;
297 }
Georg Brandl7b90e162006-05-18 07:01:27 +0000298
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000299 if (mode[0] != 'r') {
300 memmove(mode+1, mode, strlen(mode)+1);
301 mode[0] = 'r';
302 }
Georg Brandl7b90e162006-05-18 07:01:27 +0000303
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000304 if (!strchr(mode, 'b')) {
305 memmove(mode+2, mode+1, strlen(mode));
306 mode[1] = 'b';
307 }
308 } else if (mode[0] != 'r' && mode[0] != 'w' && mode[0] != 'a') {
309 PyErr_Format(PyExc_ValueError, "mode string must begin with "
310 "one of 'r', 'w', 'a' or 'U', not '%.200s'", mode);
311 return -1;
312 }
Kristján Valur Jónssonfd4c8722009-02-04 10:05:25 +0000313#ifdef Py_VERIFY_WINNT
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000314 /* additional checks on NT with visual studio 2005 and higher */
315 if (!_PyVerify_Mode_WINNT(mode)) {
316 PyErr_Format(PyExc_ValueError, "Invalid mode ('%.50s')", mode);
317 return -1;
318 }
Kristján Valur Jónssonfd4c8722009-02-04 10:05:25 +0000319#endif
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000320 return 0;
Skip Montanarobbf12ba2005-05-20 03:07:06 +0000321}
322
Tim Peters59c9a642001-09-13 05:38:56 +0000323static PyObject *
324open_the_file(PyFileObject *f, char *name, char *mode)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000325{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000326 char *newmode;
327 assert(f != NULL);
328 assert(PyFile_Check(f));
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000329#ifdef MS_WINDOWS
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000330 /* windows ignores the passed name in order to support Unicode */
331 assert(f->f_name != NULL);
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000332#else
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000333 assert(name != NULL);
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000334#endif
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000335 assert(mode != NULL);
336 assert(f->f_fp == NULL);
Tim Peters59c9a642001-09-13 05:38:56 +0000337
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000338 /* probably need to replace 'U' by 'rb' */
339 newmode = PyMem_MALLOC(strlen(mode) + 3);
340 if (!newmode) {
341 PyErr_NoMemory();
342 return NULL;
343 }
344 strcpy(newmode, mode);
Georg Brandl7b90e162006-05-18 07:01:27 +0000345
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000346 if (_PyFile_SanitizeMode(newmode)) {
347 f = NULL;
348 goto cleanup;
349 }
Skip Montanarobbf12ba2005-05-20 03:07:06 +0000350
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000351 /* rexec.py can't stop a user from getting the file() constructor --
352 all they have to do is get *any* file object f, and then do
353 type(f). Here we prevent them from doing damage with it. */
354 if (PyEval_GetRestricted()) {
355 PyErr_SetString(PyExc_IOError,
356 "file() constructor not accessible in restricted mode");
357 f = NULL;
358 goto cleanup;
359 }
360 errno = 0;
Skip Montanaro51ffac62004-06-11 04:49:03 +0000361
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000362#ifdef MS_WINDOWS
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000363 if (PyUnicode_Check(f->f_name)) {
364 PyObject *wmode;
365 wmode = PyUnicode_DecodeASCII(newmode, strlen(newmode), NULL);
366 if (f->f_name && wmode) {
367 FILE_BEGIN_ALLOW_THREADS(f)
368 /* PyUnicode_AS_UNICODE OK without thread
369 lock as it is a simple dereference. */
370 f->f_fp = _wfopen(PyUnicode_AS_UNICODE(f->f_name),
371 PyUnicode_AS_UNICODE(wmode));
372 FILE_END_ALLOW_THREADS(f)
373 }
374 Py_XDECREF(wmode);
375 }
Skip Montanaro51ffac62004-06-11 04:49:03 +0000376#endif
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000377 if (NULL == f->f_fp && NULL != name) {
378 FILE_BEGIN_ALLOW_THREADS(f)
379 f->f_fp = fopen(name, newmode);
380 FILE_END_ALLOW_THREADS(f)
381 }
Skip Montanaro51ffac62004-06-11 04:49:03 +0000382
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000383 if (f->f_fp == NULL) {
Kristján Valur Jónsson74c3ea02006-07-03 14:59:05 +0000384#if defined _MSC_VER && (_MSC_VER < 1400 || !defined(__STDC_SECURE_LIB__))
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000385 /* MSVC 6 (Microsoft) leaves errno at 0 for bad mode strings,
386 * across all Windows flavors. When it sets EINVAL varies
387 * across Windows flavors, the exact conditions aren't
388 * documented, and the answer lies in the OS's implementation
389 * of Win32's CreateFile function (whose source is secret).
390 * Seems the best we can do is map EINVAL to ENOENT.
391 * Starting with Visual Studio .NET 2005, EINVAL is correctly
392 * set by our CRT error handler (set in exceptions.c.)
393 */
394 if (errno == 0) /* bad mode string */
395 errno = EINVAL;
396 else if (errno == EINVAL) /* unknown, but not a mode string */
397 errno = ENOENT;
Tim Peters2ea91112002-04-08 04:13:12 +0000398#endif
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000399 /* EINVAL is returned when an invalid filename or
400 * an invalid mode is supplied. */
401 if (errno == EINVAL) {
402 PyObject *v;
403 char message[100];
404 PyOS_snprintf(message, 100,
405 "invalid mode ('%.50s') or filename", mode);
406 v = Py_BuildValue("(isO)", errno, message, f->f_name);
407 if (v != NULL) {
408 PyErr_SetObject(PyExc_IOError, v);
409 Py_DECREF(v);
410 }
411 }
412 else
413 PyErr_SetFromErrnoWithFilenameObject(PyExc_IOError, f->f_name);
414 f = NULL;
415 }
416 if (f != NULL)
417 f = dircheck(f);
Georg Brandl7b90e162006-05-18 07:01:27 +0000418
419cleanup:
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000420 PyMem_FREE(newmode);
Georg Brandl7b90e162006-05-18 07:01:27 +0000421
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000422 return (PyObject *)f;
Tim Peters59c9a642001-09-13 05:38:56 +0000423}
424
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +0000425static PyObject *
426close_the_file(PyFileObject *f)
427{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000428 int sts = 0;
429 int (*local_close)(FILE *);
430 FILE *local_fp = f->f_fp;
Antoine Pitrou638cee62010-10-28 14:50:57 +0000431 char *local_setbuf = f->f_setbuf;
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000432 if (local_fp != NULL) {
433 local_close = f->f_close;
434 if (local_close != NULL && f->unlocked_count > 0) {
Benjamin Petersona72d15c2017-09-13 21:20:29 -0700435 if (Py_REFCNT(f) > 0) {
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000436 PyErr_SetString(PyExc_IOError,
437 "close() called during concurrent "
Serhiy Storchaka6401e562017-11-10 12:58:55 +0200438 "operation on the same file object");
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000439 } else {
440 /* This should not happen unless someone is
441 * carelessly playing with the PyFileObject
442 * struct fields and/or its associated FILE
443 * pointer. */
444 PyErr_SetString(PyExc_SystemError,
445 "PyFileObject locking error in "
Serhiy Storchaka6401e562017-11-10 12:58:55 +0200446 "destructor (refcnt <= 0 at close)");
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000447 }
448 return NULL;
449 }
450 /* NULL out the FILE pointer before releasing the GIL, because
451 * it will not be valid anymore after the close() function is
452 * called. */
453 f->f_fp = NULL;
454 if (local_close != NULL) {
Antoine Pitrou638cee62010-10-28 14:50:57 +0000455 /* Issue #9295: must temporarily reset f_setbuf so that another
456 thread doesn't free it when running file_close() concurrently.
457 Otherwise this close() will crash when flushing the buffer. */
458 f->f_setbuf = NULL;
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000459 Py_BEGIN_ALLOW_THREADS
460 errno = 0;
461 sts = (*local_close)(local_fp);
462 Py_END_ALLOW_THREADS
Antoine Pitrou638cee62010-10-28 14:50:57 +0000463 f->f_setbuf = local_setbuf;
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000464 if (sts == EOF)
465 return PyErr_SetFromErrno(PyExc_IOError);
466 if (sts != 0)
467 return PyInt_FromLong((long)sts);
468 }
469 }
470 Py_RETURN_NONE;
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +0000471}
472
Tim Peters59c9a642001-09-13 05:38:56 +0000473PyObject *
474PyFile_FromFile(FILE *fp, char *name, char *mode, int (*close)(FILE *))
475{
Victor Stinner63c22fa2011-09-23 19:37:03 +0200476 PyFileObject *f;
477 PyObject *o_name;
478
479 f = (PyFileObject *)PyFile_Type.tp_new(&PyFile_Type, NULL, NULL);
480 if (f == NULL)
481 return NULL;
482 o_name = PyString_FromString(name);
483 if (o_name == NULL) {
484 if (close != NULL && fp != NULL)
485 close(fp);
486 Py_DECREF(f);
487 return NULL;
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000488 }
Victor Stinner63c22fa2011-09-23 19:37:03 +0200489 if (fill_file_fields(f, fp, o_name, mode, close) == NULL) {
490 Py_DECREF(f);
491 Py_DECREF(o_name);
492 return NULL;
493 }
494 Py_DECREF(o_name);
495 return (PyObject *)f;
Tim Peters59c9a642001-09-13 05:38:56 +0000496}
497
498PyObject *
499PyFile_FromString(char *name, char *mode)
500{
Antoine Pitrou02a38012012-04-05 14:07:52 +0200501 extern int fclose(FILE *);
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000502 PyFileObject *f;
Tim Peters59c9a642001-09-13 05:38:56 +0000503
Antoine Pitrou02a38012012-04-05 14:07:52 +0200504 f = (PyFileObject *)PyFile_FromFile((FILE *)NULL, name, mode, fclose);
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000505 if (f != NULL) {
506 if (open_the_file(f, name, mode) == NULL) {
507 Py_DECREF(f);
508 f = NULL;
509 }
510 }
511 return (PyObject *)f;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000512}
513
Guido van Rossumb6775db1994-08-01 11:34:53 +0000514void
Fred Drakefd99de62000-07-09 05:02:18 +0000515PyFile_SetBufSize(PyObject *f, int bufsize)
Guido van Rossumb6775db1994-08-01 11:34:53 +0000516{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000517 PyFileObject *file = (PyFileObject *)f;
518 if (bufsize >= 0) {
519 int type;
520 switch (bufsize) {
521 case 0:
522 type = _IONBF;
523 break;
Martin v. Löwis1e3bdf62003-09-04 19:01:46 +0000524#ifdef HAVE_SETVBUF
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000525 case 1:
526 type = _IOLBF;
527 bufsize = BUFSIZ;
528 break;
Martin v. Löwis1e3bdf62003-09-04 19:01:46 +0000529#endif
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000530 default:
531 type = _IOFBF;
Martin v. Löwis1e3bdf62003-09-04 19:01:46 +0000532#ifndef HAVE_SETVBUF
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000533 bufsize = BUFSIZ;
Martin v. Löwis1e3bdf62003-09-04 19:01:46 +0000534#endif
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000535 break;
536 }
537 fflush(file->f_fp);
538 if (type == _IONBF) {
539 PyMem_Free(file->f_setbuf);
540 file->f_setbuf = NULL;
541 } else {
542 file->f_setbuf = (char *)PyMem_Realloc(file->f_setbuf,
543 bufsize);
544 }
Martin v. Löwis1e3bdf62003-09-04 19:01:46 +0000545#ifdef HAVE_SETVBUF
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000546 setvbuf(file->f_fp, file->f_setbuf, type, bufsize);
Guido van Rossumf8b4de01998-03-06 15:32:40 +0000547#else /* !HAVE_SETVBUF */
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000548 setbuf(file->f_fp, file->f_setbuf);
Guido van Rossumf8b4de01998-03-06 15:32:40 +0000549#endif /* !HAVE_SETVBUF */
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000550 }
Guido van Rossumb6775db1994-08-01 11:34:53 +0000551}
552
Martin v. Löwis5467d4c2003-05-10 07:10:12 +0000553/* Set the encoding used to output Unicode strings.
Martin v. Löwis99815892008-06-01 07:20:46 +0000554 Return 1 on success, 0 on failure. */
Martin v. Löwis5467d4c2003-05-10 07:10:12 +0000555
556int
557PyFile_SetEncoding(PyObject *f, const char *enc)
558{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000559 return PyFile_SetEncodingAndErrors(f, enc, NULL);
Martin v. Löwis99815892008-06-01 07:20:46 +0000560}
561
562int
563PyFile_SetEncodingAndErrors(PyObject *f, const char *enc, char* errors)
564{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000565 PyFileObject *file = (PyFileObject*)f;
566 PyObject *str, *oerrors;
Thomas Woutersafea5292007-01-23 13:42:00 +0000567
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000568 assert(PyFile_Check(f));
569 str = PyString_FromString(enc);
570 if (!str)
571 return 0;
572 if (errors) {
573 oerrors = PyString_FromString(errors);
574 if (!oerrors) {
575 Py_DECREF(str);
576 return 0;
577 }
578 } else {
579 oerrors = Py_None;
580 Py_INCREF(Py_None);
581 }
Serhiy Storchaka763a61c2016-04-10 18:05:12 +0300582 Py_SETREF(file->f_encoding, str);
583 Py_SETREF(file->f_errors, oerrors);
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000584 return 1;
Martin v. Löwis5467d4c2003-05-10 07:10:12 +0000585}
586
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000587static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000588err_closed(void)
Guido van Rossumd7297e61992-07-06 14:19:26 +0000589{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000590 PyErr_SetString(PyExc_ValueError, "I/O operation on closed file");
591 return NULL;
Guido van Rossumd7297e61992-07-06 14:19:26 +0000592}
593
Antoine Pitroubb445a12010-02-05 17:05:54 +0000594static PyObject *
595err_mode(char *action)
596{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000597 PyErr_Format(PyExc_IOError, "File not open for %s", action);
598 return NULL;
Antoine Pitroubb445a12010-02-05 17:05:54 +0000599}
600
Thomas Woutersc45251a2006-02-12 11:53:32 +0000601/* Refuse regular file I/O if there's data in the iteration-buffer.
602 * Mixing them would cause data to arrive out of order, as the read*
603 * methods don't use the iteration buffer. */
604static PyObject *
605err_iterbuffered(void)
606{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000607 PyErr_SetString(PyExc_ValueError,
608 "Mixing iteration and read methods would lose data");
609 return NULL;
Thomas Woutersc45251a2006-02-12 11:53:32 +0000610}
611
Benjamin Petersondbf52e02018-01-02 09:25:41 -0800612static void
613drop_file_readahead(PyFileObject *f)
614{
615 PyMem_FREE(f->f_buf);
616 f->f_buf = NULL;
617}
Guido van Rossum7a6e9592002-08-06 15:55:28 +0000618
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000619/* Methods */
620
621static void
Fred Drakefd99de62000-07-09 05:02:18 +0000622file_dealloc(PyFileObject *f)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000623{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000624 PyObject *ret;
625 if (f->weakreflist != NULL)
626 PyObject_ClearWeakRefs((PyObject *) f);
627 ret = close_the_file(f);
628 if (!ret) {
629 PySys_WriteStderr("close failed in file object destructor:\n");
630 PyErr_Print();
631 }
632 else {
633 Py_DECREF(ret);
634 }
635 PyMem_Free(f->f_setbuf);
636 Py_XDECREF(f->f_name);
637 Py_XDECREF(f->f_mode);
638 Py_XDECREF(f->f_encoding);
639 Py_XDECREF(f->f_errors);
Benjamin Petersondbf52e02018-01-02 09:25:41 -0800640 drop_file_readahead(f);
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000641 Py_TYPE(f)->tp_free((PyObject *)f);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000642}
643
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000644static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000645file_repr(PyFileObject *f)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000646{
Ezio Melotti11f8b682012-03-12 01:17:02 +0200647 PyObject *ret = NULL;
648 PyObject *name = NULL;
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000649 if (PyUnicode_Check(f->f_name)) {
Martin v. Löwis0073f2e2002-11-21 23:52:35 +0000650#ifdef Py_USING_UNICODE
Ezio Melottieace3a72012-03-12 01:28:45 +0200651 const char *name_str;
Ezio Melotti11f8b682012-03-12 01:17:02 +0200652 name = PyUnicode_AsUnicodeEscapeString(f->f_name);
Ezio Melottieace3a72012-03-12 01:28:45 +0200653 name_str = name ? PyString_AsString(name) : "?";
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000654 ret = PyString_FromFormat("<%s file u'%s', mode '%s' at %p>",
655 f->f_fp == NULL ? "closed" : "open",
656 name_str,
657 PyString_AsString(f->f_mode),
658 f);
659 Py_XDECREF(name);
660 return ret;
Martin v. Löwis0073f2e2002-11-21 23:52:35 +0000661#endif
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000662 } else {
Ezio Melotti11f8b682012-03-12 01:17:02 +0200663 name = PyObject_Repr(f->f_name);
664 if (name == NULL)
665 return NULL;
666 ret = PyString_FromFormat("<%s file %s, mode '%s' at %p>",
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000667 f->f_fp == NULL ? "closed" : "open",
Ezio Melotti11f8b682012-03-12 01:17:02 +0200668 PyString_AsString(name),
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000669 PyString_AsString(f->f_mode),
670 f);
Ezio Melotti11f8b682012-03-12 01:17:02 +0200671 Py_XDECREF(name);
672 return ret;
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000673 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000674}
675
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000676static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000677file_close(PyFileObject *f)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000678{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000679 PyObject *sts = close_the_file(f);
Antoine Pitrou83137c22010-05-17 19:56:59 +0000680 if (sts) {
681 PyMem_Free(f->f_setbuf);
682 f->f_setbuf = NULL;
683 }
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000684 return sts;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000685}
686
Trent Mickf29f47b2000-08-11 19:02:59 +0000687
Guido van Rossumb8552162001-09-05 14:58:11 +0000688/* Our very own off_t-like type, 64-bit if possible */
689#if !defined(HAVE_LARGEFILE_SUPPORT)
690typedef off_t Py_off_t;
691#elif SIZEOF_OFF_T >= 8
692typedef off_t Py_off_t;
693#elif SIZEOF_FPOS_T >= 8
Guido van Rossum4f53da02001-03-01 18:26:53 +0000694typedef fpos_t Py_off_t;
695#else
Guido van Rossumb8552162001-09-05 14:58:11 +0000696#error "Large file support, but neither off_t nor fpos_t is large enough."
Guido van Rossum4f53da02001-03-01 18:26:53 +0000697#endif
698
699
Trent Mickf29f47b2000-08-11 19:02:59 +0000700/* a portable fseek() function
701 return 0 on success, non-zero on failure (with errno set) */
Guido van Rossumf68d8e52001-04-14 17:55:09 +0000702static int
Guido van Rossum4f53da02001-03-01 18:26:53 +0000703_portable_fseek(FILE *fp, Py_off_t offset, int whence)
Trent Mickf29f47b2000-08-11 19:02:59 +0000704{
Guido van Rossumb8552162001-09-05 14:58:11 +0000705#if !defined(HAVE_LARGEFILE_SUPPORT)
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000706 return fseek(fp, offset, whence);
Guido van Rossumb8552162001-09-05 14:58:11 +0000707#elif defined(HAVE_FSEEKO) && SIZEOF_OFF_T >= 8
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000708 return fseeko(fp, offset, whence);
Trent Mickf29f47b2000-08-11 19:02:59 +0000709#elif defined(HAVE_FSEEK64)
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000710 return fseek64(fp, offset, whence);
Fred Drakedb810ac2000-10-06 20:42:33 +0000711#elif defined(__BEOS__)
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000712 return _fseek(fp, offset, whence);
Guido van Rossumb8552162001-09-05 14:58:11 +0000713#elif SIZEOF_FPOS_T >= 8
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000714 /* lacking a 64-bit capable fseek(), use a 64-bit capable fsetpos()
715 and fgetpos() to implement fseek()*/
716 fpos_t pos;
717 switch (whence) {
718 case SEEK_END:
Guido van Rossum8b4e43e2001-09-10 20:43:35 +0000719#ifdef MS_WINDOWS
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000720 fflush(fp);
721 if (_lseeki64(fileno(fp), 0, 2) == -1)
722 return -1;
Guido van Rossum8b4e43e2001-09-10 20:43:35 +0000723#else
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000724 if (fseek(fp, 0, SEEK_END) != 0)
725 return -1;
Guido van Rossum8b4e43e2001-09-10 20:43:35 +0000726#endif
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000727 /* fall through */
728 case SEEK_CUR:
729 if (fgetpos(fp, &pos) != 0)
730 return -1;
731 offset += pos;
732 break;
733 /* case SEEK_SET: break; */
734 }
735 return fsetpos(fp, &offset);
Trent Mickf29f47b2000-08-11 19:02:59 +0000736#else
Guido van Rossumb8552162001-09-05 14:58:11 +0000737#error "Large file support, but no way to fseek."
Trent Mickf29f47b2000-08-11 19:02:59 +0000738#endif
739}
740
741
742/* a portable ftell() function
743 Return -1 on failure with errno set appropriately, current file
744 position on success */
Guido van Rossumf68d8e52001-04-14 17:55:09 +0000745static Py_off_t
Fred Drake8ce159a2000-08-31 05:18:54 +0000746_portable_ftell(FILE* fp)
Trent Mickf29f47b2000-08-11 19:02:59 +0000747{
Guido van Rossumb8552162001-09-05 14:58:11 +0000748#if !defined(HAVE_LARGEFILE_SUPPORT)
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000749 return ftell(fp);
Guido van Rossumb8552162001-09-05 14:58:11 +0000750#elif defined(HAVE_FTELLO) && SIZEOF_OFF_T >= 8
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000751 return ftello(fp);
Guido van Rossumb8552162001-09-05 14:58:11 +0000752#elif defined(HAVE_FTELL64)
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000753 return ftell64(fp);
Guido van Rossumb8552162001-09-05 14:58:11 +0000754#elif SIZEOF_FPOS_T >= 8
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000755 fpos_t pos;
756 if (fgetpos(fp, &pos) != 0)
757 return -1;
758 return pos;
Trent Mickf29f47b2000-08-11 19:02:59 +0000759#else
Guido van Rossumb8552162001-09-05 14:58:11 +0000760#error "Large file support, but no way to ftell."
Trent Mickf29f47b2000-08-11 19:02:59 +0000761#endif
762}
763
764
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000765static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000766file_seek(PyFileObject *f, PyObject *args)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000767{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000768 int whence;
769 int ret;
770 Py_off_t offset;
771 PyObject *offobj, *off_index;
Tim Peters86821b22001-01-07 21:19:34 +0000772
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000773 if (f->f_fp == NULL)
774 return err_closed();
Benjamin Petersondbf52e02018-01-02 09:25:41 -0800775 drop_file_readahead(f);
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000776 whence = 0;
777 if (!PyArg_ParseTuple(args, "O|i:seek", &offobj, &whence))
778 return NULL;
779 off_index = PyNumber_Index(offobj);
780 if (!off_index) {
781 if (!PyFloat_Check(offobj))
782 return NULL;
783 /* Deprecated in 2.6 */
784 PyErr_Clear();
785 if (PyErr_WarnEx(PyExc_DeprecationWarning,
786 "integer argument expected, got float",
787 1) < 0)
788 return NULL;
789 off_index = offobj;
790 Py_INCREF(offobj);
791 }
Guido van Rossum3c9fe0c1999-01-06 18:51:17 +0000792#if !defined(HAVE_LARGEFILE_SUPPORT)
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000793 offset = PyInt_AsLong(off_index);
Guido van Rossum3c9fe0c1999-01-06 18:51:17 +0000794#else
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000795 offset = PyLong_Check(off_index) ?
796 PyLong_AsLongLong(off_index) : PyInt_AsLong(off_index);
Guido van Rossum3c9fe0c1999-01-06 18:51:17 +0000797#endif
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000798 Py_DECREF(off_index);
799 if (PyErr_Occurred())
800 return NULL;
Tim Peters86821b22001-01-07 21:19:34 +0000801
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000802 FILE_BEGIN_ALLOW_THREADS(f)
803 errno = 0;
804 ret = _portable_fseek(f->f_fp, offset, whence);
805 FILE_END_ALLOW_THREADS(f)
Trent Mickf29f47b2000-08-11 19:02:59 +0000806
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000807 if (ret != 0) {
808 PyErr_SetFromErrno(PyExc_IOError);
809 clearerr(f->f_fp);
810 return NULL;
811 }
812 f->f_skipnextlf = 0;
813 Py_INCREF(Py_None);
814 return Py_None;
Guido van Rossumce5ba841991-03-06 13:06:18 +0000815}
816
Trent Mickf29f47b2000-08-11 19:02:59 +0000817
Guido van Rossumd7047b31995-01-02 19:07:15 +0000818#ifdef HAVE_FTRUNCATE
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000819static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000820file_truncate(PyFileObject *f, PyObject *args)
Guido van Rossumd7047b31995-01-02 19:07:15 +0000821{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000822 Py_off_t newsize;
823 PyObject *newsizeobj = NULL;
824 Py_off_t initialpos;
825 int ret;
Tim Peters86821b22001-01-07 21:19:34 +0000826
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000827 if (f->f_fp == NULL)
828 return err_closed();
829 if (!f->writable)
830 return err_mode("writing");
831 if (!PyArg_UnpackTuple(args, "truncate", 0, 1, &newsizeobj))
832 return NULL;
Tim Petersfb05db22002-03-11 00:24:00 +0000833
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000834 /* Get current file position. If the file happens to be open for
835 * update and the last operation was an input operation, C doesn't
836 * define what the later fflush() will do, but we promise truncate()
837 * won't change the current position (and fflush() *does* change it
838 * then at least on Windows). The easiest thing is to capture
839 * current pos now and seek back to it at the end.
840 */
841 FILE_BEGIN_ALLOW_THREADS(f)
842 errno = 0;
843 initialpos = _portable_ftell(f->f_fp);
844 FILE_END_ALLOW_THREADS(f)
845 if (initialpos == -1)
846 goto onioerror;
Tim Petersf1827cf2003-09-07 03:30:18 +0000847
Martin Panter8d496ad2016-06-02 10:35:44 +0000848 /* Set newsize to current position if newsizeobj NULL, else to the
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000849 * specified value.
850 */
851 if (newsizeobj != NULL) {
Guido van Rossum3c9fe0c1999-01-06 18:51:17 +0000852#if !defined(HAVE_LARGEFILE_SUPPORT)
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000853 newsize = PyInt_AsLong(newsizeobj);
Guido van Rossum3c9fe0c1999-01-06 18:51:17 +0000854#else
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000855 newsize = PyLong_Check(newsizeobj) ?
856 PyLong_AsLongLong(newsizeobj) :
857 PyInt_AsLong(newsizeobj);
Guido van Rossum3c9fe0c1999-01-06 18:51:17 +0000858#endif
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000859 if (PyErr_Occurred())
860 return NULL;
861 }
862 else /* default to current position */
863 newsize = initialpos;
Tim Petersfb05db22002-03-11 00:24:00 +0000864
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000865 /* Flush the stream. We're mixing stream-level I/O with lower-level
866 * I/O, and a flush may be necessary to synch both platform views
867 * of the current file state.
868 */
869 FILE_BEGIN_ALLOW_THREADS(f)
870 errno = 0;
871 ret = fflush(f->f_fp);
872 FILE_END_ALLOW_THREADS(f)
873 if (ret != 0)
874 goto onioerror;
Trent Mickf29f47b2000-08-11 19:02:59 +0000875
Martin v. Löwis6238d2b2002-06-30 15:26:10 +0000876#ifdef MS_WINDOWS
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000877 /* MS _chsize doesn't work if newsize doesn't fit in 32 bits,
878 so don't even try using it. */
879 {
880 HANDLE hFile;
Tim Petersfb05db22002-03-11 00:24:00 +0000881
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000882 /* Have to move current pos to desired endpoint on Windows. */
883 FILE_BEGIN_ALLOW_THREADS(f)
884 errno = 0;
885 ret = _portable_fseek(f->f_fp, newsize, SEEK_SET) != 0;
886 FILE_END_ALLOW_THREADS(f)
887 if (ret)
888 goto onioerror;
Tim Petersfb05db22002-03-11 00:24:00 +0000889
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000890 /* Truncate. Note that this may grow the file! */
891 FILE_BEGIN_ALLOW_THREADS(f)
892 errno = 0;
893 hFile = (HANDLE)_get_osfhandle(fileno(f->f_fp));
894 ret = hFile == (HANDLE)-1;
895 if (ret == 0) {
896 ret = SetEndOfFile(hFile) == 0;
897 if (ret)
898 errno = EACCES;
899 }
900 FILE_END_ALLOW_THREADS(f)
901 if (ret)
902 goto onioerror;
903 }
Trent Mickf29f47b2000-08-11 19:02:59 +0000904#else
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000905 FILE_BEGIN_ALLOW_THREADS(f)
906 errno = 0;
907 ret = ftruncate(fileno(f->f_fp), newsize);
908 FILE_END_ALLOW_THREADS(f)
909 if (ret != 0)
910 goto onioerror;
Martin v. Löwis6238d2b2002-06-30 15:26:10 +0000911#endif /* !MS_WINDOWS */
Tim Peters86821b22001-01-07 21:19:34 +0000912
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000913 /* Restore original file position. */
914 FILE_BEGIN_ALLOW_THREADS(f)
915 errno = 0;
916 ret = _portable_fseek(f->f_fp, initialpos, SEEK_SET) != 0;
917 FILE_END_ALLOW_THREADS(f)
918 if (ret)
919 goto onioerror;
Tim Petersf1827cf2003-09-07 03:30:18 +0000920
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000921 Py_INCREF(Py_None);
922 return Py_None;
Trent Mickf29f47b2000-08-11 19:02:59 +0000923
924onioerror:
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000925 PyErr_SetFromErrno(PyExc_IOError);
926 clearerr(f->f_fp);
927 return NULL;
Guido van Rossumd7047b31995-01-02 19:07:15 +0000928}
929#endif /* HAVE_FTRUNCATE */
930
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000931static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000932file_tell(PyFileObject *f)
Guido van Rossumce5ba841991-03-06 13:06:18 +0000933{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000934 Py_off_t pos;
Trent Mickf29f47b2000-08-11 19:02:59 +0000935
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000936 if (f->f_fp == NULL)
937 return err_closed();
938 FILE_BEGIN_ALLOW_THREADS(f)
939 errno = 0;
940 pos = _portable_ftell(f->f_fp);
941 FILE_END_ALLOW_THREADS(f)
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +0000942
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000943 if (pos == -1) {
944 PyErr_SetFromErrno(PyExc_IOError);
945 clearerr(f->f_fp);
946 return NULL;
947 }
948 if (f->f_skipnextlf) {
949 int c;
950 c = GETC(f->f_fp);
951 if (c == '\n') {
952 f->f_newlinetypes |= NEWLINE_CRLF;
953 pos++;
954 f->f_skipnextlf = 0;
955 } else if (c != EOF) ungetc(c, f->f_fp);
956 }
Guido van Rossum3c9fe0c1999-01-06 18:51:17 +0000957#if !defined(HAVE_LARGEFILE_SUPPORT)
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000958 return PyInt_FromLong(pos);
Guido van Rossum3c9fe0c1999-01-06 18:51:17 +0000959#else
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000960 return PyLong_FromLongLong(pos);
Guido van Rossum3c9fe0c1999-01-06 18:51:17 +0000961#endif
Guido van Rossumce5ba841991-03-06 13:06:18 +0000962}
963
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000964static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000965file_fileno(PyFileObject *f)
Guido van Rossumed233a51992-06-23 09:07:03 +0000966{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000967 if (f->f_fp == NULL)
968 return err_closed();
969 return PyInt_FromLong((long) fileno(f->f_fp));
Guido van Rossumed233a51992-06-23 09:07:03 +0000970}
971
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000972static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000973file_flush(PyFileObject *f)
Guido van Rossumce5ba841991-03-06 13:06:18 +0000974{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000975 int res;
Tim Peters86821b22001-01-07 21:19:34 +0000976
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000977 if (f->f_fp == NULL)
978 return err_closed();
979 FILE_BEGIN_ALLOW_THREADS(f)
980 errno = 0;
981 res = fflush(f->f_fp);
982 FILE_END_ALLOW_THREADS(f)
983 if (res != 0) {
984 PyErr_SetFromErrno(PyExc_IOError);
985 clearerr(f->f_fp);
986 return NULL;
987 }
988 Py_INCREF(Py_None);
989 return Py_None;
Guido van Rossumce5ba841991-03-06 13:06:18 +0000990}
991
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000992static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000993file_isatty(PyFileObject *f)
Guido van Rossuma1ab7fa1991-06-04 19:37:39 +0000994{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000995 long res;
996 if (f->f_fp == NULL)
997 return err_closed();
998 FILE_BEGIN_ALLOW_THREADS(f)
999 res = isatty((int)fileno(f->f_fp));
1000 FILE_END_ALLOW_THREADS(f)
1001 return PyBool_FromLong(res);
Guido van Rossuma1ab7fa1991-06-04 19:37:39 +00001002}
1003
Guido van Rossumff7e83d1999-08-27 20:39:37 +00001004
Guido van Rossum5449b6e1997-05-09 22:27:31 +00001005#if BUFSIZ < 8192
1006#define SMALLCHUNK 8192
1007#else
1008#define SMALLCHUNK BUFSIZ
1009#endif
1010
Guido van Rossum5449b6e1997-05-09 22:27:31 +00001011static size_t
Fred Drakefd99de62000-07-09 05:02:18 +00001012new_buffersize(PyFileObject *f, size_t currentsize)
Guido van Rossum5449b6e1997-05-09 22:27:31 +00001013{
1014#ifdef HAVE_FSTAT
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001015 off_t pos, end;
1016 struct stat st;
Nir Soffer830daae2017-12-07 22:25:39 +02001017 int res;
1018
1019 Py_BEGIN_ALLOW_THREADS
1020 res = fstat(fileno(f->f_fp), &st);
1021 Py_END_ALLOW_THREADS
1022
1023 if (res == 0) {
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001024 end = st.st_size;
1025 /* The following is not a bug: we really need to call lseek()
1026 *and* ftell(). The reason is that some stdio libraries
1027 mistakenly flush their buffer when ftell() is called and
1028 the lseek() call it makes fails, thereby throwing away
1029 data that cannot be recovered in any way. To avoid this,
1030 we first test lseek(), and only call ftell() if lseek()
1031 works. We can't use the lseek() value either, because we
1032 need to take the amount of buffered data into account.
1033 (Yet another reason why stdio stinks. :-) */
Nir Soffer830daae2017-12-07 22:25:39 +02001034
1035 Py_BEGIN_ALLOW_THREADS
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001036 pos = lseek(fileno(f->f_fp), 0L, SEEK_CUR);
Nir Soffer830daae2017-12-07 22:25:39 +02001037 Py_END_ALLOW_THREADS
1038
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001039 if (pos >= 0) {
1040 pos = ftell(f->f_fp);
1041 }
1042 if (pos < 0)
1043 clearerr(f->f_fp);
1044 if (end > pos && pos >= 0)
1045 return currentsize + end - pos + 1;
1046 /* Add 1 so if the file were to grow we'd notice. */
1047 }
Guido van Rossum5449b6e1997-05-09 22:27:31 +00001048#endif
Nadeem Vawda36248152011-10-13 13:52:46 +02001049 /* Expand the buffer by an amount proportional to the current size,
1050 giving us amortized linear-time behavior. Use a less-than-double
1051 growth factor to avoid excessive allocation. */
1052 return currentsize + (currentsize >> 3) + 6;
Guido van Rossum5449b6e1997-05-09 22:27:31 +00001053}
1054
Gustavo Niemeyer786ddb22002-12-16 18:12:53 +00001055#if defined(EWOULDBLOCK) && defined(EAGAIN) && EWOULDBLOCK != EAGAIN
1056#define BLOCKED_ERRNO(x) ((x) == EWOULDBLOCK || (x) == EAGAIN)
1057#else
1058#ifdef EWOULDBLOCK
1059#define BLOCKED_ERRNO(x) ((x) == EWOULDBLOCK)
1060#else
1061#ifdef EAGAIN
1062#define BLOCKED_ERRNO(x) ((x) == EAGAIN)
1063#else
1064#define BLOCKED_ERRNO(x) 0
1065#endif
1066#endif
1067#endif
1068
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001069static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +00001070file_read(PyFileObject *f, PyObject *args)
Guido van Rossumce5ba841991-03-06 13:06:18 +00001071{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001072 long bytesrequested = -1;
1073 size_t bytesread, buffersize, chunksize;
1074 PyObject *v;
Tim Peters86821b22001-01-07 21:19:34 +00001075
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001076 if (f->f_fp == NULL)
1077 return err_closed();
1078 if (!f->readable)
1079 return err_mode("reading");
1080 /* refuse to mix with f.next() */
1081 if (f->f_buf != NULL &&
1082 (f->f_bufend - f->f_bufptr) > 0 &&
1083 f->f_buf[0] != '\0')
1084 return err_iterbuffered();
1085 if (!PyArg_ParseTuple(args, "|l:read", &bytesrequested))
1086 return NULL;
1087 if (bytesrequested < 0)
1088 buffersize = new_buffersize(f, (size_t)0);
1089 else
1090 buffersize = bytesrequested;
1091 if (buffersize > PY_SSIZE_T_MAX) {
1092 PyErr_SetString(PyExc_OverflowError,
1093 "requested number of bytes is more than a Python string can hold");
1094 return NULL;
1095 }
1096 v = PyString_FromStringAndSize((char *)NULL, buffersize);
1097 if (v == NULL)
1098 return NULL;
1099 bytesread = 0;
1100 for (;;) {
Gregory P. Smithb2ac4d62012-06-25 20:57:36 -07001101 int interrupted;
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001102 FILE_BEGIN_ALLOW_THREADS(f)
1103 errno = 0;
1104 chunksize = Py_UniversalNewlineFread(BUF(v) + bytesread,
1105 buffersize - bytesread, f->f_fp, (PyObject *)f);
Gregory P. Smithb2ac4d62012-06-25 20:57:36 -07001106 interrupted = ferror(f->f_fp) && errno == EINTR;
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001107 FILE_END_ALLOW_THREADS(f)
Gregory P. Smithb2ac4d62012-06-25 20:57:36 -07001108 if (interrupted) {
1109 clearerr(f->f_fp);
1110 if (PyErr_CheckSignals()) {
1111 Py_DECREF(v);
1112 return NULL;
1113 }
1114 }
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001115 if (chunksize == 0) {
Gregory P. Smithb2ac4d62012-06-25 20:57:36 -07001116 if (interrupted)
1117 continue;
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001118 if (!ferror(f->f_fp))
1119 break;
1120 clearerr(f->f_fp);
1121 /* When in non-blocking mode, data shouldn't
1122 * be discarded if a blocking signal was
1123 * received. That will also happen if
1124 * chunksize != 0, but bytesread < buffersize. */
1125 if (bytesread > 0 && BLOCKED_ERRNO(errno))
1126 break;
1127 PyErr_SetFromErrno(PyExc_IOError);
1128 Py_DECREF(v);
1129 return NULL;
1130 }
1131 bytesread += chunksize;
Gregory P. Smithb2ac4d62012-06-25 20:57:36 -07001132 if (bytesread < buffersize && !interrupted) {
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001133 clearerr(f->f_fp);
1134 break;
1135 }
1136 if (bytesrequested < 0) {
1137 buffersize = new_buffersize(f, buffersize);
1138 if (_PyString_Resize(&v, buffersize) < 0)
1139 return NULL;
1140 } else {
1141 /* Got what was requested. */
1142 break;
1143 }
1144 }
1145 if (bytesread != buffersize && _PyString_Resize(&v, bytesread))
1146 return NULL;
1147 return v;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001148}
1149
Guido van Rossumfdf95dd1997-05-05 22:15:02 +00001150static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +00001151file_readinto(PyFileObject *f, PyObject *args)
Guido van Rossumfdf95dd1997-05-05 22:15:02 +00001152{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001153 char *ptr;
1154 Py_ssize_t ntodo;
1155 Py_ssize_t ndone, nnow;
1156 Py_buffer pbuf;
Tim Peters86821b22001-01-07 21:19:34 +00001157
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001158 if (f->f_fp == NULL)
1159 return err_closed();
1160 if (!f->readable)
1161 return err_mode("reading");
1162 /* refuse to mix with f.next() */
1163 if (f->f_buf != NULL &&
1164 (f->f_bufend - f->f_bufptr) > 0 &&
1165 f->f_buf[0] != '\0')
1166 return err_iterbuffered();
1167 if (!PyArg_ParseTuple(args, "w*", &pbuf))
1168 return NULL;
1169 ptr = pbuf.buf;
1170 ntodo = pbuf.len;
1171 ndone = 0;
1172 while (ntodo > 0) {
Gregory P. Smithb2ac4d62012-06-25 20:57:36 -07001173 int interrupted;
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001174 FILE_BEGIN_ALLOW_THREADS(f)
1175 errno = 0;
1176 nnow = Py_UniversalNewlineFread(ptr+ndone, ntodo, f->f_fp,
1177 (PyObject *)f);
Gregory P. Smithb2ac4d62012-06-25 20:57:36 -07001178 interrupted = ferror(f->f_fp) && errno == EINTR;
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001179 FILE_END_ALLOW_THREADS(f)
Gregory P. Smithb2ac4d62012-06-25 20:57:36 -07001180 if (interrupted) {
1181 clearerr(f->f_fp);
1182 if (PyErr_CheckSignals()) {
1183 PyBuffer_Release(&pbuf);
1184 return NULL;
1185 }
1186 }
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001187 if (nnow == 0) {
Gregory P. Smithb2ac4d62012-06-25 20:57:36 -07001188 if (interrupted)
1189 continue;
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001190 if (!ferror(f->f_fp))
1191 break;
1192 PyErr_SetFromErrno(PyExc_IOError);
1193 clearerr(f->f_fp);
1194 PyBuffer_Release(&pbuf);
1195 return NULL;
1196 }
1197 ndone += nnow;
1198 ntodo -= nnow;
1199 }
1200 PyBuffer_Release(&pbuf);
1201 return PyInt_FromSsize_t(ndone);
Guido van Rossumfdf95dd1997-05-05 22:15:02 +00001202}
1203
Tim Peters86821b22001-01-07 21:19:34 +00001204/**************************************************************************
Tim Petersf29b64d2001-01-15 06:33:19 +00001205Routine to get next line using platform fgets().
Tim Peters86821b22001-01-07 21:19:34 +00001206
1207Under MSVC 6:
1208
Tim Peters1c733232001-01-08 04:02:07 +00001209+ MS threadsafe getc is very slow (multiple layers of function calls before+
1210 after each character, to lock+unlock the stream).
1211+ The stream-locking functions are MS-internal -- can't access them from user
1212 code.
1213+ There's nothing Tim could find in the MS C or platform SDK libraries that
1214 can worm around this.
Tim Peters86821b22001-01-07 21:19:34 +00001215+ MS fgets locks/unlocks only once per line; it's the only hook we have.
1216
1217So we use fgets for speed(!), despite that it's painful.
1218
1219MS realloc is also slow.
1220
Tim Petersf29b64d2001-01-15 06:33:19 +00001221Reports from other platforms on this method vs getc_unlocked (which MS doesn't
1222have):
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001223 Linux a wash
1224 Solaris a wash
1225 Tru64 Unix getline_via_fgets significantly faster
Tim Peters86821b22001-01-07 21:19:34 +00001226
Tim Petersf29b64d2001-01-15 06:33:19 +00001227CAUTION: The C std isn't clear about this: in those cases where fgets
1228writes something into the buffer, can it write into any position beyond the
1229required trailing null byte? MSVC 6 fgets does not, and no platform is (yet)
1230known on which it does; and it would be a strange way to code fgets. Still,
1231getline_via_fgets may not work correctly if it does. The std test
1232test_bufio.py should fail if platform fgets() routinely writes beyond the
1233trailing null byte. #define DONT_USE_FGETS_IN_GETLINE to disable this code.
Tim Peters86821b22001-01-07 21:19:34 +00001234**************************************************************************/
1235
Tim Petersf29b64d2001-01-15 06:33:19 +00001236/* Use this routine if told to, or by default on non-get_unlocked()
1237 * platforms unless told not to. Yikes! Let's spell that out:
1238 * On a platform with getc_unlocked():
1239 * By default, use getc_unlocked().
1240 * If you want to use fgets() instead, #define USE_FGETS_IN_GETLINE.
1241 * On a platform without getc_unlocked():
1242 * By default, use fgets().
1243 * If you don't want to use fgets(), #define DONT_USE_FGETS_IN_GETLINE.
1244 */
1245#if !defined(USE_FGETS_IN_GETLINE) && !defined(HAVE_GETC_UNLOCKED)
1246#define USE_FGETS_IN_GETLINE
Tim Peters86821b22001-01-07 21:19:34 +00001247#endif
1248
Tim Petersf29b64d2001-01-15 06:33:19 +00001249#if defined(DONT_USE_FGETS_IN_GETLINE) && defined(USE_FGETS_IN_GETLINE)
1250#undef USE_FGETS_IN_GETLINE
1251#endif
1252
1253#ifdef USE_FGETS_IN_GETLINE
Tim Peters86821b22001-01-07 21:19:34 +00001254static PyObject*
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +00001255getline_via_fgets(PyFileObject *f, FILE *fp)
Tim Peters86821b22001-01-07 21:19:34 +00001256{
Tim Peters15b83852001-01-08 00:53:12 +00001257/* INITBUFSIZE is the maximum line length that lets us get away with the fast
Tim Peters142297a2001-01-15 10:36:56 +00001258 * no-realloc, one-fgets()-call path. Boosting it isn't free, because we have
1259 * to fill this much of the buffer with a known value in order to figure out
1260 * how much of the buffer fgets() overwrites. So if INITBUFSIZE is larger
1261 * than "most" lines, we waste time filling unused buffer slots. 100 is
1262 * surely adequate for most peoples' email archives, chewing over source code,
1263 * etc -- "regular old text files".
1264 * MAXBUFSIZE is the maximum line length that lets us get away with the less
1265 * fast (but still zippy) no-realloc, two-fgets()-call path. See above for
1266 * cautions about boosting that. 300 was chosen because the worst real-life
1267 * text-crunching job reported on Python-Dev was a mail-log crawler where over
1268 * half the lines were 254 chars.
Tim Peters15b83852001-01-08 00:53:12 +00001269 */
Tim Peters142297a2001-01-15 10:36:56 +00001270#define INITBUFSIZE 100
1271#define MAXBUFSIZE 300
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001272 char* p; /* temp */
1273 char buf[MAXBUFSIZE];
1274 PyObject* v; /* the string object result */
1275 char* pvfree; /* address of next free slot */
1276 char* pvend; /* address one beyond last free slot */
1277 size_t nfree; /* # of free buffer slots; pvend-pvfree */
1278 size_t total_v_size; /* total # of slots in buffer */
1279 size_t increment; /* amount to increment the buffer */
1280 size_t prev_v_size;
Tim Peters86821b22001-01-07 21:19:34 +00001281
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001282 /* Optimize for normal case: avoid _PyString_Resize if at all
1283 * possible via first reading into stack buffer "buf".
1284 */
1285 total_v_size = INITBUFSIZE; /* start small and pray */
1286 pvfree = buf;
1287 for (;;) {
1288 FILE_BEGIN_ALLOW_THREADS(f)
1289 pvend = buf + total_v_size;
1290 nfree = pvend - pvfree;
1291 memset(pvfree, '\n', nfree);
1292 assert(nfree < INT_MAX); /* Should be atmost MAXBUFSIZE */
1293 p = fgets(pvfree, (int)nfree, fp);
1294 FILE_END_ALLOW_THREADS(f)
Tim Peters15b83852001-01-08 00:53:12 +00001295
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001296 if (p == NULL) {
1297 clearerr(fp);
1298 if (PyErr_CheckSignals())
1299 return NULL;
1300 v = PyString_FromStringAndSize(buf, pvfree - buf);
1301 return v;
1302 }
1303 /* fgets read *something* */
1304 p = memchr(pvfree, '\n', nfree);
1305 if (p != NULL) {
1306 /* Did the \n come from fgets or from us?
1307 * Since fgets stops at the first \n, and then writes
1308 * \0, if it's from fgets a \0 must be next. But if
1309 * that's so, it could not have come from us, since
1310 * the \n's we filled the buffer with have only more
1311 * \n's to the right.
1312 */
1313 if (p+1 < pvend && *(p+1) == '\0') {
1314 /* It's from fgets: we win! In particular,
1315 * we haven't done any mallocs yet, and can
1316 * build the final result on the first try.
1317 */
1318 ++p; /* include \n from fgets */
1319 }
1320 else {
1321 /* Must be from us: fgets didn't fill the
1322 * buffer and didn't find a newline, so it
1323 * must be the last and newline-free line of
1324 * the file.
1325 */
1326 assert(p > pvfree && *(p-1) == '\0');
1327 --p; /* don't include \0 from fgets */
1328 }
1329 v = PyString_FromStringAndSize(buf, p - buf);
1330 return v;
1331 }
1332 /* yuck: fgets overwrote all the newlines, i.e. the entire
1333 * buffer. So this line isn't over yet, or maybe it is but
1334 * we're exactly at EOF. If we haven't already, try using the
1335 * rest of the stack buffer.
1336 */
1337 assert(*(pvend-1) == '\0');
1338 if (pvfree == buf) {
1339 pvfree = pvend - 1; /* overwrite trailing null */
1340 total_v_size = MAXBUFSIZE;
1341 }
1342 else
1343 break;
1344 }
Tim Peters142297a2001-01-15 10:36:56 +00001345
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001346 /* The stack buffer isn't big enough; malloc a string object and read
1347 * into its buffer.
1348 */
1349 total_v_size = MAXBUFSIZE << 1;
1350 v = PyString_FromStringAndSize((char*)NULL, (int)total_v_size);
1351 if (v == NULL)
1352 return v;
1353 /* copy over everything except the last null byte */
1354 memcpy(BUF(v), buf, MAXBUFSIZE-1);
1355 pvfree = BUF(v) + MAXBUFSIZE - 1;
Tim Peters86821b22001-01-07 21:19:34 +00001356
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001357 /* Keep reading stuff into v; if it ever ends successfully, break
1358 * after setting p one beyond the end of the line. The code here is
1359 * very much like the code above, except reads into v's buffer; see
1360 * the code above for detailed comments about the logic.
1361 */
1362 for (;;) {
1363 FILE_BEGIN_ALLOW_THREADS(f)
1364 pvend = BUF(v) + total_v_size;
1365 nfree = pvend - pvfree;
1366 memset(pvfree, '\n', nfree);
1367 assert(nfree < INT_MAX);
1368 p = fgets(pvfree, (int)nfree, fp);
1369 FILE_END_ALLOW_THREADS(f)
Tim Peters86821b22001-01-07 21:19:34 +00001370
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001371 if (p == NULL) {
1372 clearerr(fp);
1373 if (PyErr_CheckSignals()) {
1374 Py_DECREF(v);
1375 return NULL;
1376 }
1377 p = pvfree;
1378 break;
1379 }
1380 p = memchr(pvfree, '\n', nfree);
1381 if (p != NULL) {
1382 if (p+1 < pvend && *(p+1) == '\0') {
1383 /* \n came from fgets */
1384 ++p;
1385 break;
1386 }
1387 /* \n came from us; last line of file, no newline */
1388 assert(p > pvfree && *(p-1) == '\0');
1389 --p;
1390 break;
1391 }
1392 /* expand buffer and try again */
1393 assert(*(pvend-1) == '\0');
1394 increment = total_v_size >> 2; /* mild exponential growth */
1395 prev_v_size = total_v_size;
1396 total_v_size += increment;
1397 /* check for overflow */
1398 if (total_v_size <= prev_v_size ||
1399 total_v_size > PY_SSIZE_T_MAX) {
1400 PyErr_SetString(PyExc_OverflowError,
1401 "line is longer than a Python string can hold");
1402 Py_DECREF(v);
1403 return NULL;
1404 }
1405 if (_PyString_Resize(&v, (int)total_v_size) < 0)
1406 return NULL;
1407 /* overwrite the trailing null byte */
1408 pvfree = BUF(v) + (prev_v_size - 1);
1409 }
1410 if (BUF(v) + total_v_size != p && _PyString_Resize(&v, p - BUF(v)))
1411 return NULL;
1412 return v;
Tim Peters86821b22001-01-07 21:19:34 +00001413#undef INITBUFSIZE
Tim Peters142297a2001-01-15 10:36:56 +00001414#undef MAXBUFSIZE
Tim Peters86821b22001-01-07 21:19:34 +00001415}
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001416#endif /* ifdef USE_FGETS_IN_GETLINE */
Guido van Rossumfdf95dd1997-05-05 22:15:02 +00001417
Guido van Rossum0bd24411991-04-04 15:21:57 +00001418/* Internal routine to get a line.
1419 Size argument interpretation:
1420 > 0: max length;
Guido van Rossum86282062001-01-08 01:26:47 +00001421 <= 0: read arbitrary line
Guido van Rossumce5ba841991-03-06 13:06:18 +00001422*/
1423
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001424static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +00001425get_line(PyFileObject *f, int n)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001426{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001427 FILE *fp = f->f_fp;
1428 int c;
1429 char *buf, *end;
1430 size_t total_v_size; /* total # of slots in buffer */
1431 size_t used_v_size; /* # used slots in buffer */
1432 size_t increment; /* amount to increment the buffer */
1433 PyObject *v;
1434 int newlinetypes = f->f_newlinetypes;
1435 int skipnextlf = f->f_skipnextlf;
1436 int univ_newline = f->f_univ_newline;
Guido van Rossum0bd24411991-04-04 15:21:57 +00001437
Jack Jansen7b8c7542002-04-14 20:12:41 +00001438#if defined(USE_FGETS_IN_GETLINE)
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001439 if (n <= 0 && !univ_newline )
1440 return getline_via_fgets(f, fp);
Tim Peters86821b22001-01-07 21:19:34 +00001441#endif
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001442 total_v_size = n > 0 ? n : 100;
1443 v = PyString_FromStringAndSize((char *)NULL, total_v_size);
1444 if (v == NULL)
1445 return NULL;
1446 buf = BUF(v);
1447 end = buf + total_v_size;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001448
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001449 for (;;) {
1450 FILE_BEGIN_ALLOW_THREADS(f)
1451 FLOCKFILE(fp);
1452 if (univ_newline) {
1453 c = 'x'; /* Shut up gcc warning */
1454 while ( buf != end && (c = GETC(fp)) != EOF ) {
1455 if (skipnextlf ) {
1456 skipnextlf = 0;
1457 if (c == '\n') {
1458 /* Seeing a \n here with
1459 * skipnextlf true means we
1460 * saw a \r before.
1461 */
1462 newlinetypes |= NEWLINE_CRLF;
1463 c = GETC(fp);
1464 if (c == EOF) break;
1465 } else {
1466 newlinetypes |= NEWLINE_CR;
1467 }
1468 }
1469 if (c == '\r') {
1470 skipnextlf = 1;
1471 c = '\n';
1472 } else if ( c == '\n')
1473 newlinetypes |= NEWLINE_LF;
1474 *buf++ = c;
1475 if (c == '\n') break;
1476 }
Gregory P. Smithb2ac4d62012-06-25 20:57:36 -07001477 if (c == EOF) {
1478 if (ferror(fp) && errno == EINTR) {
1479 FUNLOCKFILE(fp);
1480 FILE_ABORT_ALLOW_THREADS(f)
1481 f->f_newlinetypes = newlinetypes;
1482 f->f_skipnextlf = skipnextlf;
1483
1484 if (PyErr_CheckSignals()) {
1485 Py_DECREF(v);
1486 return NULL;
1487 }
1488 /* We executed Python signal handlers and got no exception.
1489 * Now back to reading the line where we left off. */
1490 clearerr(fp);
1491 continue;
1492 }
1493 if (skipnextlf)
1494 newlinetypes |= NEWLINE_CR;
1495 }
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001496 } else /* If not universal newlines use the normal loop */
1497 while ((c = GETC(fp)) != EOF &&
1498 (*buf++ = c) != '\n' &&
1499 buf != end)
1500 ;
1501 FUNLOCKFILE(fp);
1502 FILE_END_ALLOW_THREADS(f)
1503 f->f_newlinetypes = newlinetypes;
1504 f->f_skipnextlf = skipnextlf;
1505 if (c == '\n')
1506 break;
1507 if (c == EOF) {
1508 if (ferror(fp)) {
Gregory P. Smithb2ac4d62012-06-25 20:57:36 -07001509 if (errno == EINTR) {
1510 if (PyErr_CheckSignals()) {
1511 Py_DECREF(v);
1512 return NULL;
1513 }
1514 /* We executed Python signal handlers and got no exception.
1515 * Now back to reading the line where we left off. */
1516 clearerr(fp);
1517 continue;
1518 }
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001519 PyErr_SetFromErrno(PyExc_IOError);
1520 clearerr(fp);
1521 Py_DECREF(v);
1522 return NULL;
1523 }
1524 clearerr(fp);
1525 if (PyErr_CheckSignals()) {
1526 Py_DECREF(v);
1527 return NULL;
1528 }
1529 break;
1530 }
1531 /* Must be because buf == end */
1532 if (n > 0)
1533 break;
1534 used_v_size = total_v_size;
1535 increment = total_v_size >> 2; /* mild exponential growth */
1536 total_v_size += increment;
1537 if (total_v_size > PY_SSIZE_T_MAX) {
1538 PyErr_SetString(PyExc_OverflowError,
1539 "line is longer than a Python string can hold");
1540 Py_DECREF(v);
1541 return NULL;
1542 }
1543 if (_PyString_Resize(&v, total_v_size) < 0)
1544 return NULL;
1545 buf = BUF(v) + used_v_size;
1546 end = BUF(v) + total_v_size;
1547 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001548
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001549 used_v_size = buf - BUF(v);
1550 if (used_v_size != total_v_size && _PyString_Resize(&v, used_v_size))
1551 return NULL;
1552 return v;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001553}
1554
Guido van Rossum0bd24411991-04-04 15:21:57 +00001555/* External C interface */
1556
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001557PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +00001558PyFile_GetLine(PyObject *f, int n)
Guido van Rossum0bd24411991-04-04 15:21:57 +00001559{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001560 PyObject *result;
Guido van Rossum4ddf0a02001-01-07 20:51:39 +00001561
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001562 if (f == NULL) {
1563 PyErr_BadInternalCall();
1564 return NULL;
1565 }
Guido van Rossum4ddf0a02001-01-07 20:51:39 +00001566
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001567 if (PyFile_Check(f)) {
1568 PyFileObject *fo = (PyFileObject *)f;
1569 if (fo->f_fp == NULL)
1570 return err_closed();
1571 if (!fo->readable)
1572 return err_mode("reading");
1573 /* refuse to mix with f.next() */
1574 if (fo->f_buf != NULL &&
1575 (fo->f_bufend - fo->f_bufptr) > 0 &&
1576 fo->f_buf[0] != '\0')
1577 return err_iterbuffered();
1578 result = get_line(fo, n);
1579 }
1580 else {
1581 PyObject *reader;
1582 PyObject *args;
Guido van Rossum4ddf0a02001-01-07 20:51:39 +00001583
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001584 reader = PyObject_GetAttrString(f, "readline");
1585 if (reader == NULL)
1586 return NULL;
1587 if (n <= 0)
1588 args = PyTuple_New(0);
1589 else
1590 args = Py_BuildValue("(i)", n);
1591 if (args == NULL) {
1592 Py_DECREF(reader);
1593 return NULL;
1594 }
1595 result = PyEval_CallObject(reader, args);
1596 Py_DECREF(reader);
1597 Py_DECREF(args);
1598 if (result != NULL && !PyString_Check(result) &&
1599 !PyUnicode_Check(result)) {
1600 Py_DECREF(result);
1601 result = NULL;
1602 PyErr_SetString(PyExc_TypeError,
1603 "object.readline() returned non-string");
1604 }
1605 }
Guido van Rossum4ddf0a02001-01-07 20:51:39 +00001606
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001607 if (n < 0 && result != NULL && PyString_Check(result)) {
1608 char *s = PyString_AS_STRING(result);
1609 Py_ssize_t len = PyString_GET_SIZE(result);
1610 if (len == 0) {
1611 Py_DECREF(result);
1612 result = NULL;
1613 PyErr_SetString(PyExc_EOFError,
1614 "EOF when reading a line");
1615 }
1616 else if (s[len-1] == '\n') {
1617 if (result->ob_refcnt == 1) {
1618 if (_PyString_Resize(&result, len-1))
1619 return NULL;
1620 }
1621 else {
1622 PyObject *v;
1623 v = PyString_FromStringAndSize(s, len-1);
1624 Py_DECREF(result);
1625 result = v;
1626 }
1627 }
1628 }
Martin v. Löwisaf6a27a2003-01-03 19:16:14 +00001629#ifdef Py_USING_UNICODE
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001630 if (n < 0 && result != NULL && PyUnicode_Check(result)) {
1631 Py_UNICODE *s = PyUnicode_AS_UNICODE(result);
1632 Py_ssize_t len = PyUnicode_GET_SIZE(result);
1633 if (len == 0) {
1634 Py_DECREF(result);
1635 result = NULL;
1636 PyErr_SetString(PyExc_EOFError,
1637 "EOF when reading a line");
1638 }
1639 else if (s[len-1] == '\n') {
1640 if (result->ob_refcnt == 1)
1641 PyUnicode_Resize(&result, len-1);
1642 else {
1643 PyObject *v;
1644 v = PyUnicode_FromUnicode(s, len-1);
1645 Py_DECREF(result);
1646 result = v;
1647 }
1648 }
1649 }
Martin v. Löwisaf6a27a2003-01-03 19:16:14 +00001650#endif
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001651 return result;
Guido van Rossum0bd24411991-04-04 15:21:57 +00001652}
1653
1654/* Python method */
1655
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001656static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +00001657file_readline(PyFileObject *f, PyObject *args)
Guido van Rossum0bd24411991-04-04 15:21:57 +00001658{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001659 int n = -1;
Guido van Rossum0bd24411991-04-04 15:21:57 +00001660
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001661 if (f->f_fp == NULL)
1662 return err_closed();
1663 if (!f->readable)
1664 return err_mode("reading");
1665 /* refuse to mix with f.next() */
1666 if (f->f_buf != NULL &&
1667 (f->f_bufend - f->f_bufptr) > 0 &&
1668 f->f_buf[0] != '\0')
1669 return err_iterbuffered();
1670 if (!PyArg_ParseTuple(args, "|i:readline", &n))
1671 return NULL;
1672 if (n == 0)
1673 return PyString_FromString("");
1674 if (n < 0)
1675 n = 0;
1676 return get_line(f, n);
Guido van Rossum0bd24411991-04-04 15:21:57 +00001677}
1678
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001679static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +00001680file_readlines(PyFileObject *f, PyObject *args)
Guido van Rossumce5ba841991-03-06 13:06:18 +00001681{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001682 long sizehint = 0;
1683 PyObject *list = NULL;
1684 PyObject *line;
1685 char small_buffer[SMALLCHUNK];
1686 char *buffer = small_buffer;
1687 size_t buffersize = SMALLCHUNK;
1688 PyObject *big_buffer = NULL;
1689 size_t nfilled = 0;
1690 size_t nread;
1691 size_t totalread = 0;
1692 char *p, *q, *end;
1693 int err;
Gregory P. Smithb2ac4d62012-06-25 20:57:36 -07001694 int shortread = 0; /* bool, did the previous read come up short? */
Guido van Rossum0bd24411991-04-04 15:21:57 +00001695
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001696 if (f->f_fp == NULL)
1697 return err_closed();
1698 if (!f->readable)
1699 return err_mode("reading");
1700 /* refuse to mix with f.next() */
1701 if (f->f_buf != NULL &&
1702 (f->f_bufend - f->f_bufptr) > 0 &&
1703 f->f_buf[0] != '\0')
1704 return err_iterbuffered();
1705 if (!PyArg_ParseTuple(args, "|l:readlines", &sizehint))
1706 return NULL;
1707 if ((list = PyList_New(0)) == NULL)
1708 return NULL;
1709 for (;;) {
1710 if (shortread)
1711 nread = 0;
1712 else {
1713 FILE_BEGIN_ALLOW_THREADS(f)
1714 errno = 0;
1715 nread = Py_UniversalNewlineFread(buffer+nfilled,
1716 buffersize-nfilled, f->f_fp, (PyObject *)f);
1717 FILE_END_ALLOW_THREADS(f)
1718 shortread = (nread < buffersize-nfilled);
1719 }
1720 if (nread == 0) {
1721 sizehint = 0;
1722 if (!ferror(f->f_fp))
1723 break;
Gregory P. Smithb2ac4d62012-06-25 20:57:36 -07001724 if (errno == EINTR) {
1725 if (PyErr_CheckSignals()) {
1726 goto error;
1727 }
1728 clearerr(f->f_fp);
1729 shortread = 0;
1730 continue;
1731 }
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001732 PyErr_SetFromErrno(PyExc_IOError);
1733 clearerr(f->f_fp);
1734 goto error;
1735 }
1736 totalread += nread;
1737 p = (char *)memchr(buffer+nfilled, '\n', nread);
1738 if (p == NULL) {
1739 /* Need a larger buffer to fit this line */
1740 nfilled += nread;
1741 buffersize *= 2;
1742 if (buffersize > PY_SSIZE_T_MAX) {
1743 PyErr_SetString(PyExc_OverflowError,
1744 "line is longer than a Python string can hold");
1745 goto error;
1746 }
1747 if (big_buffer == NULL) {
1748 /* Create the big buffer */
1749 big_buffer = PyString_FromStringAndSize(
1750 NULL, buffersize);
1751 if (big_buffer == NULL)
1752 goto error;
1753 buffer = PyString_AS_STRING(big_buffer);
1754 memcpy(buffer, small_buffer, nfilled);
1755 }
1756 else {
1757 /* Grow the big buffer */
1758 if ( _PyString_Resize(&big_buffer, buffersize) < 0 )
1759 goto error;
1760 buffer = PyString_AS_STRING(big_buffer);
1761 }
1762 continue;
1763 }
1764 end = buffer+nfilled+nread;
1765 q = buffer;
1766 do {
1767 /* Process complete lines */
1768 p++;
1769 line = PyString_FromStringAndSize(q, p-q);
1770 if (line == NULL)
1771 goto error;
1772 err = PyList_Append(list, line);
1773 Py_DECREF(line);
1774 if (err != 0)
1775 goto error;
1776 q = p;
1777 p = (char *)memchr(q, '\n', end-q);
1778 } while (p != NULL);
1779 /* Move the remaining incomplete line to the start */
1780 nfilled = end-q;
1781 memmove(buffer, q, nfilled);
1782 if (sizehint > 0)
1783 if (totalread >= (size_t)sizehint)
1784 break;
1785 }
1786 if (nfilled != 0) {
1787 /* Partial last line */
1788 line = PyString_FromStringAndSize(buffer, nfilled);
1789 if (line == NULL)
1790 goto error;
1791 if (sizehint > 0) {
1792 /* Need to complete the last line */
1793 PyObject *rest = get_line(f, 0);
1794 if (rest == NULL) {
1795 Py_DECREF(line);
1796 goto error;
1797 }
1798 PyString_Concat(&line, rest);
1799 Py_DECREF(rest);
1800 if (line == NULL)
1801 goto error;
1802 }
1803 err = PyList_Append(list, line);
1804 Py_DECREF(line);
1805 if (err != 0)
1806 goto error;
1807 }
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +00001808
1809cleanup:
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001810 Py_XDECREF(big_buffer);
1811 return list;
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +00001812
1813error:
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001814 Py_CLEAR(list);
1815 goto cleanup;
Guido van Rossumce5ba841991-03-06 13:06:18 +00001816}
1817
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001818static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +00001819file_write(PyFileObject *f, PyObject *args)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001820{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001821 Py_buffer pbuf;
Victor Stinnercaafd772010-09-08 10:51:01 +00001822 const char *s;
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001823 Py_ssize_t n, n2;
Victor Stinnercaafd772010-09-08 10:51:01 +00001824 PyObject *encoded = NULL;
Serhiy Storchaka78ad6582013-12-17 17:32:20 +02001825 int err_flag = 0, err;
Victor Stinnercaafd772010-09-08 10:51:01 +00001826
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001827 if (f->f_fp == NULL)
1828 return err_closed();
1829 if (!f->writable)
1830 return err_mode("writing");
1831 if (f->f_binary) {
1832 if (!PyArg_ParseTuple(args, "s*", &pbuf))
1833 return NULL;
1834 s = pbuf.buf;
1835 n = pbuf.len;
Victor Stinnercaafd772010-09-08 10:51:01 +00001836 }
1837 else {
Victor Stinnercaafd772010-09-08 10:51:01 +00001838 PyObject *text;
1839 if (!PyArg_ParseTuple(args, "O", &text))
1840 return NULL;
1841
1842 if (PyString_Check(text)) {
1843 s = PyString_AS_STRING(text);
1844 n = PyString_GET_SIZE(text);
Benjamin Peterson5ca88d22013-01-01 23:04:16 -06001845#ifdef Py_USING_UNICODE
Victor Stinnercaafd772010-09-08 10:51:01 +00001846 } else if (PyUnicode_Check(text)) {
Benjamin Peterson5ca88d22013-01-01 23:04:16 -06001847 const char *encoding, *errors;
Victor Stinnercaafd772010-09-08 10:51:01 +00001848 if (f->f_encoding != Py_None)
1849 encoding = PyString_AS_STRING(f->f_encoding);
1850 else
1851 encoding = PyUnicode_GetDefaultEncoding();
1852 if (f->f_errors != Py_None)
1853 errors = PyString_AS_STRING(f->f_errors);
1854 else
1855 errors = "strict";
1856 encoded = PyUnicode_AsEncodedString(text, encoding, errors);
1857 if (encoded == NULL)
1858 return NULL;
1859 s = PyString_AS_STRING(encoded);
1860 n = PyString_GET_SIZE(encoded);
Benjamin Peterson5ca88d22013-01-01 23:04:16 -06001861#endif
Victor Stinnercaafd772010-09-08 10:51:01 +00001862 } else {
1863 if (PyObject_AsCharBuffer(text, &s, &n))
1864 return NULL;
1865 }
1866 }
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001867 f->f_softspace = 0;
1868 FILE_BEGIN_ALLOW_THREADS(f)
1869 errno = 0;
1870 n2 = fwrite(s, 1, n, f->f_fp);
Serhiy Storchaka78ad6582013-12-17 17:32:20 +02001871 if (n2 != n || ferror(f->f_fp)) {
1872 err_flag = 1;
Serhiy Storchaka6d562312013-12-17 14:40:06 +02001873 err = errno;
Serhiy Storchaka78ad6582013-12-17 17:32:20 +02001874 }
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001875 FILE_END_ALLOW_THREADS(f)
Victor Stinnercaafd772010-09-08 10:51:01 +00001876 Py_XDECREF(encoded);
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001877 if (f->f_binary)
1878 PyBuffer_Release(&pbuf);
Serhiy Storchaka78ad6582013-12-17 17:32:20 +02001879 if (err_flag) {
Serhiy Storchaka6d562312013-12-17 14:40:06 +02001880 errno = err;
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001881 PyErr_SetFromErrno(PyExc_IOError);
1882 clearerr(f->f_fp);
1883 return NULL;
1884 }
1885 Py_INCREF(Py_None);
1886 return Py_None;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001887}
1888
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001889static PyObject *
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001890file_writelines(PyFileObject *f, PyObject *seq)
Guido van Rossum5a2a6831993-10-25 09:59:04 +00001891{
Guido van Rossumee70ad12000-03-13 16:27:06 +00001892#define CHUNKSIZE 1000
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001893 PyObject *list, *line;
1894 PyObject *it; /* iter(seq) */
1895 PyObject *result;
1896 int index, islist;
1897 Py_ssize_t i, j, nwritten, len;
Guido van Rossumee70ad12000-03-13 16:27:06 +00001898
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001899 assert(seq != NULL);
1900 if (f->f_fp == NULL)
1901 return err_closed();
1902 if (!f->writable)
1903 return err_mode("writing");
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001904
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001905 result = NULL;
1906 list = NULL;
1907 islist = PyList_Check(seq);
1908 if (islist)
1909 it = NULL;
1910 else {
1911 it = PyObject_GetIter(seq);
1912 if (it == NULL) {
1913 PyErr_SetString(PyExc_TypeError,
1914 "writelines() requires an iterable argument");
1915 return NULL;
1916 }
1917 /* From here on, fail by going to error, to reclaim "it". */
1918 list = PyList_New(CHUNKSIZE);
1919 if (list == NULL)
1920 goto error;
1921 }
Guido van Rossumee70ad12000-03-13 16:27:06 +00001922
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001923 /* Strategy: slurp CHUNKSIZE lines into a private list,
1924 checking that they are all strings, then write that list
1925 without holding the interpreter lock, then come back for more. */
1926 for (index = 0; ; index += CHUNKSIZE) {
1927 if (islist) {
1928 Py_XDECREF(list);
1929 list = PyList_GetSlice(seq, index, index+CHUNKSIZE);
1930 if (list == NULL)
1931 goto error;
1932 j = PyList_GET_SIZE(list);
1933 }
1934 else {
1935 for (j = 0; j < CHUNKSIZE; j++) {
1936 line = PyIter_Next(it);
1937 if (line == NULL) {
1938 if (PyErr_Occurred())
1939 goto error;
1940 break;
1941 }
1942 PyList_SetItem(list, j, line);
1943 }
Benjamin Petersonbf775542010-10-16 19:20:12 +00001944 /* The iterator might have closed the file on us. */
1945 if (f->f_fp == NULL) {
1946 err_closed();
1947 goto error;
1948 }
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001949 }
1950 if (j == 0)
1951 break;
Guido van Rossumee70ad12000-03-13 16:27:06 +00001952
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001953 /* Check that all entries are indeed strings. If not,
1954 apply the same rules as for file.write() and
1955 convert the results to strings. This is slow, but
1956 seems to be the only way since all conversion APIs
1957 could potentially execute Python code. */
1958 for (i = 0; i < j; i++) {
1959 PyObject *v = PyList_GET_ITEM(list, i);
1960 if (!PyString_Check(v)) {
1961 const char *buffer;
Antoine Pitroub0acc1b2014-05-08 19:26:04 +02001962 int res;
1963 if (f->f_binary) {
1964 res = PyObject_AsReadBuffer(v, (const void**)&buffer, &len);
1965 } else {
1966 res = PyObject_AsCharBuffer(v, &buffer, &len);
1967 }
1968 if (res) {
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001969 PyErr_SetString(PyExc_TypeError,
1970 "writelines() argument must be a sequence of strings");
1971 goto error;
1972 }
1973 line = PyString_FromStringAndSize(buffer,
1974 len);
1975 if (line == NULL)
1976 goto error;
1977 Py_DECREF(v);
1978 PyList_SET_ITEM(list, i, line);
1979 }
1980 }
Marc-André Lemburg6ef68b52000-08-25 22:39:50 +00001981
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001982 /* Since we are releasing the global lock, the
1983 following code may *not* execute Python code. */
1984 f->f_softspace = 0;
1985 FILE_BEGIN_ALLOW_THREADS(f)
1986 errno = 0;
1987 for (i = 0; i < j; i++) {
1988 line = PyList_GET_ITEM(list, i);
1989 len = PyString_GET_SIZE(line);
1990 nwritten = fwrite(PyString_AS_STRING(line),
1991 1, len, f->f_fp);
1992 if (nwritten != len) {
1993 FILE_ABORT_ALLOW_THREADS(f)
1994 PyErr_SetFromErrno(PyExc_IOError);
1995 clearerr(f->f_fp);
1996 goto error;
1997 }
1998 }
1999 FILE_END_ALLOW_THREADS(f)
Guido van Rossumee70ad12000-03-13 16:27:06 +00002000
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002001 if (j < CHUNKSIZE)
2002 break;
2003 }
Guido van Rossumee70ad12000-03-13 16:27:06 +00002004
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002005 Py_INCREF(Py_None);
2006 result = Py_None;
Guido van Rossumee70ad12000-03-13 16:27:06 +00002007 error:
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002008 Py_XDECREF(list);
2009 Py_XDECREF(it);
2010 return result;
Tim Peters2c9aa5e2001-09-23 04:06:05 +00002011#undef CHUNKSIZE
Guido van Rossum5a2a6831993-10-25 09:59:04 +00002012}
2013
Guido van Rossum7a6e9592002-08-06 15:55:28 +00002014static PyObject *
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00002015file_self(PyFileObject *f)
Guido van Rossum7a6e9592002-08-06 15:55:28 +00002016{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002017 if (f->f_fp == NULL)
2018 return err_closed();
2019 Py_INCREF(f);
2020 return (PyObject *)f;
Guido van Rossum7a6e9592002-08-06 15:55:28 +00002021}
2022
Georg Brandl98b40ad2006-06-08 14:50:21 +00002023static PyObject *
Georg Brandla9916b52008-05-17 22:11:54 +00002024file_xreadlines(PyFileObject *f)
2025{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002026 if (PyErr_WarnPy3k("f.xreadlines() not supported in 3.x, "
2027 "try 'for line in f' instead", 1) < 0)
2028 return NULL;
2029 return file_self(f);
Georg Brandla9916b52008-05-17 22:11:54 +00002030}
2031
2032static PyObject *
Georg Brandlad61bc82008-02-23 15:11:18 +00002033file_exit(PyObject *f, PyObject *args)
Georg Brandl98b40ad2006-06-08 14:50:21 +00002034{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002035 PyObject *ret = PyObject_CallMethod(f, "close", NULL);
2036 if (!ret)
2037 /* If error occurred, pass through */
2038 return NULL;
2039 Py_DECREF(ret);
2040 /* We cannot return the result of close since a true
2041 * value will be interpreted as "yes, swallow the
2042 * exception if one was raised inside the with block". */
2043 Py_RETURN_NONE;
Georg Brandl98b40ad2006-06-08 14:50:21 +00002044}
2045
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002046PyDoc_STRVAR(readline_doc,
Tim Petersefc3a3a2001-09-20 07:55:22 +00002047"readline([size]) -> next line from the file, as a string.\n"
2048"\n"
2049"Retain newline. A non-negative size argument limits the maximum\n"
2050"number of bytes to return (an incomplete line may be returned then).\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002051"Return an empty string at EOF.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00002052
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002053PyDoc_STRVAR(read_doc,
Tim Petersefc3a3a2001-09-20 07:55:22 +00002054"read([size]) -> read at most size bytes, returned as a string.\n"
2055"\n"
Gustavo Niemeyer786ddb22002-12-16 18:12:53 +00002056"If the size argument is negative or omitted, read until EOF is reached.\n"
2057"Notice that when in non-blocking mode, less data than what was requested\n"
2058"may be returned, even if no size parameter was given.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00002059
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002060PyDoc_STRVAR(write_doc,
Tim Petersefc3a3a2001-09-20 07:55:22 +00002061"write(str) -> None. Write string str to file.\n"
2062"\n"
2063"Note that due to buffering, flush() or close() may be needed before\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002064"the file on disk reflects the data written.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00002065
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002066PyDoc_STRVAR(fileno_doc,
Tim Petersefc3a3a2001-09-20 07:55:22 +00002067"fileno() -> integer \"file descriptor\".\n"
2068"\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002069"This is needed for lower-level file interfaces, such os.read().");
Tim Petersefc3a3a2001-09-20 07:55:22 +00002070
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002071PyDoc_STRVAR(seek_doc,
Tim Petersefc3a3a2001-09-20 07:55:22 +00002072"seek(offset[, whence]) -> None. Move to new file position.\n"
2073"\n"
2074"Argument offset is a byte count. Optional argument whence defaults to\n"
2075"0 (offset from start of file, offset should be >= 0); other values are 1\n"
2076"(move relative to current position, positive or negative), and 2 (move\n"
2077"relative to end of file, usually negative, although many platforms allow\n"
Martin v. Löwis849a9722003-10-18 09:38:01 +00002078"seeking beyond the end of a file). If the file is opened in text mode,\n"
2079"only offsets returned by tell() are legal. Use of other offsets causes\n"
2080"undefined behavior."
Tim Petersefc3a3a2001-09-20 07:55:22 +00002081"\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002082"Note that not all file objects are seekable.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00002083
Guido van Rossumd7047b31995-01-02 19:07:15 +00002084#ifdef HAVE_FTRUNCATE
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002085PyDoc_STRVAR(truncate_doc,
Tim Petersefc3a3a2001-09-20 07:55:22 +00002086"truncate([size]) -> None. Truncate the file to at most size bytes.\n"
2087"\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002088"Size defaults to the current file position, as returned by tell().");
Guido van Rossumd7047b31995-01-02 19:07:15 +00002089#endif
Tim Petersefc3a3a2001-09-20 07:55:22 +00002090
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002091PyDoc_STRVAR(tell_doc,
2092"tell() -> current file position, an integer (may be a long integer).");
Tim Petersefc3a3a2001-09-20 07:55:22 +00002093
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002094PyDoc_STRVAR(readinto_doc,
2095"readinto() -> Undocumented. Don't use this; it may go away.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00002096
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002097PyDoc_STRVAR(readlines_doc,
Tim Petersefc3a3a2001-09-20 07:55:22 +00002098"readlines([size]) -> list of strings, each a line from the file.\n"
2099"\n"
2100"Call readline() repeatedly and return a list of the lines so read.\n"
2101"The optional size argument, if given, is an approximate bound on the\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002102"total number of bytes in the lines returned.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00002103
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002104PyDoc_STRVAR(xreadlines_doc,
Guido van Rossum7a6e9592002-08-06 15:55:28 +00002105"xreadlines() -> returns self.\n"
Tim Petersefc3a3a2001-09-20 07:55:22 +00002106"\n"
Guido van Rossum7a6e9592002-08-06 15:55:28 +00002107"For backward compatibility. File objects now include the performance\n"
2108"optimizations previously implemented in the xreadlines module.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00002109
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002110PyDoc_STRVAR(writelines_doc,
Tim Peters2c9aa5e2001-09-23 04:06:05 +00002111"writelines(sequence_of_strings) -> None. Write the strings to the file.\n"
Tim Petersefc3a3a2001-09-20 07:55:22 +00002112"\n"
Tim Peters2c9aa5e2001-09-23 04:06:05 +00002113"Note that newlines are not added. The sequence can be any iterable object\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002114"producing strings. This is equivalent to calling write() for each string.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00002115
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002116PyDoc_STRVAR(flush_doc,
2117"flush() -> None. Flush the internal I/O buffer.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00002118
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002119PyDoc_STRVAR(close_doc,
Tim Petersefc3a3a2001-09-20 07:55:22 +00002120"close() -> None or (perhaps) an integer. Close the file.\n"
2121"\n"
Guido van Rossum77f6a652002-04-03 22:41:51 +00002122"Sets data attribute .closed to True. A closed file cannot be used for\n"
Tim Petersefc3a3a2001-09-20 07:55:22 +00002123"further I/O operations. close() may be called more than once without\n"
2124"error. Some kinds of file objects (for example, opened by popen())\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002125"may return an exit status upon closing.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00002126
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002127PyDoc_STRVAR(isatty_doc,
2128"isatty() -> true or false. True if the file is connected to a tty device.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00002129
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00002130PyDoc_STRVAR(enter_doc,
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002131 "__enter__() -> self.");
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00002132
Georg Brandl98b40ad2006-06-08 14:50:21 +00002133PyDoc_STRVAR(exit_doc,
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002134 "__exit__(*excinfo) -> None. Closes the file.");
Georg Brandl98b40ad2006-06-08 14:50:21 +00002135
Tim Petersefc3a3a2001-09-20 07:55:22 +00002136static PyMethodDef file_methods[] = {
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002137 {"readline", (PyCFunction)file_readline, METH_VARARGS, readline_doc},
2138 {"read", (PyCFunction)file_read, METH_VARARGS, read_doc},
2139 {"write", (PyCFunction)file_write, METH_VARARGS, write_doc},
2140 {"fileno", (PyCFunction)file_fileno, METH_NOARGS, fileno_doc},
2141 {"seek", (PyCFunction)file_seek, METH_VARARGS, seek_doc},
Tim Petersefc3a3a2001-09-20 07:55:22 +00002142#ifdef HAVE_FTRUNCATE
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002143 {"truncate", (PyCFunction)file_truncate, METH_VARARGS, truncate_doc},
Tim Petersefc3a3a2001-09-20 07:55:22 +00002144#endif
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002145 {"tell", (PyCFunction)file_tell, METH_NOARGS, tell_doc},
2146 {"readinto", (PyCFunction)file_readinto, METH_VARARGS, readinto_doc},
2147 {"readlines", (PyCFunction)file_readlines, METH_VARARGS, readlines_doc},
2148 {"xreadlines",(PyCFunction)file_xreadlines, METH_NOARGS, xreadlines_doc},
2149 {"writelines",(PyCFunction)file_writelines, METH_O, writelines_doc},
2150 {"flush", (PyCFunction)file_flush, METH_NOARGS, flush_doc},
2151 {"close", (PyCFunction)file_close, METH_NOARGS, close_doc},
2152 {"isatty", (PyCFunction)file_isatty, METH_NOARGS, isatty_doc},
2153 {"__enter__", (PyCFunction)file_self, METH_NOARGS, enter_doc},
2154 {"__exit__", (PyCFunction)file_exit, METH_VARARGS, exit_doc},
2155 {NULL, NULL} /* sentinel */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002156};
2157
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002158#define OFF(x) offsetof(PyFileObject, x)
Guido van Rossumb6775db1994-08-01 11:34:53 +00002159
Guido van Rossum6f799372001-09-20 20:46:19 +00002160static PyMemberDef file_memberlist[] = {
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002161 {"mode", T_OBJECT, OFF(f_mode), RO,
2162 "file mode ('r', 'U', 'w', 'a', possibly with 'b' or '+' added)"},
2163 {"name", T_OBJECT, OFF(f_name), RO,
2164 "file name"},
2165 {"encoding", T_OBJECT, OFF(f_encoding), RO,
2166 "file encoding"},
2167 {"errors", T_OBJECT, OFF(f_errors), RO,
2168 "Unicode error handler"},
2169 /* getattr(f, "closed") is implemented without this table */
2170 {NULL} /* Sentinel */
Guido van Rossumb6775db1994-08-01 11:34:53 +00002171};
2172
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002173static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00002174get_closed(PyFileObject *f, void *closure)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002175{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002176 return PyBool_FromLong((long)(f->f_fp == 0));
Guido van Rossumb6775db1994-08-01 11:34:53 +00002177}
Jack Jansen7b8c7542002-04-14 20:12:41 +00002178static PyObject *
2179get_newlines(PyFileObject *f, void *closure)
2180{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002181 switch (f->f_newlinetypes) {
2182 case NEWLINE_UNKNOWN:
2183 Py_INCREF(Py_None);
2184 return Py_None;
2185 case NEWLINE_CR:
2186 return PyString_FromString("\r");
2187 case NEWLINE_LF:
2188 return PyString_FromString("\n");
2189 case NEWLINE_CR|NEWLINE_LF:
2190 return Py_BuildValue("(ss)", "\r", "\n");
2191 case NEWLINE_CRLF:
2192 return PyString_FromString("\r\n");
2193 case NEWLINE_CR|NEWLINE_CRLF:
2194 return Py_BuildValue("(ss)", "\r", "\r\n");
2195 case NEWLINE_LF|NEWLINE_CRLF:
2196 return Py_BuildValue("(ss)", "\n", "\r\n");
2197 case NEWLINE_CR|NEWLINE_LF|NEWLINE_CRLF:
2198 return Py_BuildValue("(sss)", "\r", "\n", "\r\n");
2199 default:
2200 PyErr_Format(PyExc_SystemError,
2201 "Unknown newlines value 0x%x\n",
2202 f->f_newlinetypes);
2203 return NULL;
2204 }
Jack Jansen7b8c7542002-04-14 20:12:41 +00002205}
Guido van Rossumb6775db1994-08-01 11:34:53 +00002206
Georg Brandl65bb42d2008-03-21 20:38:24 +00002207static PyObject *
2208get_softspace(PyFileObject *f, void *closure)
2209{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002210 if (PyErr_WarnPy3k("file.softspace not supported in 3.x", 1) < 0)
2211 return NULL;
2212 return PyInt_FromLong(f->f_softspace);
Georg Brandl65bb42d2008-03-21 20:38:24 +00002213}
2214
2215static int
2216set_softspace(PyFileObject *f, PyObject *value)
2217{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002218 int new;
2219 if (PyErr_WarnPy3k("file.softspace not supported in 3.x", 1) < 0)
2220 return -1;
Georg Brandl65bb42d2008-03-21 20:38:24 +00002221
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002222 if (value == NULL) {
2223 PyErr_SetString(PyExc_TypeError,
2224 "can't delete softspace attribute");
2225 return -1;
2226 }
Georg Brandl65bb42d2008-03-21 20:38:24 +00002227
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002228 new = PyInt_AsLong(value);
2229 if (new == -1 && PyErr_Occurred())
2230 return -1;
2231 f->f_softspace = new;
2232 return 0;
Georg Brandl65bb42d2008-03-21 20:38:24 +00002233}
2234
Guido van Rossum32d34c82001-09-20 21:45:26 +00002235static PyGetSetDef file_getsetlist[] = {
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002236 {"closed", (getter)get_closed, NULL, "True if the file is closed"},
2237 {"newlines", (getter)get_newlines, NULL,
2238 "end-of-line convention used in this file"},
2239 {"softspace", (getter)get_softspace, (setter)set_softspace,
2240 "flag indicating that a space needs to be printed; used by print"},
2241 {0},
Tim Peters6d6c1a32001-08-02 04:15:00 +00002242};
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002243
Benjamin Petersondbf52e02018-01-02 09:25:41 -08002244typedef struct {
2245 char *buf, *bufptr, *bufend;
2246} readaheadbuffer;
2247
Neal Norwitzd8b995f2002-08-06 21:50:54 +00002248static void
Benjamin Petersondbf52e02018-01-02 09:25:41 -08002249drop_readaheadbuffer(readaheadbuffer *rab)
Guido van Rossum65967252001-04-21 13:20:18 +00002250{
Benjamin Petersondbf52e02018-01-02 09:25:41 -08002251 if (rab->buf != NULL) {
2252 PyMem_FREE(rab->buf);
2253 rab->buf = NULL;
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002254 }
Guido van Rossum65967252001-04-21 13:20:18 +00002255}
2256
Tim Petersf1827cf2003-09-07 03:30:18 +00002257/* Make sure that file has a readahead buffer with at least one byte
2258 (unless at EOF) and no more than bufsize. Returns negative value on
Georg Brandled02eb62006-03-31 20:31:02 +00002259 error, will set MemoryError if bufsize bytes cannot be allocated. */
Neal Norwitzd8b995f2002-08-06 21:50:54 +00002260static int
Benjamin Petersondbf52e02018-01-02 09:25:41 -08002261readahead(PyFileObject *f, readaheadbuffer *rab, Py_ssize_t bufsize)
Neal Norwitzd8b995f2002-08-06 21:50:54 +00002262{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002263 Py_ssize_t chunksize;
Guido van Rossum7a6e9592002-08-06 15:55:28 +00002264
Benjamin Petersondbf52e02018-01-02 09:25:41 -08002265 if (rab->buf != NULL) {
2266 if ((rab->bufend - rab->bufptr) >= 1)
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002267 return 0;
2268 else
Benjamin Petersondbf52e02018-01-02 09:25:41 -08002269 drop_readaheadbuffer(rab);
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002270 }
Benjamin Petersondbf52e02018-01-02 09:25:41 -08002271 if ((rab->buf = PyMem_MALLOC(bufsize)) == NULL) {
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002272 PyErr_NoMemory();
2273 return -1;
2274 }
2275 FILE_BEGIN_ALLOW_THREADS(f)
2276 errno = 0;
Benjamin Petersondbf52e02018-01-02 09:25:41 -08002277 chunksize = Py_UniversalNewlineFread(rab->buf, bufsize, f->f_fp, (PyObject *)f);
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002278 FILE_END_ALLOW_THREADS(f)
2279 if (chunksize == 0) {
2280 if (ferror(f->f_fp)) {
2281 PyErr_SetFromErrno(PyExc_IOError);
2282 clearerr(f->f_fp);
Benjamin Petersondbf52e02018-01-02 09:25:41 -08002283 drop_readaheadbuffer(rab);
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002284 return -1;
2285 }
2286 }
Benjamin Petersondbf52e02018-01-02 09:25:41 -08002287 rab->bufptr = rab->buf;
2288 rab->bufend = rab->buf + chunksize;
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002289 return 0;
Guido van Rossum7a6e9592002-08-06 15:55:28 +00002290}
2291
2292/* Used by file_iternext. The returned string will start with 'skip'
Tim Petersf1827cf2003-09-07 03:30:18 +00002293 uninitialized bytes followed by the remainder of the line. Don't be
2294 horrified by the recursive call: maximum recursion depth is limited by
Guido van Rossum7a6e9592002-08-06 15:55:28 +00002295 logarithmic buffer growth to about 50 even when reading a 1gb line. */
2296
Gregory P. Smithdd96db62008-06-09 04:58:54 +00002297static PyStringObject *
Benjamin Petersondbf52e02018-01-02 09:25:41 -08002298readahead_get_line_skip(PyFileObject *f, readaheadbuffer *rab, Py_ssize_t skip, Py_ssize_t bufsize)
Neal Norwitzd8b995f2002-08-06 21:50:54 +00002299{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002300 PyStringObject* s;
2301 char *bufptr;
2302 char *buf;
2303 Py_ssize_t len;
Guido van Rossum7a6e9592002-08-06 15:55:28 +00002304
Benjamin Petersondbf52e02018-01-02 09:25:41 -08002305 if (rab->buf == NULL)
2306 if (readahead(f, rab, bufsize) < 0)
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002307 return NULL;
Guido van Rossum7a6e9592002-08-06 15:55:28 +00002308
Benjamin Petersondbf52e02018-01-02 09:25:41 -08002309 len = rab->bufend - rab->bufptr;
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002310 if (len == 0)
Benjamin Petersondbf52e02018-01-02 09:25:41 -08002311 return (PyStringObject *)PyString_FromStringAndSize(NULL, skip);
2312 bufptr = (char *)memchr(rab->bufptr, '\n', len);
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002313 if (bufptr != NULL) {
2314 bufptr++; /* Count the '\n' */
Benjamin Petersondbf52e02018-01-02 09:25:41 -08002315 len = bufptr - rab->bufptr;
2316 s = (PyStringObject *)PyString_FromStringAndSize(NULL, skip + len);
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002317 if (s == NULL)
2318 return NULL;
Benjamin Petersondbf52e02018-01-02 09:25:41 -08002319 memcpy(PyString_AS_STRING(s) + skip, rab->bufptr, len);
2320 rab->bufptr = bufptr;
2321 if (bufptr == rab->bufend)
2322 drop_readaheadbuffer(rab);
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002323 } else {
Benjamin Petersondbf52e02018-01-02 09:25:41 -08002324 bufptr = rab->bufptr;
2325 buf = rab->buf;
2326 rab->buf = NULL; /* Force new readahead buffer */
Benjamin Peterson95bc0e42014-09-30 21:17:15 -04002327 assert(len <= PY_SSIZE_T_MAX - skip);
Benjamin Petersondbf52e02018-01-02 09:25:41 -08002328 s = readahead_get_line_skip(f, rab, skip + len, bufsize + (bufsize>>2));
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002329 if (s == NULL) {
Benjamin Petersondbf52e02018-01-02 09:25:41 -08002330 PyMem_FREE(buf);
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002331 return NULL;
2332 }
Benjamin Peterson95bc0e42014-09-30 21:17:15 -04002333 memcpy(PyString_AS_STRING(s) + skip, bufptr, len);
Benjamin Petersondbf52e02018-01-02 09:25:41 -08002334 PyMem_FREE(buf);
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002335 }
2336 return s;
Guido van Rossum7a6e9592002-08-06 15:55:28 +00002337}
2338
2339/* A larger buffer size may actually decrease performance. */
2340#define READAHEAD_BUFSIZE 8192
2341
2342static PyObject *
2343file_iternext(PyFileObject *f)
2344{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002345 PyStringObject* l;
Guido van Rossum7a6e9592002-08-06 15:55:28 +00002346
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002347 if (f->f_fp == NULL)
2348 return err_closed();
2349 if (!f->readable)
2350 return err_mode("reading");
Guido van Rossum7a6e9592002-08-06 15:55:28 +00002351
Benjamin Petersondbf52e02018-01-02 09:25:41 -08002352 {
2353 /*
2354 Multiple threads can enter this method while the GIL is released
2355 during file read and wreak havoc on the file object's readahead
2356 buffer. To avoid dealing with cross-thread coordination issues, we
2357 cache the file buffer state locally and only set it back on the file
2358 object when we're done.
2359 */
2360 readaheadbuffer rab = {f->f_buf, f->f_bufptr, f->f_bufend};
2361 f->f_buf = NULL;
2362 l = readahead_get_line_skip(f, &rab, 0, READAHEAD_BUFSIZE);
2363 /*
2364 Make sure the file's internal read buffer is cleared out. This will
2365 only do anything if some other thread interleaved with us during
2366 readahead. We want to drop any changeling buffer, so we don't leak
2367 memory. We may lose data, but that's what you get for reading the same
2368 file object in multiple threads.
2369 */
2370 drop_file_readahead(f);
2371 f->f_buf = rab.buf;
2372 f->f_bufptr = rab.bufptr;
2373 f->f_bufend = rab.bufend;
2374 }
2375
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002376 if (l == NULL || PyString_GET_SIZE(l) == 0) {
2377 Py_XDECREF(l);
2378 return NULL;
2379 }
2380 return (PyObject *)l;
Guido van Rossum7a6e9592002-08-06 15:55:28 +00002381}
2382
2383
Tim Peters59c9a642001-09-13 05:38:56 +00002384static PyObject *
2385file_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
2386{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002387 PyObject *self;
2388 static PyObject *not_yet_string;
Tim Peters44410012001-09-14 03:26:08 +00002389
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002390 assert(type != NULL && type->tp_alloc != NULL);
Tim Peters44410012001-09-14 03:26:08 +00002391
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002392 if (not_yet_string == NULL) {
2393 not_yet_string = PyString_InternFromString("<uninitialized file>");
2394 if (not_yet_string == NULL)
2395 return NULL;
2396 }
Tim Peters44410012001-09-14 03:26:08 +00002397
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002398 self = type->tp_alloc(type, 0);
2399 if (self != NULL) {
2400 /* Always fill in the name and mode, so that nobody else
2401 needs to special-case NULLs there. */
2402 Py_INCREF(not_yet_string);
2403 ((PyFileObject *)self)->f_name = not_yet_string;
2404 Py_INCREF(not_yet_string);
2405 ((PyFileObject *)self)->f_mode = not_yet_string;
2406 Py_INCREF(Py_None);
2407 ((PyFileObject *)self)->f_encoding = Py_None;
2408 Py_INCREF(Py_None);
2409 ((PyFileObject *)self)->f_errors = Py_None;
2410 ((PyFileObject *)self)->weakreflist = NULL;
2411 ((PyFileObject *)self)->unlocked_count = 0;
2412 }
2413 return self;
Tim Peters44410012001-09-14 03:26:08 +00002414}
2415
2416static int
2417file_init(PyObject *self, PyObject *args, PyObject *kwds)
2418{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002419 PyFileObject *foself = (PyFileObject *)self;
2420 int ret = 0;
2421 static char *kwlist[] = {"name", "mode", "buffering", 0};
2422 char *name = NULL;
2423 char *mode = "r";
2424 int bufsize = -1;
2425 int wideargument = 0;
Hirokazu Yamamoto5c3dd9a2009-06-29 15:52:21 +00002426#ifdef MS_WINDOWS
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002427 PyObject *po;
Hirokazu Yamamoto5c3dd9a2009-06-29 15:52:21 +00002428#endif
Tim Peters44410012001-09-14 03:26:08 +00002429
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002430 assert(PyFile_Check(self));
2431 if (foself->f_fp != NULL) {
2432 /* Have to close the existing file first. */
2433 PyObject *closeresult = file_close(foself);
2434 if (closeresult == NULL)
2435 return -1;
2436 Py_DECREF(closeresult);
2437 }
Tim Peters59c9a642001-09-13 05:38:56 +00002438
Hirokazu Yamamotob24bb272009-05-17 02:52:09 +00002439#ifdef MS_WINDOWS
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002440 if (PyArg_ParseTupleAndKeywords(args, kwds, "U|si:file",
Serhiy Storchaka3c9ce742016-07-01 23:34:44 +03002441 kwlist, &po, &mode, &bufsize) &&
2442 wcslen(PyUnicode_AS_UNICODE(po)) == (size_t)PyUnicode_GET_SIZE(po)) {
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002443 wideargument = 1;
2444 if (fill_file_fields(foself, NULL, po, mode,
2445 fclose) == NULL)
2446 goto Error;
2447 } else {
2448 /* Drop the argument parsing error as narrow
2449 strings are also valid. */
2450 PyErr_Clear();
2451 }
Mark Hammondc2e85bd2002-10-03 05:10:39 +00002452#endif
2453
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002454 if (!wideargument) {
2455 PyObject *o_name;
Nicholas Bastinabce8a62004-03-21 20:24:07 +00002456
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002457 if (!PyArg_ParseTupleAndKeywords(args, kwds, "et|si:file", kwlist,
2458 Py_FileSystemDefaultEncoding,
2459 &name,
2460 &mode, &bufsize))
2461 return -1;
Nicholas Bastinabce8a62004-03-21 20:24:07 +00002462
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002463 /* We parse again to get the name as a PyObject */
2464 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|si:file",
2465 kwlist, &o_name, &mode,
2466 &bufsize))
2467 goto Error;
Nicholas Bastinabce8a62004-03-21 20:24:07 +00002468
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002469 if (fill_file_fields(foself, NULL, o_name, mode,
2470 fclose) == NULL)
2471 goto Error;
2472 }
2473 if (open_the_file(foself, name, mode) == NULL)
2474 goto Error;
2475 foself->f_setbuf = NULL;
2476 PyFile_SetBufSize(self, bufsize);
2477 goto Done;
Tim Peters44410012001-09-14 03:26:08 +00002478
2479Error:
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002480 ret = -1;
2481 /* fall through */
Tim Peters44410012001-09-14 03:26:08 +00002482Done:
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002483 PyMem_Free(name); /* free the encoded string */
2484 return ret;
Tim Peters59c9a642001-09-13 05:38:56 +00002485}
2486
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002487PyDoc_VAR(file_doc) =
2488PyDoc_STR(
Tim Peters59c9a642001-09-13 05:38:56 +00002489"file(name[, mode[, buffering]]) -> file object\n"
2490"\n"
2491"Open a file. The mode can be 'r', 'w' or 'a' for reading (default),\n"
2492"writing or appending. The file will be created if it doesn't exist\n"
2493"when opened for writing or appending; it will be truncated when\n"
2494"opened for writing. Add a 'b' to the mode for binary files.\n"
2495"Add a '+' to the mode to allow simultaneous reading and writing.\n"
2496"If the buffering argument is given, 0 means unbuffered, 1 means line\n"
Skip Montanaro4e3ebe02007-12-08 14:37:43 +00002497"buffered, and larger numbers specify the buffer size. The preferred way\n"
2498"to open a file is with the builtin open() function.\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002499)
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002500PyDoc_STR(
Barry Warsaw4be55b52002-05-22 20:37:53 +00002501"Add a 'U' to mode to open the file for input with universal newline\n"
2502"support. Any line ending in the input file will be seen as a '\\n'\n"
2503"in Python. Also, a file so opened gains the attribute 'newlines';\n"
2504"the value for this attribute is one of None (no newline read yet),\n"
2505"'\\r', '\\n', '\\r\\n' or a tuple containing all the newline types seen.\n"
2506"\n"
2507"'U' cannot be combined with 'w' or '+' mode.\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002508);
Tim Peters59c9a642001-09-13 05:38:56 +00002509
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002510PyTypeObject PyFile_Type = {
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002511 PyVarObject_HEAD_INIT(&PyType_Type, 0)
2512 "file",
2513 sizeof(PyFileObject),
2514 0,
2515 (destructor)file_dealloc, /* tp_dealloc */
2516 0, /* tp_print */
2517 0, /* tp_getattr */
2518 0, /* tp_setattr */
2519 0, /* tp_compare */
2520 (reprfunc)file_repr, /* tp_repr */
2521 0, /* tp_as_number */
2522 0, /* tp_as_sequence */
2523 0, /* tp_as_mapping */
2524 0, /* tp_hash */
2525 0, /* tp_call */
2526 0, /* tp_str */
2527 PyObject_GenericGetAttr, /* tp_getattro */
2528 /* softspace is writable: we must supply tp_setattro */
2529 PyObject_GenericSetAttr, /* tp_setattro */
2530 0, /* tp_as_buffer */
2531 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_WEAKREFS, /* tp_flags */
2532 file_doc, /* tp_doc */
2533 0, /* tp_traverse */
2534 0, /* tp_clear */
2535 0, /* tp_richcompare */
2536 offsetof(PyFileObject, weakreflist), /* tp_weaklistoffset */
2537 (getiterfunc)file_self, /* tp_iter */
2538 (iternextfunc)file_iternext, /* tp_iternext */
2539 file_methods, /* tp_methods */
2540 file_memberlist, /* tp_members */
2541 file_getsetlist, /* tp_getset */
2542 0, /* tp_base */
2543 0, /* tp_dict */
2544 0, /* tp_descr_get */
2545 0, /* tp_descr_set */
2546 0, /* tp_dictoffset */
2547 file_init, /* tp_init */
2548 PyType_GenericAlloc, /* tp_alloc */
2549 file_new, /* tp_new */
2550 PyObject_Del, /* tp_free */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002551};
Guido van Rossumeb183da1991-04-04 10:44:06 +00002552
2553/* Interface for the 'soft space' between print items. */
2554
2555int
Fred Drakefd99de62000-07-09 05:02:18 +00002556PyFile_SoftSpace(PyObject *f, int newflag)
Guido van Rossumeb183da1991-04-04 10:44:06 +00002557{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002558 long oldflag = 0;
2559 if (f == NULL) {
2560 /* Do nothing */
2561 }
2562 else if (PyFile_Check(f)) {
2563 oldflag = ((PyFileObject *)f)->f_softspace;
2564 ((PyFileObject *)f)->f_softspace = newflag;
2565 }
2566 else {
2567 PyObject *v;
2568 v = PyObject_GetAttrString(f, "softspace");
2569 if (v == NULL)
2570 PyErr_Clear();
2571 else {
2572 if (PyInt_Check(v))
2573 oldflag = PyInt_AsLong(v);
2574 assert(oldflag < INT_MAX);
2575 Py_DECREF(v);
2576 }
2577 v = PyInt_FromLong((long)newflag);
2578 if (v == NULL)
2579 PyErr_Clear();
2580 else {
2581 if (PyObject_SetAttrString(f, "softspace", v) != 0)
2582 PyErr_Clear();
2583 Py_DECREF(v);
2584 }
2585 }
2586 return (int)oldflag;
Guido van Rossumeb183da1991-04-04 10:44:06 +00002587}
Guido van Rossum3165fe61992-09-25 21:59:05 +00002588
2589/* Interfaces to write objects/strings to file-like objects */
2590
2591int
Fred Drakefd99de62000-07-09 05:02:18 +00002592PyFile_WriteObject(PyObject *v, PyObject *f, int flags)
Guido van Rossum3165fe61992-09-25 21:59:05 +00002593{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002594 PyObject *writer, *value, *args, *result;
2595 if (f == NULL) {
2596 PyErr_SetString(PyExc_TypeError, "writeobject with NULL file");
2597 return -1;
2598 }
2599 else if (PyFile_Check(f)) {
2600 PyFileObject *fobj = (PyFileObject *) f;
Fred Drake086a0f72004-03-19 15:22:36 +00002601#ifdef Py_USING_UNICODE
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002602 PyObject *enc = fobj->f_encoding;
2603 int result;
Fred Drake086a0f72004-03-19 15:22:36 +00002604#endif
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002605 if (fobj->f_fp == NULL) {
2606 err_closed();
2607 return -1;
2608 }
Martin v. Löwis5467d4c2003-05-10 07:10:12 +00002609#ifdef Py_USING_UNICODE
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002610 if ((flags & Py_PRINT_RAW) &&
2611 PyUnicode_Check(v) && enc != Py_None) {
2612 char *cenc = PyString_AS_STRING(enc);
2613 char *errors = fobj->f_errors == Py_None ?
2614 "strict" : PyString_AS_STRING(fobj->f_errors);
2615 value = PyUnicode_AsEncodedString(v, cenc, errors);
2616 if (value == NULL)
2617 return -1;
2618 } else {
2619 value = v;
2620 Py_INCREF(value);
2621 }
2622 result = file_PyObject_Print(value, fobj, flags);
2623 Py_DECREF(value);
2624 return result;
Martin v. Löwis5467d4c2003-05-10 07:10:12 +00002625#else
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002626 return file_PyObject_Print(v, fobj, flags);
Martin v. Löwis5467d4c2003-05-10 07:10:12 +00002627#endif
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002628 }
2629 writer = PyObject_GetAttrString(f, "write");
2630 if (writer == NULL)
2631 return -1;
2632 if (flags & Py_PRINT_RAW) {
2633 if (PyUnicode_Check(v)) {
2634 value = v;
2635 Py_INCREF(value);
2636 } else
2637 value = PyObject_Str(v);
2638 }
2639 else
2640 value = PyObject_Repr(v);
2641 if (value == NULL) {
2642 Py_DECREF(writer);
2643 return -1;
2644 }
2645 args = PyTuple_Pack(1, value);
2646 if (args == NULL) {
2647 Py_DECREF(value);
2648 Py_DECREF(writer);
2649 return -1;
2650 }
2651 result = PyEval_CallObject(writer, args);
2652 Py_DECREF(args);
2653 Py_DECREF(value);
2654 Py_DECREF(writer);
2655 if (result == NULL)
2656 return -1;
2657 Py_DECREF(result);
2658 return 0;
Guido van Rossum3165fe61992-09-25 21:59:05 +00002659}
2660
Guido van Rossum27a60b11997-05-22 22:25:11 +00002661int
Tim Petersc1bbcb82001-11-28 22:13:25 +00002662PyFile_WriteString(const char *s, PyObject *f)
Guido van Rossum3165fe61992-09-25 21:59:05 +00002663{
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +00002664
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002665 if (f == NULL) {
2666 /* Should be caused by a pre-existing error */
2667 if (!PyErr_Occurred())
2668 PyErr_SetString(PyExc_SystemError,
2669 "null file for PyFile_WriteString");
2670 return -1;
2671 }
2672 else if (PyFile_Check(f)) {
2673 PyFileObject *fobj = (PyFileObject *) f;
2674 FILE *fp = PyFile_AsFile(f);
2675 if (fp == NULL) {
2676 err_closed();
2677 return -1;
2678 }
2679 FILE_BEGIN_ALLOW_THREADS(fobj)
2680 fputs(s, fp);
2681 FILE_END_ALLOW_THREADS(fobj)
2682 return 0;
2683 }
2684 else if (!PyErr_Occurred()) {
2685 PyObject *v = PyString_FromString(s);
2686 int err;
2687 if (v == NULL)
2688 return -1;
2689 err = PyFile_WriteObject(v, f, Py_PRINT_RAW);
2690 Py_DECREF(v);
2691 return err;
2692 }
2693 else
2694 return -1;
Guido van Rossum3165fe61992-09-25 21:59:05 +00002695}
Andrew M. Kuchling06051ed2000-07-13 23:56:54 +00002696
2697/* Try to get a file-descriptor from a Python object. If the object
2698 is an integer or long integer, its value is returned. If not, the
2699 object's fileno() method is called if it exists; the method must return
2700 an integer or long integer, which is returned as the file descriptor value.
2701 -1 is returned on failure.
2702*/
2703
2704int PyObject_AsFileDescriptor(PyObject *o)
2705{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002706 int fd;
2707 PyObject *meth;
Andrew M. Kuchling06051ed2000-07-13 23:56:54 +00002708
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002709 if (PyInt_Check(o)) {
Serhiy Storchaka74f49ab2013-01-19 12:55:39 +02002710 fd = _PyInt_AsInt(o);
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002711 }
2712 else if (PyLong_Check(o)) {
Serhiy Storchaka74f49ab2013-01-19 12:55:39 +02002713 fd = _PyLong_AsInt(o);
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002714 }
2715 else if ((meth = PyObject_GetAttrString(o, "fileno")) != NULL)
2716 {
2717 PyObject *fno = PyEval_CallObject(meth, NULL);
2718 Py_DECREF(meth);
2719 if (fno == NULL)
2720 return -1;
Tim Peters86821b22001-01-07 21:19:34 +00002721
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002722 if (PyInt_Check(fno)) {
Serhiy Storchaka74f49ab2013-01-19 12:55:39 +02002723 fd = _PyInt_AsInt(fno);
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002724 Py_DECREF(fno);
2725 }
2726 else if (PyLong_Check(fno)) {
Serhiy Storchaka74f49ab2013-01-19 12:55:39 +02002727 fd = _PyLong_AsInt(fno);
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002728 Py_DECREF(fno);
2729 }
2730 else {
2731 PyErr_SetString(PyExc_TypeError,
2732 "fileno() returned a non-integer");
2733 Py_DECREF(fno);
2734 return -1;
2735 }
2736 }
2737 else {
2738 PyErr_SetString(PyExc_TypeError,
Serhiy Storchaka6401e562017-11-10 12:58:55 +02002739 "argument must be an int, or have a fileno() method");
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002740 return -1;
2741 }
Andrew M. Kuchling06051ed2000-07-13 23:56:54 +00002742
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002743 if (fd < 0) {
2744 PyErr_Format(PyExc_ValueError,
2745 "file descriptor cannot be a negative integer (%i)",
2746 fd);
2747 return -1;
2748 }
2749 return fd;
Andrew M. Kuchling06051ed2000-07-13 23:56:54 +00002750}
Jack Jansen7b8c7542002-04-14 20:12:41 +00002751
Jack Jansen7b8c7542002-04-14 20:12:41 +00002752/* From here on we need access to the real fgets and fread */
2753#undef fgets
2754#undef fread
2755
2756/*
2757** Py_UniversalNewlineFgets is an fgets variation that understands
2758** all of \r, \n and \r\n conventions.
2759** The stream should be opened in binary mode.
2760** If fobj is NULL the routine always does newline conversion, and
2761** it may peek one char ahead to gobble the second char in \r\n.
2762** If fobj is non-NULL it must be a PyFileObject. In this case there
2763** is no readahead but in stead a flag is used to skip a following
2764** \n on the next read. Also, if the file is open in binary mode
2765** the whole conversion is skipped. Finally, the routine keeps track of
2766** the different types of newlines seen.
2767** Note that we need no error handling: fgets() treats error and eof
2768** identically.
2769*/
2770char *
2771Py_UniversalNewlineFgets(char *buf, int n, FILE *stream, PyObject *fobj)
2772{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002773 char *p = buf;
2774 int c;
2775 int newlinetypes = 0;
2776 int skipnextlf = 0;
2777 int univ_newline = 1;
Tim Peters058b1412002-04-21 07:29:14 +00002778
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002779 if (fobj) {
2780 if (!PyFile_Check(fobj)) {
2781 errno = ENXIO; /* What can you do... */
2782 return NULL;
2783 }
2784 univ_newline = ((PyFileObject *)fobj)->f_univ_newline;
2785 if ( !univ_newline )
2786 return fgets(buf, n, stream);
2787 newlinetypes = ((PyFileObject *)fobj)->f_newlinetypes;
2788 skipnextlf = ((PyFileObject *)fobj)->f_skipnextlf;
2789 }
2790 FLOCKFILE(stream);
2791 c = 'x'; /* Shut up gcc warning */
2792 while (--n > 0 && (c = GETC(stream)) != EOF ) {
2793 if (skipnextlf ) {
2794 skipnextlf = 0;
2795 if (c == '\n') {
2796 /* Seeing a \n here with skipnextlf true
2797 ** means we saw a \r before.
2798 */
2799 newlinetypes |= NEWLINE_CRLF;
2800 c = GETC(stream);
2801 if (c == EOF) break;
2802 } else {
2803 /*
2804 ** Note that c == EOF also brings us here,
2805 ** so we're okay if the last char in the file
2806 ** is a CR.
2807 */
2808 newlinetypes |= NEWLINE_CR;
2809 }
2810 }
2811 if (c == '\r') {
2812 /* A \r is translated into a \n, and we skip
2813 ** an adjacent \n, if any. We don't set the
2814 ** newlinetypes flag until we've seen the next char.
2815 */
2816 skipnextlf = 1;
2817 c = '\n';
2818 } else if ( c == '\n') {
2819 newlinetypes |= NEWLINE_LF;
2820 }
2821 *p++ = c;
2822 if (c == '\n') break;
2823 }
2824 if ( c == EOF && skipnextlf )
2825 newlinetypes |= NEWLINE_CR;
2826 FUNLOCKFILE(stream);
2827 *p = '\0';
2828 if (fobj) {
2829 ((PyFileObject *)fobj)->f_newlinetypes = newlinetypes;
2830 ((PyFileObject *)fobj)->f_skipnextlf = skipnextlf;
2831 } else if ( skipnextlf ) {
2832 /* If we have no file object we cannot save the
2833 ** skipnextlf flag. We have to readahead, which
2834 ** will cause a pause if we're reading from an
2835 ** interactive stream, but that is very unlikely
2836 ** unless we're doing something silly like
2837 ** execfile("/dev/tty").
2838 */
2839 c = GETC(stream);
2840 if ( c != '\n' )
2841 ungetc(c, stream);
2842 }
2843 if (p == buf)
2844 return NULL;
2845 return buf;
Jack Jansen7b8c7542002-04-14 20:12:41 +00002846}
2847
2848/*
2849** Py_UniversalNewlineFread is an fread variation that understands
2850** all of \r, \n and \r\n conventions.
2851** The stream should be opened in binary mode.
2852** fobj must be a PyFileObject. In this case there
2853** is no readahead but in stead a flag is used to skip a following
2854** \n on the next read. Also, if the file is open in binary mode
2855** the whole conversion is skipped. Finally, the routine keeps track of
2856** the different types of newlines seen.
2857*/
2858size_t
Tim Peters058b1412002-04-21 07:29:14 +00002859Py_UniversalNewlineFread(char *buf, size_t n,
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002860 FILE *stream, PyObject *fobj)
Jack Jansen7b8c7542002-04-14 20:12:41 +00002861{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002862 char *dst = buf;
2863 PyFileObject *f = (PyFileObject *)fobj;
2864 int newlinetypes, skipnextlf;
Tim Peters058b1412002-04-21 07:29:14 +00002865
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002866 assert(buf != NULL);
2867 assert(stream != NULL);
Tim Peters058b1412002-04-21 07:29:14 +00002868
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002869 if (!fobj || !PyFile_Check(fobj)) {
2870 errno = ENXIO; /* What can you do... */
2871 return 0;
2872 }
2873 if (!f->f_univ_newline)
2874 return fread(buf, 1, n, stream);
2875 newlinetypes = f->f_newlinetypes;
2876 skipnextlf = f->f_skipnextlf;
2877 /* Invariant: n is the number of bytes remaining to be filled
2878 * in the buffer.
2879 */
2880 while (n) {
2881 size_t nread;
2882 int shortread;
2883 char *src = dst;
Tim Peters058b1412002-04-21 07:29:14 +00002884
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002885 nread = fread(dst, 1, n, stream);
2886 assert(nread <= n);
2887 if (nread == 0)
2888 break;
Neal Norwitzcb3319f2003-02-09 01:10:02 +00002889
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002890 n -= nread; /* assuming 1 byte out for each in; will adjust */
2891 shortread = n != 0; /* true iff EOF or error */
2892 while (nread--) {
2893 char c = *src++;
2894 if (c == '\r') {
2895 /* Save as LF and set flag to skip next LF. */
2896 *dst++ = '\n';
2897 skipnextlf = 1;
2898 }
2899 else if (skipnextlf && c == '\n') {
2900 /* Skip LF, and remember we saw CR LF. */
2901 skipnextlf = 0;
2902 newlinetypes |= NEWLINE_CRLF;
2903 ++n;
2904 }
2905 else {
2906 /* Normal char to be stored in buffer. Also
2907 * update the newlinetypes flag if either this
2908 * is an LF or the previous char was a CR.
2909 */
2910 if (c == '\n')
2911 newlinetypes |= NEWLINE_LF;
2912 else if (skipnextlf)
2913 newlinetypes |= NEWLINE_CR;
2914 *dst++ = c;
2915 skipnextlf = 0;
2916 }
2917 }
2918 if (shortread) {
2919 /* If this is EOF, update type flags. */
2920 if (skipnextlf && feof(stream))
2921 newlinetypes |= NEWLINE_CR;
2922 break;
2923 }
2924 }
2925 f->f_newlinetypes = newlinetypes;
2926 f->f_skipnextlf = skipnextlf;
2927 return dst - buf;
Jack Jansen7b8c7542002-04-14 20:12:41 +00002928}
Anthony Baxterac6bd462006-04-13 02:06:09 +00002929
2930#ifdef __cplusplus
2931}
2932#endif