/*
 * Copyright (c) 2026, Chloe M.
 * Provided under the BSD-3 clause.
 *
 * Description: Trap dispatch
 * Author:      Chloe M.
 */

#include <machine/trap.h>
#include <ke/bugcheck.h>
#include <ptdef.h>

#define TRAP_STR(TYPE)              \
    ((TYPE) >= NELEM(TrapTab))      \
        ? "bad trap type"           \
        : TrapTab[(TYPE)]

static const CHAR *TrapTab[] = {
    [TRAP_DIVERR] = "divide error",
    [TRAP_DEBUG_EXCEPTION] = "debug exception",
    [TRAP_NMI] = "non-maskable interrupt",
    [TRAP_BREAKPOINT] = "breakpoint",
    [TRAP_OVERFLOW] = "overflow",
    [TRAP_BOUND_RANGE] = "bound range exceeded",
    [TRAP_INVALID_OPCODE] = "invalid opcode",
    [TRAP_NO_COPROCESSOR] = "no math coprocessor",
    [TRAP_DOUBLE_FAULT] = "double fault",
    [TRAP_RESERVED] = "reserved exception",
    [TRAP_INVALID_TSS] = "invalid tss",
    [TRAP_SEG_NOT_PRESENT] = "segment not present",
    [TRAP_STACK_SEG_FAULT] = "stack segment fault",
    [TRAP_GENERAL_PROTECTION] = "general protection fault",
    [TRAP_PAGE_FAULT] = "page fault"
};

VOID
MdTrapDispatch(TRAP_FRAME *TrapFrame)
{
    /* Sanity check */
    if (TrapFrame == NULL) {
        KeBugCheck(
            BUGCHECK_UNBOUND_RESRC,
            "unbound trapframe during dispatch\n"
        );
    }

    KeBugCheck(
        BUGCHECK_EXCEPTION,
        "got fatal %s\n", TRAP_STR(TrapFrame->Vector)
    );
}
