Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
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
Original file line number Diff line number Diff line change
Expand Up @@ -844,6 +844,42 @@ def test_invalid_path_error_preserves_pathlib(self):
_remote_debugging.BinaryReader(missing)
self.assertEqual(os.fspath(cm.exception.filename), os.fspath(missing))

def test_writer_rejects_malformed_samples(self):
"""Malformed sample containers raise TypeError instead of crashing."""
cases = (
("stack_frames", 42),
("interp_info", [42]),
("interp_info", [()]),
("interp_info", [(0,)]),
("threads", [(0, 42)]),
("thread_info", [(0, [42])]),
("thread_info", [(0, [()])]),
("thread_info", [(0, [(1,)])]),
("thread_info", [(0, [(1, 0)])]),
("frame_list", [(0, [(1, 0, 42)])]),
("frame_info", [(0, [(1, 0, [42])])]),
("frame_info", [(0, [(1, 0, [()])])]),
("frame_info", [(0, [(1, 0, [("a.py",)])])]),
("frame_info", [(0, [(1, 0, [("a.py", None)])])]),
("frame_info", [(0, [(1, 0, [("a.py", None, "f")])])]),
("location", [(0, [(1, 0, [("a.py", 42, "f", None)])])]),
("location", [(0, [(1, 0, [("a.py", (), "f", None)])])]),
("location", [(0, [(1, 0, [("a.py", (1,), "f", None)])])]),
("location", [(0, [(1, 0, [("a.py", (1, 1), "f", None)])])]),
("location", [(0, [(1, 0, [("a.py", (1, 1, 0), "f", None)])])]),
)
with tempfile.NamedTemporaryFile(suffix=".bin", delete=False) as f:
filename = f.name
self.temp_files.append(filename)

for field, sample in cases:
with self.subTest(field=field, sample=sample):
with _remote_debugging.BinaryWriter(
filename, 1000, 0, compression=0
) as writer:
with self.assertRaisesRegex(TypeError, field):
writer.write_sample(sample, 2000)

