Skip to content

Commit

Permalink
Extract behavior in own function.
Browse files Browse the repository at this point in the history
  • Loading branch information
ZeroIntensity committed Jan 27, 2025
1 parent 896abd1 commit cab079e
Showing 1 changed file with 23 additions and 14 deletions.
37 changes: 23 additions & 14 deletions Python/traceback.c
Original file line number Diff line number Diff line change
Expand Up @@ -1104,14 +1104,34 @@ _Py_DumpTracebackThreads(int fd, PyInterpreterState *interp,
return NULL;
}

#define TRACEBACK_ENTRY_MAX_SIZE 256

static void
format_entry(char *entry_str, const char *the_entry, Py_ssize_t *length_ptr)
{
int length = PyOS_snprintf(entry_str, TRACEBACK_ENTRY_MAX_SIZE, " %s\n", the_entry);
if (length == TRACEBACK_ENTRY_MAX_SIZE) {
/* We exceeded the size, make it look prettier */
// Add ellipsis to last 3 characters
entry_str[TRACEBACK_ENTRY_MAX_SIZE - 5] = '.';
entry_str[TRACEBACK_ENTRY_MAX_SIZE - 4] = '.';
entry_str[TRACEBACK_ENTRY_MAX_SIZE - 3] = '.';
// Ensure trailing newline
entry_str[TRACEBACK_ENTRY_MAX_SIZE - 2] = '\n';
// Ensure that it's null-terminated
entry_str[TRACEBACK_ENTRY_MAX_SIZE - 1] = '\0';
}

*length_ptr = (Py_ssize_t)length;
}

/* This is for faulthandler.
* Apparently, backtrace() doesn't play well across DLL boundaries on macOS */
#if defined(HAVE_EXECINFO_H) && defined(HAVE_BACKTRACE) && defined(HAVE_BACKTRACE_SYMBOLS)
void
_Py_DumpStack(int fd)
{
#define BACKTRACE_SIZE 32
#define TRACEBACK_ENTRY_MAX_SIZE 256
PUTS(fd, "Current thread's C stack trace (most recent call first):\n");
void *callstack[BACKTRACE_SIZE];
int frames = backtrace(callstack, BACKTRACE_SIZE);
Expand All @@ -1128,19 +1148,8 @@ _Py_DumpStack(int fd)
}
for (int i = 0; i < frames; ++i) {
char entry_str[TRACEBACK_ENTRY_MAX_SIZE];
snprintf(entry_str, TRACEBACK_ENTRY_MAX_SIZE, " %s\n", strings[i]);
size_t length = strlen(entry_str) + 1;
if (length == TRACEBACK_ENTRY_MAX_SIZE) {
/* We exceeded the size, make it look prettier */
// Add ellipsis to last 3 characters
entry_str[TRACEBACK_ENTRY_MAX_SIZE - 5] = '.';
entry_str[TRACEBACK_ENTRY_MAX_SIZE - 4] = '.';
entry_str[TRACEBACK_ENTRY_MAX_SIZE - 3] = '.';
// Ensure trailing newline
entry_str[TRACEBACK_ENTRY_MAX_SIZE - 2] = '\n';
// Ensure that it's null-terminated
entry_str[TRACEBACK_ENTRY_MAX_SIZE - 1] = '\0';
}
Py_ssize_t length;
format_entry(entry_str, strings[i], &length);
_Py_write_noraise(fd, entry_str, length);
}

Expand Down

0 comments on commit cab079e

Please sign in to comment.