From af8cd71f59c54f4b7d402aaa2e798cffbc308b1e Mon Sep 17 00:00:00 2001 From: Amoelle Date: Sun, 25 May 2025 14:30:03 +0300 Subject: [PATCH] create simple kernel in C with a linker script --- kernel.c | 29 +++++++++++++++++++++++++++++ kernel.ld | 29 +++++++++++++++++++++++++++++ 2 files changed, 58 insertions(+) create mode 100644 kernel.c create mode 100644 kernel.ld diff --git a/kernel.c b/kernel.c new file mode 100644 index 0000000..6abe1b7 --- /dev/null +++ b/kernel.c @@ -0,0 +1,29 @@ +typedef unsigned char uint8_t; +typedef unsigned int uint32_t; +typedef uint32_t size_t; + +extern char __bss[], __bss_end[], __stack_top[]; + +void *memset(void *buf, char c, size_t n) { + uint8_t *p = (uint8_t *) buf; + while (n--) + *p++ = c; + return buf; +} + +void kernel_main(void) { + memset(__bss, 0, (size_t) __bss_end - (size_t) __bss); + + for (;;); +} + +__attribute__((section(".text.boot"))) +__attribute__((naked)) +void boot(void) { + __asm__ __volatile__( + "mv sp, %[stack_top]\n" // Set stacker point + "j kernel_main\n" // Jump to the kernel function + : + : [stack_top] "r" (__stack_top) // Pass the stack top address as %[stack_top] + ); +} diff --git a/kernel.ld b/kernel.ld new file mode 100644 index 0000000..d545dda --- /dev/null +++ b/kernel.ld @@ -0,0 +1,29 @@ +ENTRY(BOOT) + +SECTIONS { + . = 0x80200000; + + .text :{ + KEEP(*(.text.boot)); + *(.text .text.*); + } + + .rodata : ALIGN(4) { + *(.rodata .rodata.*); + } + + .data : ALIGN(4) { + *(.data .data.*); + } + + .bss : ALIGN(4) { + __bss = .; + *(.bss .bss.* .sbss .sbss.*); + __bss_end = .; + } + + . = ALIGN(4); + . += 128 * 1024 /* 128KB */ + __stack_top = .; + +}