/*
 * Fault report: a CPU exception in the title (bad pointer, illegal
 * instruction, ...) writes game:/crash.txt (and DbgPrint) with the
 * exception code, the faulting instruction, the registers and the return
 * addresses along the stack, then ends the title back to the dashboard.
 * Only faults in the title's own code are reported; others are passed on.
 * Look the addresses up with `xenon-addr2line -f -C -e app.elf <addr>`.
 *
 * How the kernel hands a title its faults was found on hardware by xsdk
 * (https://github.com/jessenic/xsdk, MIT; docs/HARDWARE.md, "How the kernel
 * hands a title its faults"): RtlSetVectoredExceptionHandler (0x36D) with
 * the handler as both arguments; the handler gets a pointer to the
 * exception record and the register context. A stack overflow can't be
 * caught (the context goes on the overflowed stack).
 */
#include <stdint.h>
#include <stdio.h>
#include <stdarg.h>
#include <string.h>
#include <fcntl.h>
#include <unistd.h>

#include "xex_runtime.h"

extern unsigned long RtlSetVectoredExceptionHandler(void *first, void *handler);
extern void XamLoaderTerminateTitle(void) __attribute__((noreturn));
extern unsigned long DbgPrint(const char *format, ...);

/* X_EXCEPTION_RECORD (xenia src/xenia/xbox.h) */
typedef struct {
    uint32_t code;
    uint32_t flags;
    uint32_t nested;
    uint32_t address;
    uint32_t parameter_count;
    uint32_t parameters[15];
} exception_record;

typedef struct {
    exception_record *record;
    uint8_t *context;
} exception_pointers;

/* Register context offsets (xsdk's probe) */
#define CTX_IAR 0x008
#define CTX_LR  0x00c
#define CTX_CTR 0x010
#define CTX_GPR 0x018   /* r0-r31, 64 bits each */
#define CTX_CR  0x118
#define CTX_XER 0x11c

#define CODE_START 0x82000000u
#define CODE_END   0x84000000u

static int report_fd = -1;
static char line[256];

static void out(const char *fmt, ...) __attribute__((format(printf, 1, 2)));
static void out(const char *fmt, ...)
{
    va_list ap;
    va_start(ap, fmt);
    int n = vsnprintf(line, sizeof(line), fmt, ap);
    va_end(ap);
    if (n < 0) return;
    if (n >= (int)sizeof(line)) n = sizeof(line) - 1;
    DbgPrint("%s", line);
    if (report_fd >= 0) write(report_fd, line, n);
}

static uint32_t ctx32(const uint8_t *ctx, unsigned offset)
{
    uint32_t v;
    memcpy(&v, ctx + offset, 4);
    return v;
}

/* low word of a 64-bit register */
static uint32_t gpr(const uint8_t *ctx, int n)
{
    return ctx32(ctx, CTX_GPR + n * 8 + 4);
}

static const char *code_name(uint32_t code)
{
    switch (code) {
        case 0xc0000005: return "access violation";
        case 0x80000002: return "misaligned data";
        case 0xc000001d: return "illegal instruction";
        case 0xc0000096: return "privileged instruction";
        case 0xc00000fd: return "stack overflow";
        case 0xc0000094: return "integer divide by zero";
        default: return "exception";
    }
}

long xex_fault_handler(exception_pointers *pointers)
{
    static int inside;
    if (inside) XamLoaderTerminateTitle();   /* a fault while reporting */
    inside = 1;

    exception_record *rec = pointers->record;
    const uint8_t *ctx = pointers->context;
    if (rec->address < CODE_START || rec->address >= CODE_END) {
        inside = 0;
        return 0;   /* EXCEPTION_CONTINUE_SEARCH: not in the title's code */
    }

    report_fd = open("game:/crash.txt", O_WRONLY | O_CREAT | O_TRUNC, 0666);
    out("FAKE-08 XEX crash: %s (code %08x) at %08x\n", code_name(rec->code), (unsigned)rec->code,
        (unsigned)rec->address);
    if (rec->code == 0xc0000005 && rec->parameter_count >= 2)
        out("  %s of address %08x\n", rec->parameters[0] ? "write" : "read", (unsigned)rec->parameters[1]);
    else if (rec->parameter_count >= 1)
        out("  parameter %08x\n", (unsigned)rec->parameters[0]);
    out("IAR %08x LR %08x CTR %08x CR %08x XER %08x\n", (unsigned)ctx32(ctx, CTX_IAR),
        (unsigned)ctx32(ctx, CTX_LR), (unsigned)ctx32(ctx, CTX_CTR + 4), (unsigned)ctx32(ctx, CTX_CR),
        (unsigned)ctx32(ctx, CTX_XER));
    for (int r = 0; r < 32; r += 4)
        out("r%-2d %08x %08x %08x %08x\n", r, (unsigned)gpr(ctx, r), (unsigned)gpr(ctx, r + 1),
            (unsigned)gpr(ctx, r + 2), (unsigned)gpr(ctx, r + 3));

    /* Return addresses: SysV frames keep LR 4 bytes into the caller's frame. */
    out("stack:\n");
    uint32_t sp = gpr(ctx, 1);
    for (int depth = 0; depth < 24 && sp && (sp & 7) == 0; depth++) {
        uint32_t caller = *(volatile uint32_t *)sp;
        if (caller <= sp || caller - sp > 0x100000) break;
        uint32_t ret = *(volatile uint32_t *)(caller + 4);
        if (ret >= CODE_START && ret < CODE_END) out("  %08x\n", (unsigned)ret);
        sp = caller;
    }
    if (report_fd >= 0) close(report_fd);

    XamLoaderTerminateTitle();
}

/* kernel_entries.S: keeps r14-r31 whole for the kernel when the handler
 * returns (faults outside the title's code are passed on). */
extern long xex_fault_handler_entry(exception_pointers *pointers);

void xex_install_fault_handler(void)
{
    RtlSetVectoredExceptionHandler((void *)xex_fault_handler_entry, (void *)xex_fault_handler_entry);
}