def test_writer_handles_empty_stack_first_sample(self):
"""BinaryWriter.write_sample tolerates an empty stack on a fresh thread.

Expand Down
44 changes: 27 additions & 17 deletions Modules/_remote_debugging/binary_io_writer.c
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,22 @@
} \
} while (0)

#define CHECK_TUPLE_ITEMS(obj, n) do { \

@maurycy maurycy Sep 9, 2026

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Truth be told, we reinvent similar check over and over:

#define CHECK_LIST_OR_TUPLE(v) \
if (!PyList_Check(v) && !PyTuple_Check(v)) { \
PyErr_SetString(PyExc_TypeError, \
#v " must be a list or a tuple"); \
return NULL; \
}

#define CHECK_LIST_OR_TUPLE(v) \
do { \
if (!PyList_Check(v) && !PyTuple_Check(v)) { \
PyErr_SetString(PyExc_TypeError, \
#v " must be a list or a tuple"); \
return NULL; \
} \
} while (0)

Sometimes without a macro:

/* We allow the state tuple to be longer than 4, because we may need
someday to extend the object's state without breaking
backward-compatibility. */
if (!PyTuple_Check(state) || PyTuple_GET_SIZE(state) < 4) {
PyErr_Format(PyExc_TypeError,
"%.200s.__setstate__ argument should be 4-tuple, got %.200s",
Py_TYPE(self)->tp_name, Py_TYPE(state)->tp_name);
return NULL;
}

cpython/Python/_warnings.c

Lines 450 to 465 in 9a75080

tmp_item = PyList_GET_ITEM(filters, i);
if (!PyTuple_Check(tmp_item) || PyTuple_GET_SIZE(tmp_item) != 5) {
PyErr_Format(PyExc_ValueError,
"warnings.%s item %zd isn't a 5-tuple", list_name, i);
result = false;
break;
}
/* Python code: action, msg, cat, mod, ln = item */
Py_INCREF(tmp_item);
action = PyTuple_GET_ITEM(tmp_item, 0);
msg = PyTuple_GET_ITEM(tmp_item, 1);
cat = PyTuple_GET_ITEM(tmp_item, 2);
mod = PyTuple_GET_ITEM(tmp_item, 3);
ln_obj = PyTuple_GET_ITEM(tmp_item, 4);

if (!PyTuple_Check(obj) || PyTuple_GET_SIZE(obj) < (n)) { \
PyErr_Format(PyExc_TypeError, \
#obj " must be a tuple of at least %zd items", \
(Py_ssize_t)(n)); \
return -1; \
} \
} while (0)

#define CHECK_LIST(obj) do { \
if (!PyList_Check(obj)) { \
PyErr_SetString(PyExc_TypeError, #obj " must be a list"); \
return -1; \
} \
} while (0)

/* ============================================================================
* WRITER-SPECIFIC UTILITY HELPERS
* ============================================================================ */
Expand Down Expand Up @@ -838,8 +854,8 @@ build_frame_stack(BinaryWriter *writer, PyObject *frame_list,
*curr_depth = (stack_depth < MAX_STACK_DEPTH) ? stack_depth : MAX_STACK_DEPTH;

for (Py_ssize_t k = 0; k < (Py_ssize_t)*curr_depth; k++) {
/* Use unchecked accessors since we control the data structures */
PyObject *frame_info = PyList_GET_ITEM(frame_list, k);
CHECK_TUPLE_ITEMS(frame_info, 4);

/* Get filename, location, funcname, opcode from FrameInfo using unchecked access */
PyObject *filename = PyStructSequence_GET_ITEM(frame_info, 0);
Expand All @@ -854,20 +870,13 @@ build_frame_stack(BinaryWriter *writer, PyObject *frame_list,
int32_t end_column = LOCATION_NOT_AVAILABLE;

if (location != Py_None) {
CHECK_TUPLE_ITEMS(location, 4);

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

normalize_location() in Lib/profiling/sampling/collector.py accepts an int location (a bare lineno) and binary_collector.py hands stack_frames straight to write_sample, so this now raises where the other collectors work. Do we want a PyLong_Check(location) case here too, or is that branch in normalize_location() dead and we should drop it instead?

/* LocationInfo is a struct sequence or tuple with:
* (lineno, end_lineno, column, end_column) */
PyObject *lineno_obj = PyTuple_Check(location) ?
PyTuple_GET_ITEM(location, 0) :
PyStructSequence_GET_ITEM(location, 0);
PyObject *end_lineno_obj = PyTuple_Check(location) ?
PyTuple_GET_ITEM(location, 1) :
PyStructSequence_GET_ITEM(location, 1);
PyObject *column_obj = PyTuple_Check(location) ?
PyTuple_GET_ITEM(location, 2) :
PyStructSequence_GET_ITEM(location, 2);
PyObject *end_column_obj = PyTuple_Check(location) ?
PyTuple_GET_ITEM(location, 3) :
PyStructSequence_GET_ITEM(location, 3);
PyObject *lineno_obj = PyTuple_GET_ITEM(location, 0);
PyObject *end_lineno_obj = PyTuple_GET_ITEM(location, 1);
PyObject *column_obj = PyTuple_GET_ITEM(location, 2);
PyObject *end_column_obj = PyTuple_GET_ITEM(location, 3);

PYLONG_TO_INT32_OR_DEFAULT(lineno_obj, lineno, LOCATION_NOT_AVAILABLE);
PYLONG_TO_INT32_OR_DEFAULT(end_lineno_obj, end_lineno, LOCATION_NOT_AVAILABLE);
Expand Down Expand Up @@ -925,9 +934,11 @@ static int
process_thread_sample(BinaryWriter *writer, PyObject *thread_info,
uint32_t interpreter_id, uint64_t timestamp_us)
{
CHECK_TUPLE_ITEMS(thread_info, 3);
PyObject *thread_id_obj = PyStructSequence_GET_ITEM(thread_info, 0);
PyObject *status_obj = PyStructSequence_GET_ITEM(thread_info, 1);
PyObject *frame_list = PyStructSequence_GET_ITEM(thread_info, 2);
CHECK_LIST(frame_list);

uint64_t thread_id = PyLong_AsUnsignedLongLong(thread_id_obj);
if (thread_id == (uint64_t)-1 && PyErr_Occurred()) {
Expand Down Expand Up @@ -1010,17 +1021,16 @@ process_thread_sample(BinaryWriter *writer, PyObject *thread_info,
int
binary_writer_write_sample(BinaryWriter *writer, PyObject *stack_frames, uint64_t timestamp_us)
{
if (!PyList_Check(stack_frames)) {
PyErr_SetString(PyExc_TypeError, "stack_frames must be a list");
return -1;
}
CHECK_LIST(stack_frames);

Py_ssize_t num_interpreters = PyList_GET_SIZE(stack_frames);
for (Py_ssize_t i = 0; i < num_interpreters; i++) {
PyObject *interp_info = PyList_GET_ITEM(stack_frames, i);
CHECK_TUPLE_ITEMS(interp_info, 2);

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

We validate as we go, so a bad thread in the middle leaves the earlier threads already written and total_samples bumped even though write_sample raised. Should we walk and validate the whole structure first so this is all-or-nothing? Otherwise the caller has no way to recover from the TypeError.


PyObject *interp_id_obj = PyStructSequence_GET_ITEM(interp_info, 0);
PyObject *threads = PyStructSequence_GET_ITEM(interp_info, 1);
CHECK_LIST(threads);

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

This narrows the hole but does not close it. PyLong_AsLong(status_obj) goes through _PyNumber_Index, so an __index__ that mutates the same list re-enters us while we still hold a cached size and a borrowed thread_info:

threads = []
class Evil:
    def __index__(self):
        del threads[:]
        return 0
threads.extend([(1, Evil(), []), (2, 0, [])])
_remote_debugging.BinaryWriter("/tmp/o.bin", 1000, 0, compression=0).write_sample([(0, threads)], 2000)

This still segfaults on PyList_GET_ITEM(threads, 1) because del threads[:] frees ob_item. writer_intern_string has the same problem via PyObject_Hash. If we want to claim write_sample is safe against arbitrary input we need strong references to the containers (or to re-read the sizes), not only a type check up front. Happy to take this as a follow-up, but then let's not close the issue with this PR.


unsigned long interp_id_long = PyLong_AsUnsignedLong(interp_id_obj);
if (interp_id_long == (unsigned long)-1 && PyErr_Occurred()) {
Expand Down
Loading