Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 28 additions & 0 deletions Lib/test/test_io.py
Original file line number Diff line number Diff line change
Expand Up @@ -1062,6 +1062,34 @@ def flush(self):
# Silence destructor error
R.flush = lambda self: None

@threading_helper.requires_working_threading()
def test_write_readline_races(self):
N=2
COUNT=100

def writer(file, barrier):
barrier.wait()
for _ in range(COUNT):
f.write("x")

def reader(file, stopping):
while not stopping.is_set():
for line in file:
assert line == ""

stopping = threading.Event()
with self.open(os_helper.TESTFN, "w+") as f:
barrier = threading.Barrier(N)
reader = threading.Thread(target=reader, args=(f, stopping))
writers = [threading.Thread(target=writer, args=(f, barrier))
for _ in range(N)]
reader.start()
with threading_helper.start_threads(writers):
pass
stopping.set()
reader.join()
assert(os.stat(os_helper.TESTFN).st_size == COUNT * N)


class CIOTest(IOTest):

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Protect ``textiowrapper_iternext`` with a critical section.
14 changes: 13 additions & 1 deletion Modules/_io/textio.c
Original file line number Diff line number Diff line change
Expand Up @@ -1578,6 +1578,8 @@ _io_TextIOWrapper_detach_impl(textio *self)
static int
_textiowrapper_writeflush(textio *self)
{
_Py_CRITICAL_SECTION_ASSERT_OBJECT_LOCKED(self);

if (self->pending_bytes == NULL)
return 0;

Expand Down Expand Up @@ -3173,7 +3175,7 @@ _io_TextIOWrapper_close_impl(textio *self)
}

static PyObject *
textiowrapper_iternext(PyObject *op)
textiowrapper_iternext_locked(PyObject *op)
{
PyObject *line;
textio *self = textio_CAST(op);
Expand Down Expand Up @@ -3210,6 +3212,16 @@ textiowrapper_iternext(PyObject *op)
return line;
}

static PyObject *
textiowrapper_iternext(PyObject *op)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could you add a comment regarding fuzzing here?

{
PyObject *result;
Py_BEGIN_CRITICAL_SECTION(op);
result = textiowrapper_iternext_locked(op);
Py_END_CRITICAL_SECTION();
return result;
}

/*[clinic input]
@critical_section
@getter
Expand Down
Loading