From 594e2edfb5e0d24e03469d035d8f39ff29a64d99 Mon Sep 17 00:00:00 2001 From: Antonio Gutierrez Date: Wed, 9 Oct 2019 04:19:48 +0200 Subject: [PATCH] closes bpo-36161: Use thread-safe ttyname_r instead of ttyname. (GH-14868) Signed-off-by: Antonio Gutierrez --- .../2019-07-20-01-17-43.bpo-36161.Fzf-f9.rst | 1 + Modules/posixmodule.c | 19 +++++++++++++++---- 2 files changed, 16 insertions(+), 4 deletions(-) create mode 100644 Misc/NEWS.d/next/Library/2019-07-20-01-17-43.bpo-36161.Fzf-f9.rst diff --git a/Misc/NEWS.d/next/Library/2019-07-20-01-17-43.bpo-36161.Fzf-f9.rst b/Misc/NEWS.d/next/Library/2019-07-20-01-17-43.bpo-36161.Fzf-f9.rst new file mode 100644 index 00000000000..b31496c7017 --- /dev/null +++ b/Misc/NEWS.d/next/Library/2019-07-20-01-17-43.bpo-36161.Fzf-f9.rst @@ -0,0 +1 @@ +In :mod:`posix`, use ``ttyname_r`` instead of ``ttyname`` for thread safety. diff --git a/Modules/posixmodule.c b/Modules/posixmodule.c index 5664027b2d3..aeb0e9ddb19 100644 --- a/Modules/posixmodule.c +++ b/Modules/posixmodule.c @@ -2774,13 +2774,24 @@ static PyObject * os_ttyname_impl(PyObject *module, int fd) /*[clinic end generated code: output=c424d2e9d1cd636a input=9ff5a58b08115c55]*/ { - char *ret; - ret = ttyname(fd); - if (ret == NULL) { + long size = sysconf(_SC_TTY_NAME_MAX); + if (size == -1) { return posix_error(); } - return PyUnicode_DecodeFSDefault(ret); + char *buffer = (char *)PyMem_RawMalloc(size); + if (buffer == NULL) { + return PyErr_NoMemory(); + } + int ret = ttyname_r(fd, buffer, size); + if (ret != 0) { + PyMem_RawFree(buffer); + errno = ret; + return posix_error(); + } + PyObject *res = PyUnicode_DecodeFSDefault(buffer); + PyMem_RawFree(buffer); + return res; } #endif