#include "coredump.h"
#include "mini_printf.h"

extern uint32_t _stack_top;
extern uint32_t _data_run;
extern uint32_t _data_run_end;
extern uint32_t _data_ccm_run;
extern uint32_t _data_ccm_run_end;
extern uint32_t _bss_run;
extern uint32_t _bss_run_end;
extern uint32_t _bss_ccm_run;
extern uint32_t _bss_ccm_run_end;

static void coredump_registers(struct coredump_regs_s *sp, char *thread)
{
    mini_printf("\nregister@%s\n", thread);
    mini_printf("R0:      0x%p\n", sp->r0);
    mini_printf("R1:      0x%p\n", sp->r1);
    mini_printf("R2:      0x%p\n", sp->r2);
    mini_printf("R3:      0x%p\n", sp->r3);
    mini_printf("R4:      0x%p\n", sp->r4);
    mini_printf("R5:      0x%p\n", sp->r5);
    mini_printf("R6:      0x%p\n", sp->r6);
    mini_printf("R7:      0x%p\n", sp->r7);
    mini_printf("R8:      0x%p\n", sp->r8);
    mini_printf("R9:      0x%p\n", sp->r9);
    mini_printf("R10:     0x%p\n", sp->r10);
    mini_printf("R11:     0x%p\n", sp->r11);
    mini_printf("R12:     0x%p\n", sp->r12);
    mini_printf("R13(SP): 0x%p\n", (uint32_t)sp + sizeof(*sp));
    mini_printf("R14(LR): 0x%p\n", sp->lr);
    mini_printf("R15(PC): 0x%p\n", sp->pc);
    mini_printf("xPSR:    0x%p\n", sp->xpsr);
}

static void coredump_memory(uint32_t *start, uint32_t *end, char *comment)
{
    mini_printf("\nmemory@%s, length=%d", comment, end - start);
    for (uint32_t p = (uint32_t)start & 0xFFFFFFF0; p < (uint32_t)end; p += 4) {
        if ((p & 0xF) == 0) {
            mini_printf("\n0x%p:", p);
        }
        mini_printf(" %p", *(uint32_t *)p);
    }
}

void coredump(struct coredump_regs_s *sp)
{
    mini_printf_init();
    coredump_registers(sp, "main_thread");
    coredump_memory((uint32_t*)sp, &_stack_top, "stack");
    coredump_memory(&_data_run, &_data_run_end, "data");
    coredump_memory(&_data_ccm_run, &_data_ccm_run_end, "data_ccm");
    coredump_memory(&_bss_run, &_bss_run_end, "bss");
    coredump_memory(&_bss_ccm_run, &_bss_ccm_run_end, "bss_ccm");
}
