diff --git a/Include/internal/pycore_fileutils.h b/Include/internal/pycore_fileutils.h index 2c6d6daa01994e..2cf8860db591a9 100644 --- a/Include/internal/pycore_fileutils.h +++ b/Include/internal/pycore_fileutils.h @@ -132,6 +132,8 @@ PyAPI_FUNC(Py_ssize_t) _Py_write_noraise( const void *buf, size_t count); +extern int _Py_fdprintf(int fd, const char *fmt, ...); + #ifdef HAVE_READLINK extern int _Py_wreadlink( const wchar_t *path, diff --git a/Python/fileutils.c b/Python/fileutils.c index 78603d40704f14..b6ffbb313e6fef 100644 --- a/Python/fileutils.c +++ b/Python/fileutils.c @@ -14,6 +14,8 @@ # include # include // FILE_DEVICE_* constants # include "pycore_fileutils_windows.h" // FILE_STAT_BASIC_INFORMATION +# define fdopen _fdopen +# define dup _dup # if defined(MS_WINDOWS_GAMES) && !defined(MS_WINDOWS_DESKTOP) # define PATHCCH_ALLOW_LONG_PATHS 0x01 # else @@ -2059,6 +2061,30 @@ _Py_write_noraise(int fd, const void *buf, size_t count) return _Py_write_impl(fd, buf, count, 0); } +int +_Py_fdprintf(int fd, const char *fmt, ...) +{ + int newfd = dup(fd); + if (newfd < 0) { + return -1; + } + FILE *handle = fdopen(newfd, "a"); + if (handle == NULL) { + close(newfd); + return -1; + } + va_list vargs; + va_start(vargs, fmt); + int res = vfprintf(handle, fmt, vargs); + va_end(vargs); + fclose(handle); + if (res != 0) { + return -1; + } + + return 0; +} + #ifdef HAVE_READLINK /* Read value of symbolic link. Encode the path to the locale encoding, decode diff --git a/Python/traceback.c b/Python/traceback.c index 7319382f053eae..5d053283ff51eb 100644 --- a/Python/traceback.c +++ b/Python/traceback.c @@ -1210,7 +1210,7 @@ _Py_backtrace_symbols_fd(int fd, void *const *array, Py_ssize_t size) || info[i].dli_fname == NULL || info[i].dli_fname[0] == '\0' ) { - dprintf(fd, " Binary file '' [%p]\n", array[i]); + _Py_fdprintf(fd, " Binary file '' [%p]\n", array[i]); continue; } @@ -1222,9 +1222,9 @@ _Py_backtrace_symbols_fd(int fd, void *const *array, Py_ssize_t size) if (info[i].dli_sname == NULL && info[i].dli_saddr == 0) { - dprintf(fd, " Binary file \"%s\" [%p]\n", - info[i].dli_fname, - array[i]); + _Py_fdprintf(fd, " Binary file \"%s\" [%p]\n", + info[i].dli_fname, + array[i]); } else { char sign; @@ -1238,10 +1238,10 @@ _Py_backtrace_symbols_fd(int fd, void *const *array, Py_ssize_t size) offset = info[i].dli_saddr - array[i]; } const char *symbol_name = info[i].dli_sname != NULL ? info[i].dli_sname : ""; - dprintf(fd, " Binary file \"%s\", at %s%c%#tx [%p]\n", - info[i].dli_fname, - symbol_name, - sign, offset, array[i]); + _Py_fdprintf(fd, " Binary file \"%s\", at %s%c%#tx [%p]\n", + info[i].dli_fname, + symbol_name, + sign, offset, array[i]); } } }