Skip to content

Commit ac89f8c

Browse files
bpo-45831: _Py_DumpASCII() uses a single write() call if possible (GH-29596) (GH-29597)
If the string is ASCII only and doesn't need to escape characters, write the whole string with a single write() syscall. (cherry picked from commit b919d81) Co-authored-by: Victor Stinner <vstinner@python.org>
1 parent fd206b6 commit ac89f8c

2 files changed

Lines changed: 27 additions & 0 deletions

File tree

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
:mod:`faulthandler` can now write ASCII-only strings (like filenames and
2+
function names) with a single write() syscall when dumping a traceback. It
3+
reduces the risk of getting an unreadable dump when two threads or two
4+
processes dump a traceback to the same file (like stderr) at the same time.
5+
Patch by Victor Stinner.

‎Python/traceback.c‎

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -719,6 +719,26 @@ _Py_DumpASCII(int fd, PyObject *text)
719719
truncated = 0;
720720
}
721721

722+
// Is an ASCII string?
723+
if (ascii->state.ascii) {
724+
assert(kind == PyUnicode_1BYTE_KIND);
725+
char *str = data;
726+
727+
int need_escape = 0;
728+
for (i=0; i < size; i++) {
729+
ch = str[i];
730+
if (!(' ' <= ch && ch <= 126)) {
731+
need_escape = 1;
732+
break;
733+
}
734+
}
735+
if (!need_escape) {
736+
// The string can be written with a single write() syscall
737+
_Py_write_noraise(fd, str, size);
738+
goto done;
739+
}
740+
}
741+
722742
for (i=0; i < size; i++) {
723743
if (kind != PyUnicode_WCHAR_KIND)
724744
ch = PyUnicode_READ(kind, data, i);
@@ -742,6 +762,8 @@ _Py_DumpASCII(int fd, PyObject *text)
742762
_Py_DumpHexadecimal(fd, ch, 8);
743763
}
744764
}
765+
766+
done:
745767
if (truncated) {
746768
PUTS(fd, "...");
747769
}

0 commit comments

Comments
 (0)