Skip to content

Commit 2bbbab2

Browse files
gh-110365: Fix error overwrite in termios.tcsetattr (#110366)
Co-authored-by: Erlend E. Aasland <[email protected]>
1 parent 6592976 commit 2bbbab2

File tree

2 files changed

+28
-13
lines changed

2 files changed

+28
-13
lines changed
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
Fix :func:`termios.tcsetattr` bug that was overwritting existing errors
2+
during parsing integers from ``term`` list.

Modules/termios.c

Lines changed: 26 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -212,17 +212,25 @@ termios_tcsetattr_impl(PyObject *module, int fd, int when, PyObject *term)
212212
return PyErr_SetFromErrno(state->TermiosError);
213213
}
214214

215-
mode.c_iflag = (tcflag_t) PyLong_AsLong(PyList_GetItem(term, 0));
216-
mode.c_oflag = (tcflag_t) PyLong_AsLong(PyList_GetItem(term, 1));
217-
mode.c_cflag = (tcflag_t) PyLong_AsLong(PyList_GetItem(term, 2));
218-
mode.c_lflag = (tcflag_t) PyLong_AsLong(PyList_GetItem(term, 3));
219-
speed_t ispeed = (speed_t) PyLong_AsLong(PyList_GetItem(term, 4));
220-
speed_t ospeed = (speed_t) PyLong_AsLong(PyList_GetItem(term, 5));
221-
PyObject *cc = PyList_GetItem(term, 6);
222-
if (PyErr_Occurred()) {
223-
return NULL;
224-
}
225-
215+
speed_t ispeed, ospeed;
216+
#define SET_FROM_LIST(TYPE, VAR, LIST, N) do { \
217+
PyObject *item = PyList_GET_ITEM(LIST, N); \
218+
long num = PyLong_AsLong(item); \
219+
if (num == -1 && PyErr_Occurred()) { \
220+
return NULL; \
221+
} \
222+
VAR = (TYPE)num; \
223+
} while (0)
224+
225+
SET_FROM_LIST(tcflag_t, mode.c_iflag, term, 0);
226+
SET_FROM_LIST(tcflag_t, mode.c_oflag, term, 1);
227+
SET_FROM_LIST(tcflag_t, mode.c_cflag, term, 2);
228+
SET_FROM_LIST(tcflag_t, mode.c_lflag, term, 3);
229+
SET_FROM_LIST(speed_t, ispeed, term, 4);
230+
SET_FROM_LIST(speed_t, ospeed, term, 5);
231+
#undef SET_FROM_LIST
232+
233+
PyObject *cc = PyList_GET_ITEM(term, 6);
226234
if (!PyList_Check(cc) || PyList_Size(cc) != NCCS) {
227235
PyErr_Format(PyExc_TypeError,
228236
"tcsetattr: attributes[6] must be %d element list",
@@ -237,8 +245,13 @@ termios_tcsetattr_impl(PyObject *module, int fd, int when, PyObject *term)
237245

238246
if (PyBytes_Check(v) && PyBytes_Size(v) == 1)
239247
mode.c_cc[i] = (cc_t) * PyBytes_AsString(v);
240-
else if (PyLong_Check(v))
241-
mode.c_cc[i] = (cc_t) PyLong_AsLong(v);
248+
else if (PyLong_Check(v)) {
249+
long num = PyLong_AsLong(v);
250+
if (num == -1 && PyErr_Occurred()) {
251+
return NULL;
252+
}
253+
mode.c_cc[i] = (cc_t)num;
254+
}
242255
else {
243256
PyErr_SetString(PyExc_TypeError,
244257
"tcsetattr: elements of attributes must be characters or integers");

0 commit comments

Comments
 (0)