aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorRaghuram Subramani <raghus2247@gmail.com>2024-12-29 07:39:44 -0500
committerRaghuram Subramani <raghus2247@gmail.com>2024-12-29 07:39:44 -0500
commitc8d2524d2d45a107032d88062a95f6e659d600c3 (patch)
tree3d98f7c351027805c1b600961a131f7440106e73
parent6879ab18c79fc05c6b9da937e4645fe3c882b58c (diff)
kernel: introduce global constructors
https://wiki.osdev.org/Calling_Global_Constructors
-rw-r--r--kernel/CMakeLists.txt35
-rw-r--r--kernel/arch/x86/init/crti.s17
-rw-r--r--kernel/arch/x86/init/crtn.s9
3 files changed, 61 insertions, 0 deletions
diff --git a/kernel/CMakeLists.txt b/kernel/CMakeLists.txt
index 7f9e7f4..0c3c028 100644
--- a/kernel/CMakeLists.txt
+++ b/kernel/CMakeLists.txt
@@ -3,6 +3,7 @@ project(kernel C ASM)
set(KERNEL_SRC
kernel/kernel.c
+
arch/x86/init/boot.s
)
@@ -25,4 +26,38 @@ set(LINKER_FLAGS
-T ${LINKER_SCRIPT}
-nostdlib
)
+
+execute_process(COMMAND ${CMAKE_C_COMPILER}
+ -print-file-name=crtbegin.o
+ OUTPUT_VARIABLE CRTBEGIN_O
+ OUTPUT_STRIP_TRAILING_WHITESPACE
+)
+
+execute_process(COMMAND ${CMAKE_C_COMPILER}
+ -print-file-name=crtend.o
+ OUTPUT_VARIABLE CRTEND_O
+ OUTPUT_STRIP_TRAILING_WHITESPACE
+)
+
+add_library(crti OBJECT arch/x86/init/crti.s)
+add_library(crtn OBJECT arch/x86/init/crtn.s)
+add_dependencies(kernel crti crtn)
+
+get_target_property(CRTI_SRC crti SOURCES)
+get_target_property(CRTN_SRC crtn SOURCES)
+get_target_property(CRTI_OUT crti BINARY_DIR)
+get_target_property(CRTN_OUT crtn BINARY_DIR)
+
+set(CRTI_O "${CRTI_OUT}/CMakeFiles/crti.dir/${CRTI_SRC}.o")
+set(CRTN_O "${CRTN_OUT}/CMakeFiles/crtn.dir/${CRTN_SRC}.o")
+
+set(CMAKE_C_LINK_EXECUTABLE "${CMAKE_C_COMPILER} <CMAKE_C_LINK_FLAGS> <FLAGS> <LINK_FLAGS> \
+ ${CRTI_O} \
+ ${CRTBEGIN_O} \
+ <OBJECTS> \
+ ${CRTEND_O} \
+ ${CRTN_O} \
+ -o <TARGET> <LINK_LIBRARIES>"
+)
+
target_link_options(kernel PRIVATE ${LINKER_FLAGS})
diff --git a/kernel/arch/x86/init/crti.s b/kernel/arch/x86/init/crti.s
new file mode 100644
index 0000000..a13dd81
--- /dev/null
+++ b/kernel/arch/x86/init/crti.s
@@ -0,0 +1,17 @@
+.intel_syntax noprefix
+
+.section .init
+.global _init
+.type _init, @function
+_init:
+ push ebp
+ mov ebp, esp
+ /* gcc will nicely put the contents of crtbegin.o's .init section here. */
+
+.section .fini
+.global _fini
+.type _fini, @function
+_fini:
+ push ebp
+ mov ebp, esp
+ /* gcc will nicely put the contents of crtbegin.o's .fini section here. */
diff --git a/kernel/arch/x86/init/crtn.s b/kernel/arch/x86/init/crtn.s
new file mode 100644
index 0000000..c5a9bf2
--- /dev/null
+++ b/kernel/arch/x86/init/crtn.s
@@ -0,0 +1,9 @@
+.section .init
+ /* gcc will nicely put the contents of crtend.o's .init section here. */
+ popl %ebp
+ ret
+
+.section .fini
+ /* gcc will nicely put the contents of crtend.o's .fini section here. */
+ popl %ebp
+ ret