Luce packages
LuceLuce BaseLuciaOS

dymokomi/luce-std

Source of release 0.7.5

0.7.5 / src / crash / relaunch.lucb

#==============================================================================================
#
#   relaunch - Starting the program again to show its report
#
#   DESCRIPTION:
#       A crashed process cannot be trusted to draw: its heap may be broken, and a
#       fatal signal's handler may call next to nothing. So, as macOS's own crash
#       reporter does, the report is shown by another process: this program's own
#       executable, started with no arguments and LUCE_CRASH_REPORT naming the report.
#       Everything that start needs (the executable's path, the arguments, the
#       environment, the spawn attributes) is made ready when the program asks for it,
#       so the crash itself only calls posix_spawn, which is safe in a signal handler
#       on macOS and Linux, or CreateProcessW on Windows.
#
#==============================================================================================

import windows_text

extern func spawn_posix as "posix_spawn"(pid: i32*, path: c.str, actions: void*?, attributes: const void*?, arguments: const (c.str?)*, environment: const (c.str?)*) -> i32
extern func spawn_attributes_init as "posix_spawnattr_init"(attributes: void*) -> i32
extern func spawn_attributes_flags as "posix_spawnattr_setflags"(attributes: void*, flags: i16) -> i32
extern func spawn_attributes_mask as "posix_spawnattr_setsigmask"(attributes: void*, mask: const void*) -> i32
extern func signals_empty as "sigemptyset"(set: void*) -> i32
extern func spawn_actions_init as "posix_spawn_file_actions_init"(actions: void*) -> i32
extern func spawn_actions_open as "posix_spawn_file_actions_addopen"(actions: void*, descriptor: i32, path: c.str, flags: i32, mode: u32) -> i32
extern func crash_environment as "_NSGetEnviron"() -> (c.str?)**
extern var environ: (c.str?)*
extern func create_process as "CreateProcessW"(application: const u16*, command: u16*, process_security: void*?, thread_security: void*?, inherit: i32, flags: u32, environment: void*?, directory: void*?, startup: StartupInfo*, process: ProcessInformation*) -> i32
extern func close_handle as "CloseHandle"(handle: void*?) -> i32
extern func environment_strings as "GetEnvironmentStringsW"() -> u16*?
extern func free_environment_strings as "FreeEnvironmentStringsW"(block: u16*) -> i32
extern func quick_exit as "_exit"(code: i32) -> never

## STARTUPINFOW.
extern struct StartupInfo:
    size: u32
    reserved: void*?
    desktop: void*?
    title: void*?
    x: u32
    y: u32
    width: u32
    height: u32
    columns: u32
    rows: u32
    fill: u32
    flags: u32
    show: u16
    reserved_size: u16
    reserved_data: void*?
    input: void*?
    output: void*?
    errors: void*?

## PROCESS_INFORMATION.
extern struct ProcessInformation:
    process: void*?
    thread: void*?
    pid: u32
    tid: u32

## The program could not be made ready to start again, or could not be started.
pub let failed: ErrorCode = ErrorCode.package(85)

# mark: Making ready ===========================================================================

## Whether a crash starts the reporter, and whether it has: once a process.
var relaunching: bool = false
var reporter_started: @bool
## POSIX: the executable, `argv` and `envp`, the spawn attributes (no signal blocked
## in the reporter) and its file actions (its standard streams on /dev/null, so a
## parent reading the crashed program's output is not kept waiting by the window).
## `posix_spawnattr_t`, `posix_spawn_file_actions_t` and `sigset_t` are opaque; these
## words hold either platform's.
var posix_arguments: (c.str?)[]
var posix_environment: (c.str?)[]
var spawn_attributes: u64[64]
var spawn_actions: u64[16]
var no_signals: u64[16]
## Windows: the executable and the command line as UTF-16, and the environment block.
var windows_program: u16[]
var windows_command: u16[]
var windows_environment: u16[]

## After a crash, once its report is written (and the hooks have run), start this
## program again with no arguments and LUCE_CRASH_REPORT naming the report, so the
## new process can show it (`report_to_show`); luce-ui shows it in a window. A
## process started that way never does this itself, so a crash while showing a
## report starts nothing. Turns crash reports on when they are off.
pub func relaunch_on_crash() -> !:
    if relaunching or showing_report():
        return
    if not core.crash_reports_enabled():
        try enable()
    var setting: u8[1200]
    let variable = try strings.format(setting, f"{(str)report_variable}={(str)report_path[..<report_length]}")
    with memory.heap:
        let program = try os.executable()
        if platform.windows:
            try ready_windows(program, variable)
        else:
            try ready_posix(program, variable)
    relaunching = true

