Skip to content

Commit cab079e

Browse files
committed
Extract behavior in own function.
1 parent 896abd1 commit cab079e

File tree

1 file changed

+23
-14
lines changed

1 file changed

+23
-14
lines changed

Python/traceback.c

Lines changed: 23 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -1104,14 +1104,34 @@ _Py_DumpTracebackThreads(int fd, PyInterpreterState *interp,
11041104
return NULL;
11051105
}
11061106

1107+
#define TRACEBACK_ENTRY_MAX_SIZE 256
1108+
1109+
static void
1110+
format_entry(char *entry_str, const char *the_entry, Py_ssize_t *length_ptr)
1111+
{
1112+
int length = PyOS_snprintf(entry_str, TRACEBACK_ENTRY_MAX_SIZE, " %s\n", the_entry);
1113+
if (length == TRACEBACK_ENTRY_MAX_SIZE) {
1114+
/* We exceeded the size, make it look prettier */
1115+
// Add ellipsis to last 3 characters
1116+
entry_str[TRACEBACK_ENTRY_MAX_SIZE - 5] = '.';
1117+
entry_str[TRACEBACK_ENTRY_MAX_SIZE - 4] = '.';
1118+
entry_str[TRACEBACK_ENTRY_MAX_SIZE - 3] = '.';
1119+
// Ensure trailing newline
1120+
entry_str[TRACEBACK_ENTRY_MAX_SIZE - 2] = '\n';
1121+
// Ensure that it's null-terminated
1122+
entry_str[TRACEBACK_ENTRY_MAX_SIZE - 1] = '\0';
1123+
}
1124+
1125+
*length_ptr = (Py_ssize_t)length;
1126+
}
1127+
11071128
/* This is for faulthandler.
11081129
* Apparently, backtrace() doesn't play well across DLL boundaries on macOS */
11091130
#if defined(HAVE_EXECINFO_H) && defined(HAVE_BACKTRACE) && defined(HAVE_BACKTRACE_SYMBOLS)
11101131
void
11111132
_Py_DumpStack(int fd)
11121133
{
11131134
#define BACKTRACE_SIZE 32
1114-
#define TRACEBACK_ENTRY_MAX_SIZE 256
11151135
PUTS(fd, "Current thread's C stack trace (most recent call first):\n");
11161136
void *callstack[BACKTRACE_SIZE];
11171137
int frames = backtrace(callstack, BACKTRACE_SIZE);
@@ -1128,19 +1148,8 @@ _Py_DumpStack(int fd)
11281148
}
11291149
for (int i = 0; i < frames; ++i) {
11301150
char entry_str[TRACEBACK_ENTRY_MAX_SIZE];
1131-
snprintf(entry_str, TRACEBACK_ENTRY_MAX_SIZE, " %s\n", strings[i]);
1132-
size_t length = strlen(entry_str) + 1;
1133-
if (length == TRACEBACK_ENTRY_MAX_SIZE) {
1134-
/* We exceeded the size, make it look prettier */
1135-
// Add ellipsis to last 3 characters
1136-
entry_str[TRACEBACK_ENTRY_MAX_SIZE - 5] = '.';
1137-
entry_str[TRACEBACK_ENTRY_MAX_SIZE - 4] = '.';
1138-
entry_str[TRACEBACK_ENTRY_MAX_SIZE - 3] = '.';
1139-
// Ensure trailing newline
1140-
entry_str[TRACEBACK_ENTRY_MAX_SIZE - 2] = '\n';
1141-
// Ensure that it's null-terminated
1142-
entry_str[TRACEBACK_ENTRY_MAX_SIZE - 1] = '\0';
1143-
}
1151+
Py_ssize_t length;
1152+
format_entry(entry_str, strings[i], &length);
11441153
_Py_write_noraise(fd, entry_str, length);
11451154
}
11461155

0 commit comments

Comments
 (0)