Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 1e3bdf6

Browse files
committed
Patch #788249: Pass an explicit buffer to setvbuf in PyFile_SetBufSize().
Fixes #603724. Will backport to 2.3.
1 parent fa3bdea commit 1e3bdf6

2 files changed

Lines changed: 20 additions & 5 deletions

File tree

Include/fileobject.h

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@ typedef struct {
1919
char* f_buf; /* Allocated readahead buffer */
2020
char* f_bufend; /* Points after last occupied position */
2121
char* f_bufptr; /* Current buffer position */
22+
char *f_setbuf; /* Buffer for setbuf(3) and setvbuf(3) */
2223
#ifdef WITH_UNIVERSAL_NEWLINES
2324
int f_univ_newline; /* Handle any newline convention */
2425
int f_newlinetypes; /* Types of newlines seen */

Objects/fileobject.c

Lines changed: 19 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -283,25 +283,37 @@ PyFile_FromString(char *name, char *mode)
283283
void
284284
PyFile_SetBufSize(PyObject *f, int bufsize)
285285
{
286+
PyFileObject *file = (PyFileObject *)f;
286287
if (bufsize >= 0) {
287-
#ifdef HAVE_SETVBUF
288288
int type;
289289
switch (bufsize) {
290290
case 0:
291291
type = _IONBF;
292292
break;
293+
#ifdef HAVE_SETVBUF
293294
case 1:
294295
type = _IOLBF;
295296
bufsize = BUFSIZ;
296297
break;
298+
#endif
297299
default:
298300
type = _IOFBF;
301+
#ifndef HAVE_SETVBUF
302+
bufsize = BUFSIZ;
303+
#endif
304+
break;
305+
}
306+
fflush(file->f_fp);
307+
if (type == _IONBF) {
308+
PyMem_Free(file->f_setbuf);
309+
file->f_setbuf = NULL;
310+
} else {
311+
file->f_setbuf = PyMem_Realloc(file->f_setbuf, bufsize);
299312
}
300-
setvbuf(((PyFileObject *)f)->f_fp, (char *)NULL,
301-
type, bufsize);
313+
#ifdef HAVE_SETVBUF
314+
setvbuf(file->f_fp, file->f_setbuf, type, bufsize);
302315
#else /* !HAVE_SETVBUF */
303-
if (bufsize <= 1)
304-
setbuf(((PyFileObject *)f)->f_fp, (char *)NULL);
316+
setbuf(file->f_fp, file->f_setbuf);
305317
#endif /* !HAVE_SETVBUF */
306318
}
307319
}
@@ -376,6 +388,7 @@ static PyObject *
376388
file_close(PyFileObject *f)
377389
{
378390
int sts = 0;
391+
PyMem_Free(f->f_setbuf);
379392
if (f->f_fp != NULL) {
380393
if (f->f_close != NULL) {
381394
Py_BEGIN_ALLOW_THREADS
@@ -1928,6 +1941,7 @@ file_init(PyObject *self, PyObject *args, PyObject *kwds)
19281941
}
19291942
if (open_the_file(foself, name, mode) == NULL)
19301943
goto Error;
1944+
foself->f_setbuf = NULL;
19311945
PyFile_SetBufSize(self, bufsize);
19321946
goto Done;
19331947

0 commit comments

Comments
 (0)