text: /*
   * Copyright (c) 2021, Dylan Cleaver <dylancleaver@yahoo.com>
   *
   * SPDX-License-Identifier: BSD-2-Clause
   */
  
  #ifndef __no_kdebug
  
  #include <kernel/debug.h>
  #include <kernel/kassert.h>
  #include <kernel/serial.h>
  #include <stdbool.h>
  #include <stddef.h>
  #include <stdint.h>
  #include <stdio.h>
  #include <stdlib.h>
  #include <string.h>
  
  
  #if UINT32_MAX == UINTPTR_MAX
  #   define STACK_CANARY 0xE8942347
  #else
  #   define STACK_CANARY 0x5097839542112c67
  #endif
  
  
  uintptr_t __stack_chk_guard = STACK_CANARY;
  
  
  __attribute__((noreturn)) void
  __stack_chk_fail(void)
  {
      printf("Stack smashing detected\n");
      abort();
  }
  
  
  inline __attribute__((always_inline))
  void
  dump_all_registers_and_abort(void)
  {
      asm volatile (
          "\tpushq %%rax\n"
          "\tpushq %%rbx\n"
          "\tpushq %%rcx\n"
          "\tpushq %%rdx\n"
          "\tpushq %%rbp\n"
          "\tpushq %%rsp\n"
          "\tpushq %%rdi\n"
          "\tpushq %%rsi\n"
          "\tpushq %%r8\n"
          "\tpushq %%r9\n"
          "\tpushq %%r10\n"
          "\tpushq %%r11\n"
          "\tpushq %%r12\n"
          "\tpushq %%r13\n"
          "\tpushq %%r14\n"
          "\tpushq %%r15\n"
          :
      );
  
      uint64_t registers[16];
      size_t i;
      for (i=0; i<16; ++i)
      {
          asm volatile(
              "\tpopq %%rax\n"
              "\tmovq %%rax, %0"
              : "=r"(registers[i])
          );
      }
  
      printf("\n-------------------------------------\n");
      printf("Register dump:\n\n");
      printf("RAX: %x", registers[15]);
      printf("  RBX: %x", registers[14]);
      printf("  RCX: %x", registers[13]);
      printf("  RDX: %x\n", registers[12]);
      printf("RBP: %x", registers[11]);
      printf("  RSP: %x", registers[10]);
      printf("  RDI: %x", registers[9]);
      printf("  RSI: %x\n", registers[8]);
      printf("R8:  %x", registers[7]);
      printf("  R9:  %x", registers[6]);
      printf("  R10: %x", registers[5]);
      printf("  R11: %x\n", registers[4]);
      printf("R12: %x", registers[3]);
      printf("  R13: %x", registers[2]);
      printf("  R14: %x", registers[1]);
      printf("  R15: %x\n", registers[0]);
      printf("\n-------------------------------------\n");
  
      abort();
  }
  
  #endif
  