Skip to content

[Backtracing] Add an indication that we're working on a backtrace. #69775

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 4 commits into from
Nov 13, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
107 changes: 5 additions & 102 deletions include/swift/Runtime/Backtrace.h
Original file line number Diff line number Diff line change
Expand Up @@ -31,114 +31,17 @@

#include <inttypes.h>

#ifdef _WIN32
// For DWORD
#define WIN32_LEAN_AND_MEAN
#define NOMINMAX
#include <windows.h>

// For wchar_t
#include <cwchar>
#endif

#ifdef __cplusplus
namespace swift {
namespace runtime {
namespace backtrace {
#endif

#ifdef _WIN32
typedef wchar_t ArgChar;
typedef DWORD ErrorCode;
#else
typedef char ArgChar;
typedef int ErrorCode;
#endif

SWIFT_RUNTIME_STDLIB_INTERNAL ErrorCode _swift_installCrashHandler();

#ifdef __linux__
SWIFT_RUNTIME_STDLIB_INTERNAL bool _swift_spawnBacktracer(const ArgChar * const *argv, int memserver_fd);
#else
SWIFT_RUNTIME_STDLIB_INTERNAL bool _swift_spawnBacktracer(const ArgChar * const *argv);
#endif

enum class UnwindAlgorithm {
Auto = 0,
Fast = 1,
Precise = 2
};

enum class OnOffTty {
Off = 0,
On = 1,
TTY = 2
};

enum class Preset {
Auto = -1,
Friendly = 0,
Medium = 1,
Full = 2
};

enum class ThreadsToShow {
Preset = -1,
All = 0,
Crashed = 1
};

enum class RegistersToShow {
Preset = -1,
None = 0,
All = 1,
Crashed = 2
};

enum class ImagesToShow {
Preset = -1,
None = 0,
All = 1,
Mentioned = 2
};

enum class SanitizePaths {
Preset = -1,
Off = 0,
On = 1
};

enum class OutputTo {
Auto = -1,
Stdout = 0,
Stderr = 2,
};

struct BacktraceSettings {
UnwindAlgorithm algorithm;
OnOffTty enabled;
bool demangle;
OnOffTty interactive;
OnOffTty color;
unsigned timeout;
ThreadsToShow threads;
RegistersToShow registers;
ImagesToShow images;
unsigned limit;
unsigned top;
SanitizePaths sanitize;
Preset preset;
bool cache;
OutputTo outputTo;
const char *swiftBacktracePath;
};

SWIFT_RUNTIME_STDLIB_INTERNAL BacktraceSettings _swift_backtraceSettings;

inline bool _swift_backtrace_isEnabled() {
return _swift_backtraceSettings.enabled == OnOffTty::On;
}

// Test if a given function is a Swift thunk of some sort.
//
// @param mangledName is the name of the symbol to test.
//
// @returns true if the function is a thunk.
SWIFT_RUNTIME_STDLIB_SPI
bool _swift_backtrace_isThunkFunction(const char *mangledName);

Expand Down
57 changes: 52 additions & 5 deletions stdlib/public/libexec/swift-backtrace/main.swift
Original file line number Diff line number Diff line change
Expand Up @@ -113,6 +113,38 @@ internal struct SwiftBacktrace {
}
}

static func subtract(timespec ts: timespec, from: timespec) -> timespec {
var sec = from.tv_sec - ts.tv_sec
var nsec = from.tv_nsec - ts.tv_nsec
if nsec < 0 {
sec -= 1
nsec += 1000000000
}
return timespec(tv_sec: sec, tv_nsec: nsec)
}

// We can't use Foundation here, so there's no String(format:, ...)
static func format(duration: timespec) -> String {
let centisRounded = (duration.tv_nsec + 5000000) / 10000000
let centis = centisRounded % 100
let secs = duration.tv_sec + (centisRounded / 100)
let d1 = centis / 10
let d2 = centis % 10

return "\(secs).\(d1)\(d2)"
}

static func measureDuration(_ body: () -> ()) -> timespec {
var startTime = timespec()
var endTime = timespec()

clock_gettime(CLOCK_MONOTONIC, &startTime)
body()
clock_gettime(CLOCK_MONOTONIC, &endTime)

return subtract(timespec: startTime, from: endTime)
}

static func usage() {
print("""
usage: swift-backtrace [--unwind <algorithm>] [--demangle [<bool>]] [--interactive [<bool>]] [--color [<bool>]] [--timeout <seconds>] [--preset <preset>] [--threads [<bool>]] [--registers <registers>] [--images <images>] [--cache [<bool>]] [--output-to <stream>] --crashinfo <addr>
Expand Down Expand Up @@ -460,16 +492,25 @@ Generate a backtrace for the parent process.
// want to do it *once* for all the backtraces we showed.
formattingOptions = formattingOptions.showImages(.none)

target = Target(crashInfoAddr: crashInfoAddr,
limit: args.limit, top: args.top,
cache: args.cache)
// Target's initializer fetches and symbolicates backtraces, so
// we want to time that part here.
let duration = measureDuration {
target = Target(crashInfoAddr: crashInfoAddr,
limit: args.limit, top: args.top,
cache: args.cache)

currentThread = target!.crashingThreadNdx
currentThread = target!.crashingThreadNdx
}

printCrashLog()

writeln("")

let formattedDuration = format(duration: duration)

writeln("Backtrace took \(formattedDuration)s")
writeln("")

if args.interactive {
// Make sure we're line buffered
setvbuf(stdout, nil, _IOLBF, 0)
Expand Down Expand Up @@ -611,7 +652,13 @@ Generate a backtrace for the parent process.
description = "Program crashed: \(target.signalDescription) at \(hex(target.faultAddress))"
}

writeln("")
// Clear (or complete) the message written by the crash handler
if args.color {
write("\r\u{1b}[0K")
} else {
write(" done ***\n\n")
}

writeln(theme.crashReason(description))

var mentionedImages = Set<Int>()
Expand Down
104 changes: 81 additions & 23 deletions stdlib/public/runtime/Backtrace.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,8 @@
#include <cxxabi.h>
#endif

#include "BacktracePrivate.h"

#define DEBUG_BACKTRACING_SETTINGS 0

#ifndef lengthof
Expand All @@ -74,13 +76,7 @@ SWIFT_RUNTIME_STDLIB_INTERNAL BacktraceSettings _swift_backtraceSettings = {
UnwindAlgorithm::Auto,

// enabled
#if TARGET_OS_OSX
OnOffTty::TTY,
#elif defined(__linux__) // || defined(_WIN32)
OnOffTty::On,
#else
OnOffTty::Off,
#endif
OnOffTty::Default,

// demangle
true,
Expand Down Expand Up @@ -230,6 +226,7 @@ const char *algorithmToString(UnwindAlgorithm algorithm) {

const char *onOffTtyToString(OnOffTty oot) {
switch (oot) {
case OnOffTty::Default: return "Default";
case OnOffTty::On: return "On";
case OnOffTty::Off: return "Off";
case OnOffTty::TTY: return "TTY";
Expand Down Expand Up @@ -277,6 +274,32 @@ BacktraceInitializer::BacktraceInitializer() {
if (backtracing)
_swift_parseBacktracingSettings(backtracing);

#if !defined(SWIFT_RUNTIME_FIXED_BACKTRACER_PATH)
if (!_swift_backtraceSettings.swiftBacktracePath) {
_swift_backtraceSettings.swiftBacktracePath
= swift_copyAuxiliaryExecutablePath("swift-backtrace");

if (!_swift_backtraceSettings.swiftBacktracePath) {
if (_swift_backtraceSettings.enabled == OnOffTty::On) {
swift::warning(0,
"swift runtime: unable to locate swift-backtrace; "
"disabling backtracing.\n");
}
_swift_backtraceSettings.enabled = OnOffTty::Off;
}
}
#endif

if (_swift_backtraceSettings.enabled == OnOffTty::Default) {
#if TARGET_OS_OSX
_swift_backtraceSettings.enabled = OnOffTty::TTY;
#elif defined(__linux__) // || defined(_WIN32)
_swift_backtraceSettings.enabled = OnOffTty::On;
#else
_swift_backtraceSettings.enabled = OnOffTty::Off;
#endif
}

#if !SWIFT_BACKTRACE_ON_CRASH_SUPPORTED
if (_swift_backtraceSettings.enabled != OnOffTty::Off) {
swift::warning(0,
Expand Down Expand Up @@ -329,22 +352,6 @@ BacktraceInitializer::BacktraceInitializer() {
_swift_backtraceSettings.outputTo = OutputTo::Stderr;
}

#if !defined(SWIFT_RUNTIME_FIXED_BACKTRACER_PATH)
if (_swift_backtraceSettings.enabled == OnOffTty::On
&& !_swift_backtraceSettings.swiftBacktracePath) {
_swift_backtraceSettings.swiftBacktracePath
= swift_copyAuxiliaryExecutablePath("swift-backtrace");

if (!_swift_backtraceSettings.swiftBacktracePath) {
// Disabled warning for now - rdar://106813646
/* swift::warning(0,
"swift runtime: unable to locate swift-backtrace; "
"disabling backtracing.\n"); */
_swift_backtraceSettings.enabled = OnOffTty::Off;
}
}
#endif

if (_swift_backtraceSettings.enabled == OnOffTty::On) {
// Copy the path to swift-backtrace into swiftBacktracePath, then write
// protect it so that it can't be overwritten easily at runtime. We do
Expand Down Expand Up @@ -987,6 +994,57 @@ _swift_spawnBacktracer(const ArgChar * const *argv)
#endif
}

// N.B. THIS FUNCTION MUST BE SAFE TO USE FROM A CRASH HANDLER. On Linux
// and macOS, that means it must be async-signal-safe. On Windows, there
// isn't an equivalent notion but a similar restriction applies.
SWIFT_RUNTIME_STDLIB_INTERNAL void
_swift_displayCrashMessage(int signum, const void *pc)
{
#if !SWIFT_BACKTRACE_ON_CRASH_SUPPORTED
return;
#else
int fd = STDOUT_FILENO;

if (_swift_backtraceSettings.outputTo == OutputTo::Stderr)
fd = STDERR_FILENO;

const char *intro;
if (_swift_backtraceSettings.color == OnOffTty::On) {
intro = "\n💣 \033[91mProgram crashed: ";
} else {
intro = "\n*** ";
}
write(fd, intro, strlen(intro));

char sigbuf[30];
strcpy(sigbuf, "Signal ");
_swift_formatUnsigned((unsigned)signum, sigbuf + 7);
write(fd, sigbuf, strlen(sigbuf));

const char *message;
if (!pc) {
message = ": Backtracing";
} else {
message = ": Backtracing from 0x";
}
write(fd, message, strlen(message));

if (pc) {
char pcbuf[18];
_swift_formatAddress(pc, pcbuf);
write(fd, pcbuf, strlen(pcbuf));
}

const char *outro;
if (_swift_backtraceSettings.color == OnOffTty::On) {
outro = "...\033[0m";
} else {
outro = "...";
}
write(fd, outro, strlen(outro));
#endif
}

} // namespace backtrace
} // namespace runtime
} // namespace swift
Loading