func ready_posix(program: str, variable: str) -> !:
    posix_arguments = try new (c.str?)[2] ---
    posix_arguments[0] = (c.str)program
    posix_arguments[1] = none
    let inherited = current_environment()
    var count: usize = 0
    while inherited[count] != none:
        count += 1
    posix_environment = try new (c.str?)[count + 2] ---
    var kept: usize = 0
    for index in 0..<count:
        let entry = inherited[index] else break
        if not names_report((str)entry):
            posix_environment[kept] = entry
            kept += 1
    posix_environment[kept] = (c.str)try strings.copy(variable)
    posix_environment[kept + 1] = none
    if spawn_attributes_init((void*)&spawn_attributes[0]) != 0:
        error(failed, "the spawn attributes could not be made")
    _ = signals_empty((void*)&no_signals[0])
    # POSIX_SPAWN_SETSIGMASK: the reporter starts with no signal blocked
    _ = spawn_attributes_mask((void*)&spawn_attributes[0], (const void*)&no_signals[0])
    _ = spawn_attributes_flags((void*)&spawn_attributes[0], 8)
    if spawn_actions_init((void*)&spawn_actions[0]) != 0:
        error(failed, "the spawn file actions could not be made")
    for descriptor in [(i32)0, 1, 2]:
        # O_RDONLY for the input, O_WRONLY for the outputs
        _ = spawn_actions_open((void*)&spawn_actions[0], descriptor, "/dev/null", 0 if descriptor == 0 else 1, 0)

func ready_windows(program: str, variable: str) -> !:
    windows_program = try windows_text.wide((c.str)program, failed)
    windows_command = try quoted_command(windows_program)
    let block = environment_strings() else error(failed, "the environment could not be read")
    defer _ = free_environment_strings(block)
    var length: usize = 0
    while block[length] != 0 or block[length + 1] != 0:
        length += 1
    let ours = try windows_text.wide((c.str)try strings.copy(variable), failed)
    windows_environment = try new u16[length + ours.length + 2] ---
    var used: usize = 0
    var start: usize = 0
    # each entry ends with a NUL, the block with one more
    while block[start] != 0:
        var end = start
        while block[end] != 0:
            end += 1
        if not wide_names_report(block, start, end):
            for index in start..=end:
                windows_environment[used] = block[index]
                used += 1
        start = end + 1
    for code in ours:
        windows_environment[used] = code
        used += 1
    windows_environment[used] = 0

## `"program"`, NUL-terminated: CreateProcessW may write to its command line.
func quoted_command(program: const u16[]) -> u16[]!:
    let command = try new u16[program.length + 2] ---
    command[0] = (u16)'"'
    var used: usize = 1
    for code in program:
        if code == 0:
            break
        command[used] = code
        used += 1
    command[used] = (u16)'"'
    command[used + 1] = 0
    return command

## Whether an environment entry is a report to show, which a new process never inherits.
func names_report(entry: str) -> bool:
    let name = (str)report_variable
    return entry.length > name.length and strings.starts_with(entry, name) and entry.bytes[name.length] == '='

func wide_names_report(block: u16*, start: usize, end: usize) -> bool:
    let name = (str)report_variable
    if end - start <= name.length or block[start + name.length] != (u16)'=':
        return false
    for index in 0..<name.length:
        if block[start + index] != (u16)name.bytes[index]:
            return false
    return true

func current_environment() -> (c.str?)*:
    if platform.macos:
        return *crash_environment()
    return environ

# mark: Starting ===============================================================================

## Start the reporter, once, if the program asked for one. Safe in a signal
## handler: it only reads what `relaunch_on_crash` made ready and starts a process.
func start_reporter():
    if not relaunching or reporter_started.swap(true, .acq_rel):
        return
    if platform.windows:
        _ = start_windows(windows_program.data, windows_command.data, (void*)windows_environment.data)
    elif platform.posix:
        let program = posix_arguments[0] else return
        var pid: i32 = 0
        _ = spawn_posix(&pid, program, (void*)&spawn_actions[0], (const void*)&spawn_attributes[0], posix_arguments.data, posix_environment.data)

func start_windows(program: const u16*, command: u16*, environment: void*?) -> bool:
    var startup: StartupInfo
    startup.size = (u32)memory.size_of(StartupInfo)
    var started: ProcessInformation
    # CREATE_UNICODE_ENVIRONMENT
    if create_process(program, command, none, none, 0, 1024, environment, none, &startup, &started) == 0:
        return false
    _ = close_handle(started.process)
    _ = close_handle(started.thread)
    return true

## Start this program again as an ordinary run: no arguments, and without the report
## this process was started to show. It does not wait for it: the caller usually
## quits next, as a crash window's Reopen does.
pub func reopen() -> !:
    try os.unset_env(report_variable)
    let program = try os.executable()
    defer strings.release(program)
    if platform.windows:
        let wide = try windows_text.wide((c.str)program, failed)
        defer free(wide)
        let command = try quoted_command(wide)
        defer free(command)
        if not start_windows(wide.data, command.data, none):
            error(failed, "the program could not be started again")
    else:
        var arguments: (c.str?)[2] = [(c.str)program, none]
        var pid: i32 = 0
        if spawn_posix(&pid, (c.str)program, none, none, &arguments[0], current_environment()) != 0:
            error(failed, "the program could not be started again")