From 386d9a5bffcd66633e4c3c72eb6cb25722796c92 Mon Sep 17 00:00:00 2001 From: Amlal El Mahrouss Date: Sat, 24 May 2025 10:59:49 +0200 Subject: feat(kernel): Better syscall routing, also added new tools. what: - ping, manual have been added. - Rework RtlCurrentPID to SchedGetCurrentProcessID. - Cleanup codebase overall. Signed-off-by: Amlal El Mahrouss --- public/tools/ping/src/CommandLine.cc | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) create mode 100644 public/tools/ping/src/CommandLine.cc (limited to 'public/tools/ping/src/CommandLine.cc') diff --git a/public/tools/ping/src/CommandLine.cc b/public/tools/ping/src/CommandLine.cc new file mode 100644 index 00000000..9aae0ea9 --- /dev/null +++ b/public/tools/ping/src/CommandLine.cc @@ -0,0 +1,29 @@ +#include + +SInt32 _NeMain(SInt32 argc, Char* argv[]) { + SCI_UNUSED(argc); + + if (argc < 2) { + PrintOut(nullptr, "HELP: ping \n"); + return EXIT_FAILURE; + } + + PrintOut(nullptr, "Pinging %s...\n", argv[1]); + + for (SizeT i = 0U; i < 4; ++i) { + SInt32 result = 0; + + if (result != 0) { + PrintOut(nullptr, "Request timed out.\n"); + return EXIT_FAILURE; + } + + SInt32 bytes = 64; // Simulated response size + SInt32 time = 100 + (i * 10); // Simulated response time + SInt32 ttl = 64; + + PrintOut(nullptr, "Reply from %s: bytes=%i time=%ims TTL=%i\n", argv[1], bytes, time, ttl); + } + + return EXIT_SUCCESS; +} \ No newline at end of file -- cgit v1.2.3 From 5b30cacacf0f0ca6fb06bb34389f04b05ceb2b15 Mon Sep 17 00:00:00 2001 From: Amlal El Mahrouss Date: Sun, 25 May 2025 09:56:46 +0200 Subject: kernel!: lots of changes, see commit details. refactor(hal): unify file naming and drop redundant architecture suffixes feat(build): rename kernel and bootloader to 'ne_kernel' and 'ne_bootz' refactor(memory): replace mm_get_phys_address with mm_get_page_addr feat(bitmap): track bitmap allocator usage and add out-of-memory error fix(heap): correct heap magic naming and alignment logic chore(fs): downgrade HeFS disk size check to warning chore(tools): clean up formatting in 'ping' and 'manual' docs(design): update OS_DESIGN.drawio to reflect Hypr86 and new layout Signed-off-by: Amlal El Mahrouss --- .gitignore | 3 + dev/boot/BootKit/Support.h | 4 +- dev/boot/amd64-ci.make | 6 +- dev/boot/amd64-desktop.make | 6 +- dev/boot/arm64-desktop.make | 6 +- dev/boot/src/BootloaderRsrc.rsrc | 2 +- dev/boot/src/HEL/AMD64/BootEFI.cc | 4 +- dev/boot/src/HEL/ARM64/BootEFI.cc | 2 +- dev/kernel/HALKit/AMD64/HalApplicationProcessor.cc | 1 + dev/kernel/HALKit/AMD64/HalControlRegister.s | 45 ------ dev/kernel/HALKit/AMD64/HalControlRegisterAPI.s | 45 ++++++ dev/kernel/HALKit/AMD64/HalCoreInterruptHandler.cc | 159 ++++++++++++++++++++ .../HALKit/AMD64/HalCoreInterruptHandlerAMD64.cc | 159 -------------------- dev/kernel/HALKit/AMD64/HalKernelMain.cc | 10 +- dev/kernel/HALKit/AMD64/HalPagingMgr.cc | 164 +++++++++++++++++++++ dev/kernel/HALKit/AMD64/HalPagingMgrAMD64.cc | 164 --------------------- dev/kernel/HALKit/AMD64/HalProcessor.cc | 89 +++++++++++ dev/kernel/HALKit/AMD64/HalProcessorAMD64.cc | 80 ---------- .../HALKit/AMD64/HalSchedulerCorePrimitives.cc | 47 ++++++ .../AMD64/HalSchedulerCorePrimitivesAMD64.cc | 47 ------ dev/kernel/HALKit/AMD64/HalTimer.cc | 97 ++++++++++++ dev/kernel/HALKit/AMD64/HalTimerAMD64.cc | 97 ------------ dev/kernel/HALKit/AMD64/HalUtilsAPI.asm | 2 - .../HALKit/AMD64/Network/Generic+Basic+RTL8139.cc | 2 +- dev/kernel/HALKit/AMD64/Processor.h | 13 +- dev/kernel/HALKit/AMD64/Storage/AHCI+Generic.cc | 4 +- dev/kernel/HALKit/ARM64/HalPagingMgr.cc | 28 ++++ dev/kernel/HALKit/ARM64/HalPagingMgrARM64.cc | 28 ---- dev/kernel/HALKit/ARM64/HalSchedulerCore.cc | 21 +++ dev/kernel/HALKit/ARM64/HalSchedulerCoreARM64.cc | 21 --- .../HALKit/ARM64/HalSchedulerCorePrimitives.cc | 30 ++++ .../ARM64/HalSchedulerCorePrimitivesARM64.cc | 30 ---- dev/kernel/HALKit/ARM64/HalTimer.cc | 15 ++ dev/kernel/HALKit/ARM64/HalTimerARM64.cc | 15 -- dev/kernel/HALKit/ARM64/Processor.h | 2 +- dev/kernel/KernelKit/KPC.h | 3 +- dev/kernel/KernelKit/LockDelegate.h | 4 +- dev/kernel/KernelKit/ZXD.h | 24 +-- dev/kernel/amd64-ci.make | 2 +- dev/kernel/amd64-desktop.make | 2 +- dev/kernel/arm64-desktop.make | 2 +- dev/kernel/kernel_rsrc.rsrc | 2 +- dev/kernel/src/BitMapMgr.cc | 18 ++- dev/kernel/src/FS/HeFS+FileSystemParser.cc | 5 +- dev/kernel/src/HeapMgr.cc | 16 +- dev/kernel/src/PEFCodeMgr.cc | 2 +- dev/kernel/src/UserProcessScheduler.cc | 4 +- docs/drawio/OS_DESIGN.drawio | 30 ++-- public/tools/manual/src/CommandLine.cc | 4 +- public/tools/ping/src/CommandLine.cc | 8 +- 50 files changed, 798 insertions(+), 776 deletions(-) delete mode 100644 dev/kernel/HALKit/AMD64/HalControlRegister.s create mode 100644 dev/kernel/HALKit/AMD64/HalControlRegisterAPI.s create mode 100644 dev/kernel/HALKit/AMD64/HalCoreInterruptHandler.cc delete mode 100644 dev/kernel/HALKit/AMD64/HalCoreInterruptHandlerAMD64.cc create mode 100644 dev/kernel/HALKit/AMD64/HalPagingMgr.cc delete mode 100644 dev/kernel/HALKit/AMD64/HalPagingMgrAMD64.cc create mode 100644 dev/kernel/HALKit/AMD64/HalProcessor.cc delete mode 100644 dev/kernel/HALKit/AMD64/HalProcessorAMD64.cc create mode 100644 dev/kernel/HALKit/AMD64/HalSchedulerCorePrimitives.cc delete mode 100644 dev/kernel/HALKit/AMD64/HalSchedulerCorePrimitivesAMD64.cc create mode 100644 dev/kernel/HALKit/AMD64/HalTimer.cc delete mode 100644 dev/kernel/HALKit/AMD64/HalTimerAMD64.cc create mode 100644 dev/kernel/HALKit/ARM64/HalPagingMgr.cc delete mode 100644 dev/kernel/HALKit/ARM64/HalPagingMgrARM64.cc create mode 100644 dev/kernel/HALKit/ARM64/HalSchedulerCore.cc delete mode 100644 dev/kernel/HALKit/ARM64/HalSchedulerCoreARM64.cc create mode 100644 dev/kernel/HALKit/ARM64/HalSchedulerCorePrimitives.cc delete mode 100644 dev/kernel/HALKit/ARM64/HalSchedulerCorePrimitivesARM64.cc create mode 100644 dev/kernel/HALKit/ARM64/HalTimer.cc delete mode 100644 dev/kernel/HALKit/ARM64/HalTimerARM64.cc (limited to 'public/tools/ping/src/CommandLine.cc') diff --git a/.gitignore b/.gitignore index 01c18138..9722f662 100644 --- a/.gitignore +++ b/.gitignore @@ -20,6 +20,9 @@ public/frameworks/*/dist/* *.pdf *.aux +ne_kernel +ne_bootz + neoskrnl/neoskrnl.xcodeproj/project.xcworkspace/xcshareddata/ tooling/dist/mkfs.* diff --git a/dev/boot/BootKit/Support.h b/dev/boot/BootKit/Support.h index 6e1407c2..b4129abc 100644 --- a/dev/boot/BootKit/Support.h +++ b/dev/boot/BootKit/Support.h @@ -9,7 +9,7 @@ /// @file Support.h /// @brief Purpose of this file is to help port libs into the bootloader. -#ifndef __aarch64__ +#ifndef __NE_ARM64__ #include #endif @@ -38,7 +38,9 @@ EXTERN_C int strcmp(const char* whatToCheck, const char* whatToCheckRight); #else +#ifndef __NE_ARM64__ #include +#endif #endif // __BOOTZ__ diff --git a/dev/boot/amd64-ci.make b/dev/boot/amd64-ci.make index d711abde..0715151c 100644 --- a/dev/boot/amd64-ci.make +++ b/dev/boot/amd64-ci.make @@ -69,8 +69,8 @@ FLAG_GNU=-fshort-wchar -Wall -Wpedantic -Wextra -Werror -D__EFI_x86_64__ -mno-re -DEFI_FUNCTION_WRAPPER -I./ -I../kernel $(DEBUG_MACRO) $(DISK_DRV) -I../ -c -nostdlib -fno-rtti -fno-exceptions \ -std=c++20 -DBOOTZ_GPT_SUPPORT -DBOOTZ_EPM_SUPPORT -D__HAVE_NE_APIS__ -DZBA_USE_FB -D__NE_AMD64__ -D__NE__ -DNE_AUTO_FORMAT -BOOTLOADER=bootz.efi -KERNEL=krnl.efi +BOOTLOADER=ne_bootz +KERNEL=ne_kernel SYSCHK=chk.efi BOOTNET=net.efi SCIKIT=libSystem.sys @@ -130,7 +130,7 @@ efi: $(HTTP_GET) https://retrage.github.io/edk2-nightly/bin/DEBUGX64_OVMF.fd -O OVMF.fd BINS=*.bin -EXECUTABLES=bootz.efi krnl.efi OVMF.fd +EXECUTABLES=ne_bootz ne_kernel OVMF.fd TARGETS=$(REM_FLAG) $(OBJ) $(BIN) $(IMG) $(IMG_2) $(EXECUTABLES) diff --git a/dev/boot/amd64-desktop.make b/dev/boot/amd64-desktop.make index 05ac5db8..113c6295 100644 --- a/dev/boot/amd64-desktop.make +++ b/dev/boot/amd64-desktop.make @@ -71,8 +71,8 @@ FLAG_GNU=-fshort-wchar -D__EFI_x86_64__ -Wall -Wpedantic -Wextra -mno-red-zone - -DEFI_FUNCTION_WRAPPER -I./ -I../kernel $(DISK_DRV) -I../ -c -nostdlib -fno-rtti -fno-exceptions \ -std=c++20 -DBOOTZ_GPT_SUPPORT -D__HAVE_NE_APIS__ -DZBA_USE_FB -D__NE_AMD64__ -D__NE__ -DNE_AUTO_FORMAT -Wl,--disable-reloc-section -BOOTLOADER=bootz.efi -KERNEL=krnl.efi +BOOTLOADER=ne_bootz +KERNEL=ne_kernel SYSCHK=chk.efi BOOTNET=net.efi SCIKIT=libSystem.sys @@ -140,7 +140,7 @@ efi: $(HTTP_GET) https://retrage.github.io/edk2-nightly/bin/DEBUGX64_OVMF.fd -O OVMF.fd BINS=*.bin -EXECUTABLES=bootz.efi krnl.efi OVMF.fd +EXECUTABLES=ne_bootz ne_kernel OVMF.fd TARGETS=$(REM_FLAG) $(OBJ) $(BIN) $(IMG) $(IMG_2) $(EXECUTABLES) diff --git a/dev/boot/arm64-desktop.make b/dev/boot/arm64-desktop.make index 114d2e7e..409975a4 100644 --- a/dev/boot/arm64-desktop.make +++ b/dev/boot/arm64-desktop.make @@ -47,8 +47,8 @@ FLAG_GNU=-fshort-wchar -c -ffreestanding -MMD -mno-red-zone -D__NE_ARM64__ -fno- -target aarch64-unknown-windows \ -std=c++20 -DBOOTZ_EPM_SUPPORT -DZBA_USE_FB -D__FSKIT_USE_NEFS__ -D__BOOTZ_STANDALONE__ -D__NEOSKRNL__ -D__BOOTZ__ -D__HAVE_NE_APIS__ -D__NE__ -I../ -I../kernel -BOOT_LOADER=bootz.efi -KERNEL=krnl.efi +BOOT_LOADER=ne_bootz +KERNEL=ne_kernel SYSCHK=chk.efi STARTUP=startup.efi @@ -94,7 +94,7 @@ efi: $(HTTP_GET) https://retrage.github.io/edk2-nightly/bin/DEBUGAARCH64_QEMU_EFI.fd -O OVMF.fd BINS=*.bin -EXECUTABLES=bootz.efi krnl.efi OVMF.fd +EXECUTABLES=ne_bootz ne_kernel OVMF.fd TARGETS=$(REM_FLAG) $(OBJ) $(BIN) $(IMG) $(IMG_2) $(EXECUTABLES) diff --git a/dev/boot/src/BootloaderRsrc.rsrc b/dev/boot/src/BootloaderRsrc.rsrc index c634a8f6..33bce7f7 100644 --- a/dev/boot/src/BootloaderRsrc.rsrc +++ b/dev/boot/src/BootloaderRsrc.rsrc @@ -13,7 +13,7 @@ BEGIN VALUE "FileVersion", BOOTLOADER_VERSION VALUE "InternalName", "bootz" VALUE "LegalCopyright", "Copyright (C) 2024, Amlal El Mahrouss all rights reserved." - VALUE "OriginalFilename", "bootz.efi" + VALUE "OriginalFilename", "ne_bootz" VALUE "ProductName", "bootz" VALUE "ProductVersion", BOOTLOADER_VERSION END diff --git a/dev/boot/src/HEL/AMD64/BootEFI.cc b/dev/boot/src/HEL/AMD64/BootEFI.cc index 58610c39..e1dd5d9e 100644 --- a/dev/boot/src/HEL/AMD64/BootEFI.cc +++ b/dev/boot/src/HEL/AMD64/BootEFI.cc @@ -193,8 +193,8 @@ EFI_EXTERN_C EFI_API Int32 BootloaderMain(EfiHandlePtr image_handle, EfiSystemTa handover_hdr->f_FirmwareVendorLen = Boot::BStrLen(sys_table->FirmwareVendor); // Assign to global 'kHandoverHeader'. - WideChar kernel_path[256U] = L"krnl.efi"; - UInt32 kernel_path_sz = StrLen("krnl.efi"); + WideChar kernel_path[256U] = L"ne_kernel"; + UInt32 kernel_path_sz = StrLen("ne_kernel"); UInt32 sz_ver = sizeof(UInt64); UInt64 ver = KERNEL_VERSION_BCD; diff --git a/dev/boot/src/HEL/ARM64/BootEFI.cc b/dev/boot/src/HEL/ARM64/BootEFI.cc index be2d8acd..413edd5b 100644 --- a/dev/boot/src/HEL/ARM64/BootEFI.cc +++ b/dev/boot/src/HEL/ARM64/BootEFI.cc @@ -210,7 +210,7 @@ EFI_EXTERN_C EFI_API Int32 BootloaderMain(EfiHandlePtr image_handle, EfiSystemTa handover_hdr->f_FirmwareVendorLen = Boot::BStrLen(sys_table->FirmwareVendor); - Boot::BootFileReader reader_kernel(L"krnl.efi", image_handle); + Boot::BootFileReader reader_kernel(L"ne_kernel", image_handle); reader_kernel.ReadAll(0); diff --git a/dev/kernel/HALKit/AMD64/HalApplicationProcessor.cc b/dev/kernel/HALKit/AMD64/HalApplicationProcessor.cc index 7926289f..2ce05e7c 100644 --- a/dev/kernel/HALKit/AMD64/HalApplicationProcessor.cc +++ b/dev/kernel/HALKit/AMD64/HalApplicationProcessor.cc @@ -128,6 +128,7 @@ EXTERN_C BOOL mp_register_task(HAL::StackFramePtr stack_frame, ProcessID thrdid) /// @brief Is the current config SMP aware? /// @return True if YES, False if not. /***********************************************************************************/ + Bool mp_is_smp(Void) noexcept { return kSMPAware; } diff --git a/dev/kernel/HALKit/AMD64/HalControlRegister.s b/dev/kernel/HALKit/AMD64/HalControlRegister.s deleted file mode 100644 index 631d1d55..00000000 --- a/dev/kernel/HALKit/AMD64/HalControlRegister.s +++ /dev/null @@ -1,45 +0,0 @@ -/* ------------------------------------------- - - Copyright (C) 2024-2025, Amlal El Mahrouss, all rights reserved. - -------------------------------------------- */ - -.globl hal_write_cr3 -.globl hal_write_cr0 -.globl hal_read_cr2 -.globl hal_read_cr3 -.globl hal_read_cr0 -.globl hal_flush_tlb -.globl hal_invl_tlb - -.text - -hal_invl_tlb: - invlpg (%rcx) - retq - -hal_flush_tlb: - call hal_read_cr3 - mov %rax, %rcx - call hal_write_cr3 - retq - -hal_read_cr3: - movq %cr3, %rax - retq - -hal_read_cr0: - movq %cr0, %rax - retq - -hal_read_cr2: - movq %cr2, %rax - retq - -hal_write_cr3: - movq %rcx, %cr3 - retq - -hal_write_cr0: - movq %rcx, %cr0 - retq diff --git a/dev/kernel/HALKit/AMD64/HalControlRegisterAPI.s b/dev/kernel/HALKit/AMD64/HalControlRegisterAPI.s new file mode 100644 index 00000000..631d1d55 --- /dev/null +++ b/dev/kernel/HALKit/AMD64/HalControlRegisterAPI.s @@ -0,0 +1,45 @@ +/* ------------------------------------------- + + Copyright (C) 2024-2025, Amlal El Mahrouss, all rights reserved. + +------------------------------------------- */ + +.globl hal_write_cr3 +.globl hal_write_cr0 +.globl hal_read_cr2 +.globl hal_read_cr3 +.globl hal_read_cr0 +.globl hal_flush_tlb +.globl hal_invl_tlb + +.text + +hal_invl_tlb: + invlpg (%rcx) + retq + +hal_flush_tlb: + call hal_read_cr3 + mov %rax, %rcx + call hal_write_cr3 + retq + +hal_read_cr3: + movq %cr3, %rax + retq + +hal_read_cr0: + movq %cr0, %rax + retq + +hal_read_cr2: + movq %cr2, %rax + retq + +hal_write_cr3: + movq %rcx, %cr3 + retq + +hal_write_cr0: + movq %rcx, %cr0 + retq diff --git a/dev/kernel/HALKit/AMD64/HalCoreInterruptHandler.cc b/dev/kernel/HALKit/AMD64/HalCoreInterruptHandler.cc new file mode 100644 index 00000000..01456ae5 --- /dev/null +++ b/dev/kernel/HALKit/AMD64/HalCoreInterruptHandler.cc @@ -0,0 +1,159 @@ +/* ------------------------------------------- + + Copyright (C) 2024-2025, Amlal El Mahrouss, all rights reserved. + +------------------------------------------- */ + +#include +#include +#include +#include + +EXTERN_C Kernel::Void idt_handle_breakpoint(Kernel::UIntPtr rip); + +EXTERN_C Kernel::UIntPtr kApicBaseAddress; + +STATIC BOOL kIsRunning = NO; + +/// @brief Notify APIC and PIC that we're done with the interrupt. +/// @note +STATIC void hal_idt_send_eoi(UInt8 vector) { + ((volatile UInt32*) kApicBaseAddress)[0xB0 / 4] = 0; + + if (vector >= kPICCommand && vector <= 0x2F) { + if (vector >= 0x28) { + Kernel::HAL::rt_out8(kPIC2Command, kPICCommand); + } + Kernel::HAL::rt_out8(kPICCommand, kPICCommand); + } +} + +/// @brief Handle GPF fault. +/// @param rsp +EXTERN_C Kernel::Void idt_handle_gpf(Kernel::UIntPtr rsp) { + auto& process = Kernel::UserProcessScheduler::The().TheCurrentProcess(); + process.Leak().Crash(); + + hal_idt_send_eoi(13); + + process.Leak().Signal.SignalArg = rsp; + process.Leak().Signal.SignalID = SIGKILL; + process.Leak().Signal.Status = process.Leak().Status; +} + +/// @brief Handle page fault. +/// @param rsp +EXTERN_C void idt_handle_pf(Kernel::UIntPtr rsp) { + auto& process = Kernel::UserProcessScheduler::The().TheCurrentProcess(); + process.Leak().Crash(); + + hal_idt_send_eoi(14); + + process.Leak().Signal.SignalArg = rsp; + process.Leak().Signal.SignalID = SIGKILL; + process.Leak().Signal.Status = process.Leak().Status; +} + +/// @brief Handle scheduler interrupt. +EXTERN_C void idt_handle_scheduler(Kernel::UIntPtr rsp) { + NE_UNUSED(rsp); + + hal_idt_send_eoi(32); + + while (kIsRunning) + ; + + kIsRunning = YES; + + Kernel::UserProcessHelper::StartScheduling(); + + kIsRunning = NO; +} + +/// @brief Handle math fault. +/// @param rsp +EXTERN_C void idt_handle_math(Kernel::UIntPtr rsp) { + auto& process = Kernel::UserProcessScheduler::The().TheCurrentProcess(); + process.Leak().Crash(); + + hal_idt_send_eoi(8); + + process.Leak().Signal.SignalArg = rsp; + process.Leak().Signal.SignalID = SIGKILL; + process.Leak().Signal.Status = process.Leak().Status; +} + +/// @brief Handle any generic fault. +/// @param rsp +EXTERN_C void idt_handle_generic(Kernel::UIntPtr rsp) { + auto& process = Kernel::UserProcessScheduler::The().TheCurrentProcess(); + process.Leak().Crash(); + + hal_idt_send_eoi(30); + + Kernel::kout << "Kernel: Generic Process Fault.\r"; + + process.Leak().Signal.SignalArg = rsp; + process.Leak().Signal.SignalID = SIGKILL; + process.Leak().Signal.Status = process.Leak().Status; + + Kernel::kout << "Kernel: SIGKILL status.\r"; +} + +EXTERN_C Kernel::Void idt_handle_breakpoint(Kernel::UIntPtr rip) { + auto& process = Kernel::UserProcessScheduler::The().TheCurrentProcess(); + + hal_idt_send_eoi(3); + + process.Leak().Signal.SignalArg = rip; + process.Leak().Signal.SignalID = SIGTRAP; + + process.Leak().Signal.Status = process.Leak().Status; + + process.Leak().Status = Kernel::ProcessStatusKind::kFrozen; +} + +/// @brief Handle #UD fault. +/// @param rsp +EXTERN_C void idt_handle_ud(Kernel::UIntPtr rsp) { + auto& process = Kernel::UserProcessScheduler::The().TheCurrentProcess(); + process.Leak().Crash(); + + hal_idt_send_eoi(6); + + process.Leak().Signal.SignalArg = rsp; + process.Leak().Signal.SignalID = SIGKILL; + process.Leak().Signal.Status = process.Leak().Status; +} + +/// @brief Enter syscall from assembly. +/// @param stack the stack pushed from assembly routine. +/// @return nothing. +EXTERN_C Kernel::Void hal_system_call_enter(Kernel::UIntPtr rcx_syscall_index, + Kernel::UIntPtr rdx_syscall_struct) { + hal_idt_send_eoi(50); + + if (rcx_syscall_index < kSysCalls.Count()) { + if (kSysCalls[rcx_syscall_index].fHooked) { + if (kSysCalls[rcx_syscall_index].fProc) { + (kSysCalls[rcx_syscall_index].fProc)((Kernel::VoidPtr) rdx_syscall_struct); + } + } + } +} + +/// @brief Enter Kernel call from assembly (DDK only). +/// @param stack the stack pushed from assembly routine. +/// @return nothing. +EXTERN_C Kernel::Void hal_kernel_call_enter(Kernel::UIntPtr rcx_kerncall_index, + Kernel::UIntPtr rdx_kerncall_struct) { + hal_idt_send_eoi(51); + + if (rcx_kerncall_index < kKernCalls.Count()) { + if (kKernCalls[rcx_kerncall_index].fHooked) { + if (kKernCalls[rcx_kerncall_index].fProc) { + (kKernCalls[rcx_kerncall_index].fProc)((Kernel::VoidPtr) rdx_kerncall_struct); + } + } + } +} diff --git a/dev/kernel/HALKit/AMD64/HalCoreInterruptHandlerAMD64.cc b/dev/kernel/HALKit/AMD64/HalCoreInterruptHandlerAMD64.cc deleted file mode 100644 index b70cd51f..00000000 --- a/dev/kernel/HALKit/AMD64/HalCoreInterruptHandlerAMD64.cc +++ /dev/null @@ -1,159 +0,0 @@ -/* ------------------------------------------- - - Copyright (C) 2024-2025, Amlal El Mahrouss, all rights reserved. - -------------------------------------------- */ - -#include -#include -#include -#include - -EXTERN_C Kernel::Void idt_handle_breakpoint(Kernel::UIntPtr rip); - -EXTERN_C Kernel::UIntPtr kApicBaseAddress; - -STATIC BOOL kIsRunning = NO; - -/// @brief Notify APIC and PIC that we're done with the interrupt. -/// @note -STATIC void hal_idt_send_eoi(UInt8 vector) { - ((volatile UInt32*) kApicBaseAddress)[0xB0 / 4] = 0; - - if (vector >= kPICCommand && vector <= 0x2F) { - if (vector >= 0x28) { - Kernel::HAL::rt_out8(kPIC2Command, kPICCommand); - } - Kernel::HAL::rt_out8(kPICCommand, kPICCommand); - } -} - -/// @brief Handle GPF fault. -/// @param rsp -EXTERN_C Kernel::Void idt_handle_gpf(Kernel::UIntPtr rsp) { - auto& process = Kernel::UserProcessScheduler::The().TheCurrentProcess(); - process.Leak().Crash(); - - hal_idt_send_eoi(13); - - process.Leak().Signal.SignalArg = rsp; - process.Leak().Signal.SignalID = SIGKILL; - process.Leak().Signal.Status = process.Leak().Status; -} - -/// @brief Handle page fault. -/// @param rsp -EXTERN_C void idt_handle_pf(Kernel::UIntPtr rsp) { - auto& process = Kernel::UserProcessScheduler::The().TheCurrentProcess(); - process.Leak().Crash(); - - hal_idt_send_eoi(14); - - process.Leak().Signal.SignalArg = rsp; - process.Leak().Signal.SignalID = SIGKILL; - process.Leak().Signal.Status = process.Leak().Status; -} - -/// @brief Handle scheduler interrupt. -EXTERN_C void idt_handle_scheduler(Kernel::UIntPtr rsp) { - NE_UNUSED(rsp); - - hal_idt_send_eoi(32); - - while (kIsRunning) - ; - - kIsRunning = YES; - - Kernel::UserProcessHelper::StartScheduling(); - - kIsRunning = NO; -} - -/// @brief Handle math fault. -/// @param rsp -EXTERN_C void idt_handle_math(Kernel::UIntPtr rsp) { - auto& process = Kernel::UserProcessScheduler::The().TheCurrentProcess(); - process.Leak().Crash(); - - hal_idt_send_eoi(8); - - process.Leak().Signal.SignalArg = rsp; - process.Leak().Signal.SignalID = SIGKILL; - process.Leak().Signal.Status = process.Leak().Status; -} - -/// @brief Handle any generic fault. -/// @param rsp -EXTERN_C void idt_handle_generic(Kernel::UIntPtr rsp) { - auto& process = Kernel::UserProcessScheduler::The().TheCurrentProcess(); - process.Leak().Crash(); - - hal_idt_send_eoi(30); - - Kernel::kout << "Kernel: Generic Process Fault.\r"; - - process.Leak().Signal.SignalArg = rsp; - process.Leak().Signal.SignalID = SIGKILL; - process.Leak().Signal.Status = process.Leak().Status; - - Kernel::kout << "Kernel: SIGKILL status.\r"; -} - -EXTERN_C Kernel::Void idt_handle_breakpoint(Kernel::UIntPtr rip) { - auto& process = Kernel::UserProcessScheduler::The().TheCurrentProcess(); - - hal_idt_send_eoi(3); - - process.Leak().Signal.SignalArg = rip; - process.Leak().Signal.SignalID = SIGTRAP; - - process.Leak().Signal.Status = process.Leak().Status; - - process.Leak().Status = Kernel::ProcessStatusKind::kFrozen; -} - -/// @brief Handle #UD fault. -/// @param rsp -EXTERN_C void idt_handle_ud(Kernel::UIntPtr rsp) { - auto& process = Kernel::UserProcessScheduler::The().TheCurrentProcess(); - process.Leak().Crash(); - - hal_idt_send_eoi(6); - - process.Leak().Signal.SignalArg = rsp; - process.Leak().Signal.SignalID = SIGKILL; - process.Leak().Signal.Status = process.Leak().Status; -} - -/// @brief Enter syscall from assembly. -/// @param stack the stack pushed from assembly routine. -/// @return nothing. -EXTERN_C Kernel::Void hal_system_call_enter(Kernel::UIntPtr rcx_syscall_index, - Kernel::UIntPtr rdx_syscall_struct) { - hal_idt_send_eoi(50); - - if (rcx_syscall_index < kSysCalls.Count()) { - if (kSysCalls[rcx_syscall_index].fHooked) { - if (kSysCalls[rcx_syscall_index].fProc) { - (kSysCalls[rcx_syscall_index].fProc)((Kernel::VoidPtr) rdx_syscall_struct); - } - } - } -} - -/// @brief Enter Kernel call from assembly (DDK only). -/// @param stack the stack pushed from assembly routine. -/// @return nothing. -EXTERN_C Kernel::Void hal_kernel_call_enter(Kernel::UIntPtr rcx_kerncall_index, - Kernel::UIntPtr rdx_kerncall_struct) { - hal_idt_send_eoi(51); - - if (rcx_kerncall_index < kKernCalls.Count()) { - if (kKernCalls[rcx_kerncall_index].fHooked) { - if (kKernCalls[rcx_kerncall_index].fProc) { - (kKernCalls[rcx_kerncall_index].fProc)((Kernel::VoidPtr) rdx_kerncall_struct); - } - } - } -} diff --git a/dev/kernel/HALKit/AMD64/HalKernelMain.cc b/dev/kernel/HALKit/AMD64/HalKernelMain.cc index c1558892..edbe058a 100644 --- a/dev/kernel/HALKit/AMD64/HalKernelMain.cc +++ b/dev/kernel/HALKit/AMD64/HalKernelMain.cc @@ -146,17 +146,19 @@ EXTERN_C Kernel::Void hal_real_init(Kernel::Void) noexcept { HAL::mp_init_cores(kHandoverHeader->f_HardwareTables.f_VendorPtr); #ifdef __FSKIT_INCLUDES_HEFS__ - if (HeFS::fs_init_hefs()) { - goto hal_spin_kernel; + if (!HeFS::fs_init_hefs()) { + kout << "HeFS cannot be formated on disk. Aborting\r"; + DBG_TRAP(); } #endif +#ifdef __FSKIT_INCLUDES_NEFS__ if (!NeFS::fs_init_nefs()) { - kout << "NeFS cannot be formated on the disk. Aborting\r"; + kout << "NeFS cannot be formated on disk. Aborting\r"; DBG_TRAP(); } +#endif -hal_spin_kernel: HAL::Register64 idt_reg; idt_reg.Base = reinterpret_cast(kInterruptVectorTable); diff --git a/dev/kernel/HALKit/AMD64/HalPagingMgr.cc b/dev/kernel/HALKit/AMD64/HalPagingMgr.cc new file mode 100644 index 00000000..048cb7c2 --- /dev/null +++ b/dev/kernel/HALKit/AMD64/HalPagingMgr.cc @@ -0,0 +1,164 @@ +/* ------------------------------------------- + + Copyright (C) 2024-2025, Amlal El Mahrouss, all rights reserved. + + File: HalPagingMgr.cc + Purpose: Platform Paging Manager. + +------------------------------------------- */ + +#include +#include + +namespace Kernel::HAL { +namespace Detail { + /// @brief Page Table Entry for AMD64. + struct PTE { + UInt64 Present : 1; + UInt64 Wr : 1; + UInt64 User : 1; + UInt64 Pwt : 1; // Page-level Write-Through + UInt64 Pcd : 1; // Page-level Cache Disable + UInt64 Accessed : 1; + UInt64 Dirty : 1; + UInt64 Pat : 1; // Page Attribute Table (or PS for PDE) + UInt64 Global : 1; + UInt64 Ignored1 : 3; // Available to software + UInt64 PhysicalAddress : 40; // Physical page frame address (bits 12–51) + UInt64 Ignored2 : 7; // More software bits / reserved + UInt64 ProtectionKey : 4; // Optional (if PKU enabled) + UInt64 Reserved : 1; // Usually reserved + UInt64 Nx : 1; // No Execute + }; +} // namespace Detail + +/***********************************************************************************/ +/// \brief Retrieve the page status of a PTE. +/// \param pte Page Table Entry pointer. +/***********************************************************************************/ +STATIC Void mmi_page_status(Detail::PTE* pte) { + NE_UNUSED(pte); + +#ifdef __NE_VERBOSE_BITMAP__ + (Void)(kout << "Flag: " << (pte->Present ? "Present" : "Not Present") << kendl); + (Void)(kout << "Flag: " << (pte->Wr ? "W/R" : "Not W/R") << kendl); + (Void)(kout << "Flag: " << (pte->Nx ? "NX" : "Not NX") << kendl); + (Void)(kout << "Flag: " << pte->User ? "User" : "Not User") << kendl); + (Void)(kout << "Flag: " << (pte->Pcd ? "Not Cached" : "Cached") << kendl); + (Void)(kout << "Flag: " << (pte->Accessed ? "Accessed" : "Not Accessed") << kendl); + (Void)(kout << "Flag: " << (pte->ProtectionKey ? "Protected" : "Not Protected/PKU Disabled") + << kendl); + (Void)(kout << "Physical Address: " << hex_number(pte->PhysicalAddress) << kendl); +#endif +} + +/***********************************************************************************/ +/// @brief Gets a physical address from a virtual address. +/// @param virt a valid virtual address. +/// @return Physical address. +/***********************************************************************************/ +EXTERN_C UIntPtr mm_get_page_addr(VoidPtr virt) { + const UInt64 kVMAddr = (UInt64) virt; + const UInt64 kMask9Bits = 0x1FFULL; + const UInt64 kPageOffsetMask = 0xFFFULL; + + UInt64 cr3 = (UInt64) hal_read_cr3() & ~kPageOffsetMask; + + // Level 4 + auto pml4 = reinterpret_cast(cr3); + UInt64 pml4e = pml4[(kVMAddr >> 39) & kMask9Bits]; + + if (!(pml4e & 1)) return 0; + + // Level 3 + auto pdpt = reinterpret_cast(pml4e & ~kPageOffsetMask); + UInt64 pdpte = pdpt[(kVMAddr >> 30) & kMask9Bits]; + + if (!(pdpte & 1)) return 0; + + // Level 2 + auto pd = reinterpret_cast(pdpte & ~kPageOffsetMask); + UInt64 pde = pd[(kVMAddr >> 21) & kMask9Bits]; + + if (!(pde & 1)) return 0; + + // 1 GiB page support + if (pde & (1 << 7)) { + return (pde & ~((1ULL << 30) - 1)) | (kVMAddr & ((1ULL << 30) - 1)); + } + + // Level 1 + auto pt = reinterpret_cast(pde & ~kPageOffsetMask); + Detail::PTE* pte = (Detail::PTE*) pt[(kVMAddr >> 12) & kMask9Bits]; + + if (!pte->Present) return 0; + + mmi_page_status((Detail::PTE*) pte); + + return (pte->PhysicalAddress << 12) | (kVMAddr & 0xFFF); +} + +/***********************************************************************************/ +/// @brief clflush+mfence helper function. +/***********************************************************************************/ +EXTERN_C Int32 mm_memory_fence(VoidPtr virtual_address) { + if (!virtual_address || !mm_get_page_addr(virtual_address)) return kErrorInvalidData; + + asm volatile("clflush (%0)" : : "r"(virtual_address) : "memory"); + asm volatile("mfence" ::: "memory"); + + return kErrorSuccess; +} + +/***********************************************************************************/ +/// @brief Maps or allocates a page from virtual_address. +/// @param virtual_address a valid virtual address. +/// @param phys_addr point to physical address. +/// @param flags the flags to put on the page. +/// @return Status code of page manipulation process. +/***********************************************************************************/ +EXTERN_C Int32 mm_map_page(VoidPtr virtual_address, VoidPtr physical_address, UInt32 flags) { + if (physical_address == 0) return kErrorInvalidData; + + const UInt64 kVMAddr = (UInt64) virtual_address; + constexpr UInt64 kMask9 = 0x1FF; + constexpr UInt64 kPageMask = 0xFFF; + + UInt64 cr3 = (UIntPtr) hal_read_cr3() & ~kPageMask; + + auto pml4 = reinterpret_cast(cr3); + UInt64 pml4e = pml4[(kVMAddr >> 39) & kMask9]; + + if (!(pml4e & 1)) return kErrorInvalidData; + + UInt64* pdpt = reinterpret_cast(pml4e & ~kPageMask); + UInt64 pdpte = pdpt[(kVMAddr >> 30) & kMask9]; + + if (!(pdpte & 1)) return kErrorInvalidData; + + UInt64* pd = reinterpret_cast(pdpte & ~kPageMask); + UInt64 pde = pd[(kVMAddr >> 21) & kMask9]; + + if (!(pde & 1)) return kErrorInvalidData; + + UInt64* pt = reinterpret_cast(pde & ~kPageMask); + Detail::PTE* pte = (Detail::PTE*) pt[(kVMAddr >> 12) & kMask9]; + + pte->Present = !!(flags & kMMFlagsPresent); + pte->Wr = !!(flags & kMMFlagsWr); + pte->User = !!(flags & kMMFlagsUser); + pte->Nx = !!(flags & kMMFlagsNX); + pte->Pcd = !!(flags & kMMFlagsPCD); + pte->Pwt = !!(flags & kMMFlagsPwt); + + pte->PhysicalAddress = ((UIntPtr) (physical_address)) >> 12; + + hal_invl_tlb(virtual_address); + + mm_memory_fence(virtual_address); + + mmi_page_status(pte); + + return kErrorSuccess; +} +} // namespace Kernel::HAL diff --git a/dev/kernel/HALKit/AMD64/HalPagingMgrAMD64.cc b/dev/kernel/HALKit/AMD64/HalPagingMgrAMD64.cc deleted file mode 100644 index 4681b5e5..00000000 --- a/dev/kernel/HALKit/AMD64/HalPagingMgrAMD64.cc +++ /dev/null @@ -1,164 +0,0 @@ -/* ------------------------------------------- - - Copyright (C) 2024-2025, Amlal El Mahrouss, all rights reserved. - - File: HalPagingMgr.cc - Purpose: Platform Paging Manager. - -------------------------------------------- */ - -#include -#include - -namespace Kernel::HAL { -namespace Detail { - /// @brief Page Table Entry for AMD64. - struct PTE { - UInt64 Present : 1; - UInt64 Wr : 1; - UInt64 User : 1; - UInt64 Pwt : 1; // Page-level Write-Through - UInt64 Pcd : 1; // Page-level Cache Disable - UInt64 Accessed : 1; - UInt64 Dirty : 1; - UInt64 Pat : 1; // Page Attribute Table (or PS for PDE) - UInt64 Global : 1; - UInt64 Ignored1 : 3; // Available to software - UInt64 PhysicalAddress : 40; // Physical page frame address (bits 12–51) - UInt64 Ignored2 : 7; // More software bits / reserved - UInt64 ProtectionKey : 4; // Optional (if PKU enabled) - UInt64 Reserved : 1; // Usually reserved - UInt64 Nx : 1; // No Execute - }; -} // namespace Detail - -/***********************************************************************************/ -/// \brief Retrieve the page status of a PTE. -/// \param pte Page Table Entry pointer. -/***********************************************************************************/ -STATIC Void mmi_page_status(Detail::PTE* pte) { - NE_UNUSED(pte); - -#ifdef __NE_VERBOSE_BITMAP__ - (Void)(kout << "Flag: " << (pte->Present ? "Present" : "Not Present") << kendl); - (Void)(kout << "Flag: " << (pte->Wr ? "W/R" : "Not W/R") << kendl); - (Void)(kout << "Flag: " << (pte->Nx ? "NX" : "Not NX") << kendl); - (Void)(kout << "Flag: " << pte->User ? "User" : "Not User") << kendl); - (Void)(kout << "Flag: " << (pte->Pcd ? "Not Cached" : "Cached") << kendl); - (Void)(kout << "Flag: " << (pte->Accessed ? "Accessed" : "Not Accessed") << kendl); - (Void)(kout << "Flag: " << (pte->ProtectionKey ? "Protected" : "Not Protected/PKU Disabled") - << kendl); - (Void)(kout << "Physical Address: " << hex_number(pte->PhysicalAddress) << kendl); -#endif -} - -/***********************************************************************************/ -/// @brief Gets a physical address from a virtual address. -/// @param virt a valid virtual address. -/// @return Physical address. -/***********************************************************************************/ -UIntPtr mm_get_phys_address(VoidPtr virt) { - const UInt64 kVMAddr = (UInt64) virt; - const UInt64 kMask9Bits = 0x1FFULL; - const UInt64 kPageOffsetMask = 0xFFFULL; - - UInt64 cr3 = (UInt64) hal_read_cr3() & ~kPageOffsetMask; - - // Level 4 - auto pml4 = reinterpret_cast(cr3); - UInt64 pml4e = pml4[(kVMAddr >> 39) & kMask9Bits]; - - if (!(pml4e & 1)) return 0; - - // Level 3 - auto pdpt = reinterpret_cast(pml4e & ~kPageOffsetMask); - UInt64 pdpte = pdpt[(kVMAddr >> 30) & kMask9Bits]; - - if (!(pdpte & 1)) return 0; - - // Level 2 - auto pd = reinterpret_cast(pdpte & ~kPageOffsetMask); - UInt64 pde = pd[(kVMAddr >> 21) & kMask9Bits]; - - if (!(pde & 1)) return 0; - - // 1 GiB page support - if (pde & (1 << 7)) { - return (pde & ~((1ULL << 30) - 1)) | (kVMAddr & ((1ULL << 30) - 1)); - } - - // Level 1 - auto pt = reinterpret_cast(pde & ~kPageOffsetMask); - Detail::PTE* pte = (Detail::PTE*) pt[(kVMAddr >> 12) & kMask9Bits]; - - if (!pte->Present) return 0; - - mmi_page_status((Detail::PTE*) pte); - - return (pte->PhysicalAddress << 12) | (kVMAddr & 0xFFF); -} - -/***********************************************************************************/ -/// @brief clflush+mfence helper function. -/***********************************************************************************/ -EXTERN_C Int32 mm_memory_fence(VoidPtr virtual_address) { - if (!virtual_address || !mm_get_phys_address(virtual_address)) return kErrorInvalidData; - - asm volatile("clflush (%0)" : : "r"(virtual_address) : "memory"); - asm volatile("mfence" ::: "memory"); - - return kErrorSuccess; -} - -/***********************************************************************************/ -/// @brief Maps or allocates a page from virtual_address. -/// @param virtual_address a valid virtual address. -/// @param phys_addr point to physical address. -/// @param flags the flags to put on the page. -/// @return Status code of page manipulation process. -/***********************************************************************************/ -EXTERN_C Int32 mm_map_page(VoidPtr virtual_address, VoidPtr physical_address, UInt32 flags) { - if (physical_address == 0) return kErrorInvalidData; - - const UInt64 kVMAddr = (UInt64) virtual_address; - constexpr UInt64 kMask9 = 0x1FF; - constexpr UInt64 kPageMask = 0xFFF; - - UInt64 cr3 = (UIntPtr) hal_read_cr3() & ~kPageMask; - - auto pml4 = reinterpret_cast(cr3); - UInt64 pml4e = pml4[(kVMAddr >> 39) & kMask9]; - - if (!(pml4e & 1)) return kErrorInvalidData; - - UInt64* pdpt = reinterpret_cast(pml4e & ~kPageMask); - UInt64 pdpte = pdpt[(kVMAddr >> 30) & kMask9]; - - if (!(pdpte & 1)) return kErrorInvalidData; - - UInt64* pd = reinterpret_cast(pdpte & ~kPageMask); - UInt64 pde = pd[(kVMAddr >> 21) & kMask9]; - - if (!(pde & 1)) return kErrorInvalidData; - - UInt64* pt = reinterpret_cast(pde & ~kPageMask); - Detail::PTE* pte = (Detail::PTE*) pt[(kVMAddr >> 12) & kMask9]; - - pte->Present = !!(flags & kMMFlagsPresent); - pte->Wr = !!(flags & kMMFlagsWr); - pte->User = !!(flags & kMMFlagsUser); - pte->Nx = !!(flags & kMMFlagsNX); - pte->Pcd = !!(flags & kMMFlagsPCD); - pte->Pwt = !!(flags & kMMFlagsPwt); - - pte->PhysicalAddress = ((UIntPtr) (physical_address)) >> 12; - - hal_invl_tlb(virtual_address); - - mm_memory_fence(virtual_address); - - mmi_page_status(pte); - - return kErrorSuccess; -} -} // namespace Kernel::HAL diff --git a/dev/kernel/HALKit/AMD64/HalProcessor.cc b/dev/kernel/HALKit/AMD64/HalProcessor.cc new file mode 100644 index 00000000..6ebbea08 --- /dev/null +++ b/dev/kernel/HALKit/AMD64/HalProcessor.cc @@ -0,0 +1,89 @@ +/* ------------------------------------------- + + Copyright (C) 2024-2025, Amlal El Mahrouss, all rights reserved. + + File: HalCPU.cc + Purpose: Platform processor routines. + +------------------------------------------- */ + +#include +#include + +/** + * @file HalCPU.cc + * @brief Common CPU API. + */ + +namespace Kernel::HAL { +inline Bool hal_has_msr() noexcept { + static UInt32 eax, unused, edx; // eax, edx + + __get_cpuid(1, &eax, &unused, &unused, &edx); + + // edx returns the flag for MSR (which is 1 shifted to 5.) + return edx & (1 << 5); +} + +Void hal_get_msr(UInt32 msr, UInt32* lo, UInt32* hi) noexcept { + if (!lo || !hi) return; + asm volatile("rdmsr" : "=a"(*lo), "=d"(*hi) : "c"(msr)); +} + +Void hal_set_msr(UInt32 msr, UInt32 lo, UInt32 hi) noexcept { + asm volatile("wrmsr" : : "a"(lo), "d"(hi), "c"(msr)); +} + +Void lrt_hal_out8(UInt16 port, UInt8 value) { + asm volatile("outb %%al, %1" : : "a"(value), "Nd"(port) : "memory"); +} + +Void lrt_hal_out16(UInt16 port, UInt16 value) { + asm volatile("outw %%ax, %1" : : "a"(value), "Nd"(port) : "memory"); +} + +Void lrt_hal_out32(UInt16 port, UInt32 value) { + asm volatile("outl %%eax, %1" : : "a"(value), "Nd"(port) : "memory"); +} + +UInt8 lrt_hal_in8(UInt16 port) { + UInt8 value = 0UL; + asm volatile("inb %1, %%al" : "=a"(value) : "Nd"(port) : "memory"); + + return value; +} + +UInt16 lrt_hal_in16(UInt16 port) { + UInt16 value = 0UL; + asm volatile("inw %1, %%ax" : "=a"(value) : "Nd"(port) : "memory"); + + return value; +} + +UInt32 lrt_hal_in32(UInt16 port) { + UInt32 value = 0UL; + asm volatile("inl %1, %%eax" : "=a"(value) : "Nd"(port) : "memory"); + + return value; +} + +Void rt_halt() { + asm volatile("hlt"); +} + +Void rt_cli() { + asm volatile("cli"); +} + +Void rt_sti() { + asm volatile("sti"); +} + +Void rt_cld() { + asm volatile("cld"); +} + +Void rt_std() { + asm volatile("std"); +} +} // namespace Kernel::HAL diff --git a/dev/kernel/HALKit/AMD64/HalProcessorAMD64.cc b/dev/kernel/HALKit/AMD64/HalProcessorAMD64.cc deleted file mode 100644 index 2fc18e2f..00000000 --- a/dev/kernel/HALKit/AMD64/HalProcessorAMD64.cc +++ /dev/null @@ -1,80 +0,0 @@ -/* ------------------------------------------- - - Copyright (C) 2024-2025, Amlal El Mahrouss, all rights reserved. - - File: HalCPU.cc - Purpose: Platform processor routines. - -------------------------------------------- */ - -#include -#include - -/** - * @file HalCPU.cc - * @brief Common CPU API. - */ - -namespace Kernel::HAL { -Void hal_get_msr(UInt32 msr, UInt32* lo, UInt32* hi) noexcept { - if (!lo || !hi) return; - asm volatile("rdmsr" : "=a"(*lo), "=d"(*hi) : "c"(msr)); -} - -Void hal_set_msr(UInt32 msr, UInt32 lo, UInt32 hi) noexcept { - asm volatile("wrmsr" : : "a"(lo), "d"(hi), "c"(msr)); -} - -Void lrt_hal_out8(UInt16 port, UInt8 value) { - asm volatile("outb %%al, %1" : : "a"(value), "Nd"(port) : "memory"); -} - -Void lrt_hal_out16(UInt16 port, UInt16 value) { - asm volatile("outw %%ax, %1" : : "a"(value), "Nd"(port) : "memory"); -} - -Void lrt_hal_out32(UInt16 port, UInt32 value) { - asm volatile("outl %%eax, %1" : : "a"(value), "Nd"(port) : "memory"); -} - -UInt8 lrt_hal_in8(UInt16 port) { - UInt8 value = 0UL; - asm volatile("inb %1, %%al" : "=a"(value) : "Nd"(port) : "memory"); - - return value; -} - -UInt16 lrt_hal_in16(UInt16 port) { - UInt16 value = 0UL; - asm volatile("inw %1, %%ax" : "=a"(value) : "Nd"(port) : "memory"); - - return value; -} - -UInt32 lrt_hal_in32(UInt16 port) { - UInt32 value = 0UL; - asm volatile("inl %1, %%eax" : "=a"(value) : "Nd"(port) : "memory"); - - return value; -} - -Void rt_halt() { - asm volatile("hlt"); -} - -Void rt_cli() { - asm volatile("cli"); -} - -Void rt_sti() { - asm volatile("sti"); -} - -Void rt_cld() { - asm volatile("cld"); -} - -Void rt_std() { - asm volatile("std"); -} -} // namespace Kernel::HAL diff --git a/dev/kernel/HALKit/AMD64/HalSchedulerCorePrimitives.cc b/dev/kernel/HALKit/AMD64/HalSchedulerCorePrimitives.cc new file mode 100644 index 00000000..0c468e14 --- /dev/null +++ b/dev/kernel/HALKit/AMD64/HalSchedulerCorePrimitives.cc @@ -0,0 +1,47 @@ +/* ------------------------------------------- + + Copyright (C) 2024-2025, Amlal El Mahrouss, all rights reserved. + +------------------------------------------- */ + +#include +#include + +namespace Kernel { +/***********************************************************************************/ +/// @brief Unimplemented function (crashes by default) +/// @param +/***********************************************************************************/ + +EXTERN_C Void __zka_pure_call(USER_PROCESS* process) { + if (process) process->Crash(); +} + +/***********************************************************************************/ +/// @brief Validate user stack. +/// @param stack_ptr the frame pointer. +/***********************************************************************************/ + +EXTERN_C Bool hal_check_stack(HAL::StackFramePtr stack_ptr) { + if (!stack_ptr) return No; + + return stack_ptr->SP != 0 && stack_ptr->IP != 0; +} + +/// @brief Wakes up thread. +/// Wakes up thread from the hang state. +Void mp_wakeup_thread(HAL::StackFrame* stack) { + NE_UNUSED(stack); + Kernel::UserProcessHelper::StartScheduling(); +} + +/// @brief makes the thread sleep on a loop. +/// hooks and hangs thread to prevent code from executing. +Void mp_hang_thread(HAL::StackFrame* stack) { + NE_UNUSED(stack); + + while (Yes) { + /* Nothing to do, code is spinning */ + } +} +} // namespace Kernel diff --git a/dev/kernel/HALKit/AMD64/HalSchedulerCorePrimitivesAMD64.cc b/dev/kernel/HALKit/AMD64/HalSchedulerCorePrimitivesAMD64.cc deleted file mode 100644 index 0c468e14..00000000 --- a/dev/kernel/HALKit/AMD64/HalSchedulerCorePrimitivesAMD64.cc +++ /dev/null @@ -1,47 +0,0 @@ -/* ------------------------------------------- - - Copyright (C) 2024-2025, Amlal El Mahrouss, all rights reserved. - -------------------------------------------- */ - -#include -#include - -namespace Kernel { -/***********************************************************************************/ -/// @brief Unimplemented function (crashes by default) -/// @param -/***********************************************************************************/ - -EXTERN_C Void __zka_pure_call(USER_PROCESS* process) { - if (process) process->Crash(); -} - -/***********************************************************************************/ -/// @brief Validate user stack. -/// @param stack_ptr the frame pointer. -/***********************************************************************************/ - -EXTERN_C Bool hal_check_stack(HAL::StackFramePtr stack_ptr) { - if (!stack_ptr) return No; - - return stack_ptr->SP != 0 && stack_ptr->IP != 0; -} - -/// @brief Wakes up thread. -/// Wakes up thread from the hang state. -Void mp_wakeup_thread(HAL::StackFrame* stack) { - NE_UNUSED(stack); - Kernel::UserProcessHelper::StartScheduling(); -} - -/// @brief makes the thread sleep on a loop. -/// hooks and hangs thread to prevent code from executing. -Void mp_hang_thread(HAL::StackFrame* stack) { - NE_UNUSED(stack); - - while (Yes) { - /* Nothing to do, code is spinning */ - } -} -} // namespace Kernel diff --git a/dev/kernel/HALKit/AMD64/HalTimer.cc b/dev/kernel/HALKit/AMD64/HalTimer.cc new file mode 100644 index 00000000..13573880 --- /dev/null +++ b/dev/kernel/HALKit/AMD64/HalTimer.cc @@ -0,0 +1,97 @@ +/* ------------------------------------------- + + Copyright (C) 2024-2025, Amlal El Mahrouss, all rights reserved. + + File: HalTimer.cc + Purpose: HAL timer + + Revision History: + + 07/07/24: Added file (amlel) + +------------------------------------------- */ + +#include +#include +#include + +// timer slot 0 + +#define kHPETSignature ("HPET") + +#define kHPETCounterRegValue (0x00) +#define kHPETConfigRegValue (0x20) +#define kHPETCompRegValue (0x24) +#define kHPETInterruptRegValue (0x2C) + +///! BUGS: 0 +///! @file HalTimer.cc +///! @brief Hardware Timer (HPET) + +namespace Kernel::Detail { +struct HPET_BLOCK : public Kernel::SDT { + Kernel::UInt8 hardware_rev_id; + Kernel::UInt8 comparator_count : 5; + Kernel::UInt8 counter_size : 1; + Kernel::UInt8 reserved : 1; + Kernel::UInt8 legacy_replacement : 1; + Kernel::UInt16 pci_vendor_id; + ACPI_ADDRESS address; + Kernel::UInt8 hpet_number; + Kernel::UInt16 minimum_tick; + Kernel::UInt8 page_protection; +} PACKED; +} // namespace Kernel::Detail + +using namespace Kernel; + +HardwareTimer::HardwareTimer(UInt64 ms) : fWaitFor(ms) { + auto power = PowerFactoryInterface(kHandoverHeader->f_HardwareTables.f_VendorPtr); + + auto hpet = (Detail::HPET_BLOCK*) power.Find(kHPETSignature).Leak().Leak(); + MUST_PASS(hpet); + + fDigitalTimer = (UInt8*) hpet->address.Address; + + if (hpet->page_protection) { + HAL::mm_map_page((VoidPtr) fDigitalTimer, (VoidPtr) fDigitalTimer, + HAL::kMMFlagsWr | HAL::kMMFlagsPCD | HAL::kMMFlagsPwt); + } + + // if not enabled yet. + if (!(*((volatile UInt64*) ((UInt8*) fDigitalTimer + kHPETConfigRegValue)) & (1 << 0))) { + *((volatile UInt64*) ((UInt8*) fDigitalTimer + kHPETConfigRegValue)) = + *((volatile UInt64*) ((UInt8*) fDigitalTimer + kHPETConfigRegValue)) | + (1 << 0); // enable timer + *((volatile UInt64*) ((UInt8*) fDigitalTimer + kHPETConfigRegValue)) = + *((volatile UInt64*) ((UInt8*) fDigitalTimer + kHPETConfigRegValue)) | + (1 << 3); // one shot conf + } +} + +HardwareTimer::~HardwareTimer() { + fDigitalTimer = nullptr; + fWaitFor = 0; +} + +/***********************************************************************************/ +/// @brief Wait for the timer to stop spinning. +/***********************************************************************************/ + +BOOL HardwareTimer::Wait() noexcept { + if (fWaitFor < 1) return NO; + + UInt64 hpet_cap = *((volatile UInt64*) (fDigitalTimer + kHPETCounterRegValue)); + UInt64 femtoseconds_per_tick = (hpet_cap >> 32); + + if (femtoseconds_per_tick == 0) return NO; + + volatile UInt64* timer = (volatile UInt64*) (fDigitalTimer + kHPETCounterRegValue); + + UInt64 now = *timer; + UInt64 prev = now + (fWaitFor / femtoseconds_per_tick); + + while (*timer < (prev)) asm volatile("pause"); + + return YES; +} diff --git a/dev/kernel/HALKit/AMD64/HalTimerAMD64.cc b/dev/kernel/HALKit/AMD64/HalTimerAMD64.cc deleted file mode 100644 index 13573880..00000000 --- a/dev/kernel/HALKit/AMD64/HalTimerAMD64.cc +++ /dev/null @@ -1,97 +0,0 @@ -/* ------------------------------------------- - - Copyright (C) 2024-2025, Amlal El Mahrouss, all rights reserved. - - File: HalTimer.cc - Purpose: HAL timer - - Revision History: - - 07/07/24: Added file (amlel) - -------------------------------------------- */ - -#include -#include -#include - -// timer slot 0 - -#define kHPETSignature ("HPET") - -#define kHPETCounterRegValue (0x00) -#define kHPETConfigRegValue (0x20) -#define kHPETCompRegValue (0x24) -#define kHPETInterruptRegValue (0x2C) - -///! BUGS: 0 -///! @file HalTimer.cc -///! @brief Hardware Timer (HPET) - -namespace Kernel::Detail { -struct HPET_BLOCK : public Kernel::SDT { - Kernel::UInt8 hardware_rev_id; - Kernel::UInt8 comparator_count : 5; - Kernel::UInt8 counter_size : 1; - Kernel::UInt8 reserved : 1; - Kernel::UInt8 legacy_replacement : 1; - Kernel::UInt16 pci_vendor_id; - ACPI_ADDRESS address; - Kernel::UInt8 hpet_number; - Kernel::UInt16 minimum_tick; - Kernel::UInt8 page_protection; -} PACKED; -} // namespace Kernel::Detail - -using namespace Kernel; - -HardwareTimer::HardwareTimer(UInt64 ms) : fWaitFor(ms) { - auto power = PowerFactoryInterface(kHandoverHeader->f_HardwareTables.f_VendorPtr); - - auto hpet = (Detail::HPET_BLOCK*) power.Find(kHPETSignature).Leak().Leak(); - MUST_PASS(hpet); - - fDigitalTimer = (UInt8*) hpet->address.Address; - - if (hpet->page_protection) { - HAL::mm_map_page((VoidPtr) fDigitalTimer, (VoidPtr) fDigitalTimer, - HAL::kMMFlagsWr | HAL::kMMFlagsPCD | HAL::kMMFlagsPwt); - } - - // if not enabled yet. - if (!(*((volatile UInt64*) ((UInt8*) fDigitalTimer + kHPETConfigRegValue)) & (1 << 0))) { - *((volatile UInt64*) ((UInt8*) fDigitalTimer + kHPETConfigRegValue)) = - *((volatile UInt64*) ((UInt8*) fDigitalTimer + kHPETConfigRegValue)) | - (1 << 0); // enable timer - *((volatile UInt64*) ((UInt8*) fDigitalTimer + kHPETConfigRegValue)) = - *((volatile UInt64*) ((UInt8*) fDigitalTimer + kHPETConfigRegValue)) | - (1 << 3); // one shot conf - } -} - -HardwareTimer::~HardwareTimer() { - fDigitalTimer = nullptr; - fWaitFor = 0; -} - -/***********************************************************************************/ -/// @brief Wait for the timer to stop spinning. -/***********************************************************************************/ - -BOOL HardwareTimer::Wait() noexcept { - if (fWaitFor < 1) return NO; - - UInt64 hpet_cap = *((volatile UInt64*) (fDigitalTimer + kHPETCounterRegValue)); - UInt64 femtoseconds_per_tick = (hpet_cap >> 32); - - if (femtoseconds_per_tick == 0) return NO; - - volatile UInt64* timer = (volatile UInt64*) (fDigitalTimer + kHPETCounterRegValue); - - UInt64 now = *timer; - UInt64 prev = now + (fWaitFor / femtoseconds_per_tick); - - while (*timer < (prev)) asm volatile("pause"); - - return YES; -} diff --git a/dev/kernel/HALKit/AMD64/HalUtilsAPI.asm b/dev/kernel/HALKit/AMD64/HalUtilsAPI.asm index ab639992..11336229 100644 --- a/dev/kernel/HALKit/AMD64/HalUtilsAPI.asm +++ b/dev/kernel/HALKit/AMD64/HalUtilsAPI.asm @@ -22,5 +22,3 @@ rt_install_tib: ret ;; //////////////////////////////////////////////////// ;; - -[extern kApicMadtAddressesCount] diff --git a/dev/kernel/HALKit/AMD64/Network/Generic+Basic+RTL8139.cc b/dev/kernel/HALKit/AMD64/Network/Generic+Basic+RTL8139.cc index 7c611c26..3ccbfa24 100644 --- a/dev/kernel/HALKit/AMD64/Network/Generic+Basic+RTL8139.cc +++ b/dev/kernel/HALKit/AMD64/Network/Generic+Basic+RTL8139.cc @@ -79,7 +79,7 @@ EXTERN_C void rtl_rtl8139_interrupt_handler() { // While we receive data. while ((rt_in8(kRTLIOBase + 0x37) & 0x01) == 0) { // We grab an offset from the RX buffer. - UInt32 offset = kRXOffset % kRXBufferSize; + UInt32 offset = kRXOffset % kRXBufferSize; // If the offset is too high, we reset it. if (offset >= (kRXBufferSize - 16)) { diff --git a/dev/kernel/HALKit/AMD64/Processor.h b/dev/kernel/HALKit/AMD64/Processor.h index 5a70b465..80dc7a1d 100644 --- a/dev/kernel/HALKit/AMD64/Processor.h +++ b/dev/kernel/HALKit/AMD64/Processor.h @@ -174,16 +174,7 @@ Void mp_init_cores(VoidPtr vendor_ptr) noexcept; /// @retval true it does exists. /// @retval false it doesn't. /***********************************************************************************/ -inline Bool hal_has_msr() noexcept { - static UInt32 eax, unused, edx; // eax, edx - - __get_cpuid(1, &eax, &unused, &unused, &edx); - - // edx returns the flag for MSR (which is 1 shifted to 5.) - return edx & (1 << 5); -} - -UIntPtr mm_get_phys_address(VoidPtr virtual_address); +Bool hal_has_msr() noexcept; /***********************************************************************************/ /// @brief Get Model specific register inside core. @@ -271,6 +262,8 @@ EXTERN_C Void rt_sti(); EXTERN_C Void rt_cld(); EXTERN_C Void rt_std(); +EXTERN_C UIntPtr mm_get_page_addr(VoidPtr virtual_address); + EXTERN_C Int32 mm_memory_fence(VoidPtr virtual_address); } // namespace Kernel::HAL diff --git a/dev/kernel/HALKit/AMD64/Storage/AHCI+Generic.cc b/dev/kernel/HALKit/AMD64/Storage/AHCI+Generic.cc index b530a730..b30bfc32 100644 --- a/dev/kernel/HALKit/AMD64/Storage/AHCI+Generic.cc +++ b/dev/kernel/HALKit/AMD64/Storage/AHCI+Generic.cc @@ -359,7 +359,7 @@ STATIC Bool drv_init_command_structures_ahci() { return NO; } - UIntPtr clb_phys = HAL::mm_get_phys_address(clb_mem); + UIntPtr clb_phys = HAL::mm_get_page_addr(clb_mem); kSATAHba->Ports[kSATAIndex].Clb = (UInt32) (clb_phys & 0xFFFFFFFF); kSATAHba->Ports[kSATAIndex].Clbu = (UInt32) (clb_phys >> 32); @@ -379,7 +379,7 @@ STATIC Bool drv_init_command_structures_ahci() { return NO; } - UIntPtr ct_phys = HAL::mm_get_phys_address(ct_mem); + UIntPtr ct_phys = HAL::mm_get_page_addr(ct_mem); header[i].Ctba = (UInt32) (ct_phys & 0xFFFFFFFF); header[i].Ctbau = (UInt32) (ct_phys >> 32); diff --git a/dev/kernel/HALKit/ARM64/HalPagingMgr.cc b/dev/kernel/HALKit/ARM64/HalPagingMgr.cc new file mode 100644 index 00000000..faad6778 --- /dev/null +++ b/dev/kernel/HALKit/ARM64/HalPagingMgr.cc @@ -0,0 +1,28 @@ +/* ------------------------------------------- + + Copyright (C) 2024-2025, Amlal El Mahrouss, all rights reserved. + + File: HalPagingMgr.cc + Purpose: Platform Paging Manager. + +------------------------------------------- */ + +#include +#include + +namespace Kernel::HAL { +typedef UInt32 PageTableIndex; + +/// @brief Maps or allocates a page from virtual_address. +/// @param virtual_address a valid virtual address. +/// @param phys_addr point to physical address. +/// @param flags the flags to put on the page. +/// @return Status code of page manipulation process. +EXTERN_C Int32 mm_map_page(VoidPtr virtual_address, VoidPtr physical_address, UInt32 flags) { + if (!virtual_address || !flags) return kErrorInvalidData; + + NE_UNUSED(physical_address); + + return kErrorSuccess; +} +} // namespace Kernel::HAL diff --git a/dev/kernel/HALKit/ARM64/HalPagingMgrARM64.cc b/dev/kernel/HALKit/ARM64/HalPagingMgrARM64.cc deleted file mode 100644 index faad6778..00000000 --- a/dev/kernel/HALKit/ARM64/HalPagingMgrARM64.cc +++ /dev/null @@ -1,28 +0,0 @@ -/* ------------------------------------------- - - Copyright (C) 2024-2025, Amlal El Mahrouss, all rights reserved. - - File: HalPagingMgr.cc - Purpose: Platform Paging Manager. - -------------------------------------------- */ - -#include -#include - -namespace Kernel::HAL { -typedef UInt32 PageTableIndex; - -/// @brief Maps or allocates a page from virtual_address. -/// @param virtual_address a valid virtual address. -/// @param phys_addr point to physical address. -/// @param flags the flags to put on the page. -/// @return Status code of page manipulation process. -EXTERN_C Int32 mm_map_page(VoidPtr virtual_address, VoidPtr physical_address, UInt32 flags) { - if (!virtual_address || !flags) return kErrorInvalidData; - - NE_UNUSED(physical_address); - - return kErrorSuccess; -} -} // namespace Kernel::HAL diff --git a/dev/kernel/HALKit/ARM64/HalSchedulerCore.cc b/dev/kernel/HALKit/ARM64/HalSchedulerCore.cc new file mode 100644 index 00000000..b3f1b62a --- /dev/null +++ b/dev/kernel/HALKit/ARM64/HalSchedulerCore.cc @@ -0,0 +1,21 @@ +/* ------------------------------------------- + + Copyright (C) 2024-2025, Amlal El Mahrouss, all rights reserved. + +------------------------------------------- */ + +#include + +namespace Kernel { +/// @brief Wakes up thread. +/// Wakes up thread from the hang state. +Void mp_wakeup_thread(HAL::StackFrame* stack) { + NE_UNUSED(stack); +} + +/// @brief makes the thread sleep on a loop. +/// hooks and hangs thread to prevent code from executing. +Void mp_hang_thread(HAL::StackFrame* stack) { + NE_UNUSED(stack); +} +} // namespace Kernel diff --git a/dev/kernel/HALKit/ARM64/HalSchedulerCoreARM64.cc b/dev/kernel/HALKit/ARM64/HalSchedulerCoreARM64.cc deleted file mode 100644 index b3f1b62a..00000000 --- a/dev/kernel/HALKit/ARM64/HalSchedulerCoreARM64.cc +++ /dev/null @@ -1,21 +0,0 @@ -/* ------------------------------------------- - - Copyright (C) 2024-2025, Amlal El Mahrouss, all rights reserved. - -------------------------------------------- */ - -#include - -namespace Kernel { -/// @brief Wakes up thread. -/// Wakes up thread from the hang state. -Void mp_wakeup_thread(HAL::StackFrame* stack) { - NE_UNUSED(stack); -} - -/// @brief makes the thread sleep on a loop. -/// hooks and hangs thread to prevent code from executing. -Void mp_hang_thread(HAL::StackFrame* stack) { - NE_UNUSED(stack); -} -} // namespace Kernel diff --git a/dev/kernel/HALKit/ARM64/HalSchedulerCorePrimitives.cc b/dev/kernel/HALKit/ARM64/HalSchedulerCorePrimitives.cc new file mode 100644 index 00000000..ee286639 --- /dev/null +++ b/dev/kernel/HALKit/ARM64/HalSchedulerCorePrimitives.cc @@ -0,0 +1,30 @@ +/* ------------------------------------------- + + Copyright (C) 2024-2025, Amlal El Mahrouss, all rights reserved. + +------------------------------------------- */ + +#include +#include + +namespace Kernel { +/***********************************************************************************/ +/// @brief Unimplemented function (crashes by default) +/// @param void +/***********************************************************************************/ + +EXTERN_C Void __zka_pure_call(USER_PROCESS* process) { + if (process) process->Crash(); +} + +/***********************************************************************************/ +/// @brief Validate user stack. +/// @param stack_ptr the frame pointer. +/***********************************************************************************/ + +EXTERN_C Bool hal_check_stack(HAL::StackFramePtr stack_ptr) { + if (!stack_ptr) return No; + + return stack_ptr->SP != 0 && stack_ptr->IP != 0; +} +} // namespace Kernel diff --git a/dev/kernel/HALKit/ARM64/HalSchedulerCorePrimitivesARM64.cc b/dev/kernel/HALKit/ARM64/HalSchedulerCorePrimitivesARM64.cc deleted file mode 100644 index ee286639..00000000 --- a/dev/kernel/HALKit/ARM64/HalSchedulerCorePrimitivesARM64.cc +++ /dev/null @@ -1,30 +0,0 @@ -/* ------------------------------------------- - - Copyright (C) 2024-2025, Amlal El Mahrouss, all rights reserved. - -------------------------------------------- */ - -#include -#include - -namespace Kernel { -/***********************************************************************************/ -/// @brief Unimplemented function (crashes by default) -/// @param void -/***********************************************************************************/ - -EXTERN_C Void __zka_pure_call(USER_PROCESS* process) { - if (process) process->Crash(); -} - -/***********************************************************************************/ -/// @brief Validate user stack. -/// @param stack_ptr the frame pointer. -/***********************************************************************************/ - -EXTERN_C Bool hal_check_stack(HAL::StackFramePtr stack_ptr) { - if (!stack_ptr) return No; - - return stack_ptr->SP != 0 && stack_ptr->IP != 0; -} -} // namespace Kernel diff --git a/dev/kernel/HALKit/ARM64/HalTimer.cc b/dev/kernel/HALKit/ARM64/HalTimer.cc new file mode 100644 index 00000000..2a595f11 --- /dev/null +++ b/dev/kernel/HALKit/ARM64/HalTimer.cc @@ -0,0 +1,15 @@ +/* ------------------------------------------- + + Copyright (C) 2024-2025, Amlal El Mahrouss, all rights reserved. + + File: HalTimer.cc + Purpose: HAL timer + + Revision History: + + 07/07/24: Added file (amlel) + +------------------------------------------- */ + +#include +#include \ No newline at end of file diff --git a/dev/kernel/HALKit/ARM64/HalTimerARM64.cc b/dev/kernel/HALKit/ARM64/HalTimerARM64.cc deleted file mode 100644 index 2a595f11..00000000 --- a/dev/kernel/HALKit/ARM64/HalTimerARM64.cc +++ /dev/null @@ -1,15 +0,0 @@ -/* ------------------------------------------- - - Copyright (C) 2024-2025, Amlal El Mahrouss, all rights reserved. - - File: HalTimer.cc - Purpose: HAL timer - - Revision History: - - 07/07/24: Added file (amlel) - -------------------------------------------- */ - -#include -#include \ No newline at end of file diff --git a/dev/kernel/HALKit/ARM64/Processor.h b/dev/kernel/HALKit/ARM64/Processor.h index 38669b2f..068b798d 100644 --- a/dev/kernel/HALKit/ARM64/Processor.h +++ b/dev/kernel/HALKit/ARM64/Processor.h @@ -38,7 +38,7 @@ enum { /// @return Status code of page manip. EXTERN_C Int32 mm_map_page(VoidPtr virtual_address, VoidPtr physical_address, UInt32 flags); -EXTERN_C UIntPtr mm_get_phys_address(VoidPtr virtual_address); +EXTERN_C UIntPtr mm_get_page_addr(VoidPtr virtual_address); typedef UIntPtr Reg; typedef Register64 Register; diff --git a/dev/kernel/KernelKit/KPC.h b/dev/kernel/KernelKit/KPC.h index 944c8efc..811d7f5d 100644 --- a/dev/kernel/KernelKit/KPC.h +++ b/dev/kernel/KernelKit/KPC.h @@ -64,7 +64,8 @@ inline constexpr KPCError kErrorUnrecoverableDisk = 63; inline constexpr KPCError kErrorFileLocked = 64; inline constexpr KPCError kErrorDiskIsTooTiny = 65; /// Kernel errors. -inline constexpr KPCError kErrorDmaExhausted = 101; +inline constexpr KPCError kErrorDmaExhausted = 101; +inline constexpr KPCError kErrorOutOfBitMapMemory = 102; /// Generic errors. inline constexpr KPCError kErrorUnimplemented = -1; diff --git a/dev/kernel/KernelKit/LockDelegate.h b/dev/kernel/KernelKit/LockDelegate.h index a8162897..b5977c92 100644 --- a/dev/kernel/KernelKit/LockDelegate.h +++ b/dev/kernel/KernelKit/LockDelegate.h @@ -11,8 +11,8 @@ namespace Kernel { enum { - kLockInvalid, - kLockDone = 200, + kLockInvalid = 0, + kLockDone = 200, kLockTimedOut, kLockCount = 3, }; diff --git a/dev/kernel/KernelKit/ZXD.h b/dev/kernel/KernelKit/ZXD.h index 2c5a33c4..10af568b 100644 --- a/dev/kernel/KernelKit/ZXD.h +++ b/dev/kernel/KernelKit/ZXD.h @@ -17,25 +17,25 @@ struct ZXD_STUB_HEADER; /// @brief ZXD executable header /// @details This header is used to identify ZXD executable files. struct ZXD_EXEC_HEADER { - UInt32 fMagic; - UInt32 fVersion; - UInt32 fFlags; - UInt32 fHdrSize; - UInt32 fCRC32; - UInt32 fAssigneeSignature; - UInt32 fIssuerSingature; + UInt32 fMagic; + UInt32 fVersion; + UInt32 fFlags; + UInt32 fHdrSize; + UInt32 fCRC32; + UInt32 fAssigneeSignature; + UInt32 fIssuerSingature; UIntPtr fExecOffset; - SizeT fExecSize; + SizeT fExecSize; UIntPtr fStubOffset; - SizeT fStubSize; - SizeT fStubAlign; - SizeT fStubCount; + SizeT fStubSize; + SizeT fStubAlign; + SizeT fStubCount; }; /// @brief ZXD stub header /// @details This header is used to identify ZXD stub files. It contains the size of the stub, the /// offset of the stub, and the CRC32 checksum of the stub. -struct ZXD_STUB_HEADER : public ZXD_EXEC_HEADER { +struct ZXD_STUB_HEADER { UInt32 fStubSize; UInt32 fStubOffset; UInt32 fStubCRC32; diff --git a/dev/kernel/amd64-ci.make b/dev/kernel/amd64-ci.make index 38021901..c728b29c 100644 --- a/dev/kernel/amd64-ci.make +++ b/dev/kernel/amd64-ci.make @@ -35,7 +35,7 @@ LDFLAGS = -e hal_init_platform --subsystem=17 --image-base 0x4000000 LDOBJ = obj/*.obj # This file is the Kernel, responsible of task, memory, driver, sci, disk and device management. -KERNEL_IMG = krnl.efi +KERNEL_IMG = ne_kernel .PHONY: error error: diff --git a/dev/kernel/amd64-desktop.make b/dev/kernel/amd64-desktop.make index ae2307fd..49593101 100644 --- a/dev/kernel/amd64-desktop.make +++ b/dev/kernel/amd64-desktop.make @@ -37,7 +37,7 @@ LDFLAGS = -e hal_init_platform --subsystem=17 --image-base 0x10000000 LDOBJ = obj/*.obj # This file is the Kernel, responsible of task, memory, driver, sci, disk and device management. -KERNEL_IMG = krnl.efi +KERNEL_IMG = ne_kernel .PHONY: error error: diff --git a/dev/kernel/arm64-desktop.make b/dev/kernel/arm64-desktop.make index 31d8f49e..423391af 100644 --- a/dev/kernel/arm64-desktop.make +++ b/dev/kernel/arm64-desktop.make @@ -23,7 +23,7 @@ LDFLAGS = -subsystem:efi_application -entry:hal_init_platform /nodefaultlib LDOBJ = obj/*.obj # This file is the Kernel, responsible of task management and memory. -KERNEL = krnl.efi +KERNEL = ne_kernel .PHONY: error error: diff --git a/dev/kernel/kernel_rsrc.rsrc b/dev/kernel/kernel_rsrc.rsrc index 8d0093e4..5b1cb14f 100644 --- a/dev/kernel/kernel_rsrc.rsrc +++ b/dev/kernel/kernel_rsrc.rsrc @@ -13,7 +13,7 @@ BEGIN VALUE "FileVersion", KERNEL_VERSION VALUE "InternalName", "krnl" VALUE "LegalCopyright", "(c) 2024-2025 Amlal El Mahrouss, all rights reserved." - VALUE "OriginalFilename", "krnl.efi" + VALUE "OriginalFilename", "ne_kernel" VALUE "ProductName", "NeKernel" VALUE "ProductVersion", KERNEL_VERSION END diff --git a/dev/kernel/src/BitMapMgr.cc b/dev/kernel/src/BitMapMgr.cc index 4301ce5b..df678d41 100644 --- a/dev/kernel/src/BitMapMgr.cc +++ b/dev/kernel/src/BitMapMgr.cc @@ -22,6 +22,8 @@ namespace Kernel { namespace HAL { namespace Detail { + STATIC SizeT kBitMapCursor = 0UL; + /***********************************************************************************/ /// \brief Proxy Interface to manage a bitmap allocator. /***********************************************************************************/ @@ -47,6 +49,8 @@ namespace HAL { UIntPtr* ptr_bit_set = reinterpret_cast(page_ptr); + kBitMapCursor += ptr_bit_set[kBitMapSizeIdx]; + ptr_bit_set[kBitMapMagIdx] = kBitMapMagic; ptr_bit_set[kBitMapUsedIdx] = No; @@ -59,7 +63,6 @@ namespace HAL { UInt32 flags = kMMFlagsPresent; if (wr) flags |= kMMFlagsWr; - if (user) flags |= kMMFlagsUser; return flags; @@ -77,11 +80,18 @@ namespace HAL { auto FindBitMap(VoidPtr base_ptr, SizeT size, Bool wr, Bool user, SizeT pad) -> VoidPtr { if (!size) return nullptr; + if (kBitMapCursor > kKernelBitMpSize) { + err_global_get() = kErrorOutOfBitMapMemory; + + (Void)(kout << "Bitmap limit reached, can't allocate more bitmaps." << kendl); + return nullptr; + } + VoidPtr base = reinterpret_cast((UIntPtr) base_ptr); MUST_PASS(base); - static SizeT biggest = 0UL; + STATIC SizeT biggest = 0UL; while (YES) { UIntPtr* ptr_bit_set = reinterpret_cast(base); @@ -99,6 +109,8 @@ namespace HAL { if (biggest < (size + pad)) biggest = size + pad; + kBitMapCursor += size + pad; + return (VoidPtr) ptr_bit_set; } } else if (ptr_bit_set[kBitMapMagIdx] != kBitMapMagic) { @@ -113,6 +125,8 @@ namespace HAL { if (biggest < (size + pad)) biggest = (size + pad); + kBitMapCursor += size + pad; + return (VoidPtr) ptr_bit_set; } diff --git a/dev/kernel/src/FS/HeFS+FileSystemParser.cc b/dev/kernel/src/FS/HeFS+FileSystemParser.cc index a18abaf8..893f43ef 100644 --- a/dev/kernel/src/FS/HeFS+FileSystemParser.cc +++ b/dev/kernel/src/FS/HeFS+FileSystemParser.cc @@ -758,9 +758,8 @@ _Output Bool HeFileSystemParser::Format(_Input _Output DriveTrait* mnt, _Input c } if (drv_std_get_size() < kHeFSMinimumDiskSize) { - (Void)(kout << "HeFS requires at least 128 GiB of free space." << kendl); - err_global_get() = kErrorDisk; - return NO; + (Void)(kout << "HeFS recommends at least 128 GiB of free space." << kendl); + (Void)(kout << "The OS will still try to format a HeFS disk here." << kendl); } HEFS_BOOT_NODE* boot = (HEFS_BOOT_NODE*) RTL_ALLOCA(sizeof(HEFS_BOOT_NODE)); diff --git a/dev/kernel/src/HeapMgr.cc b/dev/kernel/src/HeapMgr.cc index 5280bcc3..2fdfe748 100644 --- a/dev/kernel/src/HeapMgr.cc +++ b/dev/kernel/src/HeapMgr.cc @@ -25,8 +25,8 @@ //! @file HeapMgr.cc //! @brief Heap system that serves as the main memory manager. -#define kMemoryMgrMagic (0xD4D75) -#define kMemoryMgrAlignSz (4U) +#define kHeapMgrMagic (0xD4D75) +#define kHeapMgrAlignSz (4U) namespace Kernel { /// @brief Implementation details. @@ -68,7 +68,7 @@ namespace Detail { UInt32 fPad; /// @brief Padding bytes for header. - UInt8 fPadding[kMemoryMgrAlignSz]; + UInt8 fPadding[kHeapMgrAlignSz]; }; /// @brief Check for heap address validity. @@ -112,7 +112,7 @@ _Output VoidPtr mm_alloc_ptr(SizeT sz, Bool wr, Bool user, SizeT pad_amount) { sizeof(Detail::MM_INFORMATION_BLOCK)); heap_info_ptr->fSize = sz_fix; - heap_info_ptr->fMagic = kMemoryMgrMagic; + heap_info_ptr->fMagic = kHeapMgrMagic; heap_info_ptr->fCRC32 = 0U; // dont fill it for now. heap_info_ptr->fOffset = reinterpret_cast(heap_info_ptr) + sizeof(Detail::MM_INFORMATION_BLOCK); @@ -122,7 +122,7 @@ _Output VoidPtr mm_alloc_ptr(SizeT sz, Bool wr, Bool user, SizeT pad_amount) { heap_info_ptr->fPresent = Yes; heap_info_ptr->fPad = pad_amount; - rt_set_memory(heap_info_ptr->fPadding, 0, kMemoryMgrAlignSz); + rt_set_memory(heap_info_ptr->fPadding, 0, kHeapMgrAlignSz); auto result = reinterpret_cast(heap_info_ptr->fOffset); @@ -191,7 +191,7 @@ _Output Int32 mm_free_ptr(VoidPtr heap_ptr) { reinterpret_cast((UIntPtr) (heap_ptr) - sizeof(Detail::MM_INFORMATION_BLOCK)); - if (heap_info_ptr && heap_info_ptr->fMagic == kMemoryMgrMagic) { + if (heap_info_ptr && heap_info_ptr->fMagic == kHeapMgrMagic) { if (!heap_info_ptr->fPresent) { return kErrorHeapNotPresent; } @@ -231,7 +231,7 @@ _Output Boolean mm_is_valid_ptr(VoidPtr heap_ptr) { reinterpret_cast((UIntPtr) (heap_ptr) - sizeof(Detail::MM_INFORMATION_BLOCK)); - return (heap_info_ptr && heap_info_ptr->fPresent && heap_info_ptr->fMagic == kMemoryMgrMagic); + return (heap_info_ptr && heap_info_ptr->fPresent && heap_info_ptr->fMagic == kHeapMgrMagic); } return No; @@ -247,7 +247,7 @@ _Output Boolean mm_protect_ptr(VoidPtr heap_ptr) { sizeof(Detail::MM_INFORMATION_BLOCK)); /// if valid, present and is heap header, then compute crc32 - if (heap_info_ptr && heap_info_ptr->fPresent && kMemoryMgrMagic == heap_info_ptr->fMagic) { + if (heap_info_ptr && heap_info_ptr->fPresent && kHeapMgrMagic == heap_info_ptr->fMagic) { heap_info_ptr->fCRC32 = ke_calculate_crc32((Char*) heap_info_ptr->fOffset, heap_info_ptr->fSize); diff --git a/dev/kernel/src/PEFCodeMgr.cc b/dev/kernel/src/PEFCodeMgr.cc index e810651a..ed72473f 100644 --- a/dev/kernel/src/PEFCodeMgr.cc +++ b/dev/kernel/src/PEFCodeMgr.cc @@ -161,7 +161,7 @@ ErrorOr PEFLoader::FindSymbol(const Char* name, Int32 kind) { kout << "PEFLoader: Information: Loaded stub: " << container_header->Name << "!\r"; auto ret = HAL::mm_map_page((VoidPtr) container_header->VMAddress, - (VoidPtr) HAL::mm_get_phys_address(container_blob_value), + (VoidPtr) HAL::mm_get_page_addr(container_blob_value), HAL::kMMFlagsPresent | HAL::kMMFlagsUser); if (ret != kErrorSuccess) { diff --git a/dev/kernel/src/UserProcessScheduler.cc b/dev/kernel/src/UserProcessScheduler.cc index 77421f5f..f900f984 100644 --- a/dev/kernel/src/UserProcessScheduler.cc +++ b/dev/kernel/src/UserProcessScheduler.cc @@ -403,10 +403,10 @@ ProcessID UserProcessScheduler::Spawn(const Char* name, VoidPtr code, VoidPtr im #ifdef __NE_VIRTUAL_MEMORY_SUPPORT__ HAL::mm_map_page((VoidPtr) process.StackFrame->IP, - (VoidPtr) HAL::mm_get_phys_address((VoidPtr) process.StackFrame->IP), + (VoidPtr) HAL::mm_get_page_addr((VoidPtr) process.StackFrame->IP), HAL::kMMFlagsUser | HAL::kMMFlagsPresent); HAL::mm_map_page((VoidPtr) process.StackFrame->SP, - (VoidPtr) HAL::mm_get_phys_address((VoidPtr) process.StackFrame->SP), + (VoidPtr) HAL::mm_get_page_addr((VoidPtr) process.StackFrame->SP), HAL::kMMFlagsUser | HAL::kMMFlagsPresent); #endif // ifdef __NE_VIRTUAL_MEMORY_SUPPORT__ diff --git a/docs/drawio/OS_DESIGN.drawio b/docs/drawio/OS_DESIGN.drawio index 3a03540c..c428d137 100644 --- a/docs/drawio/OS_DESIGN.drawio +++ b/docs/drawio/OS_DESIGN.drawio @@ -8,37 +8,37 @@ - + - + - - + + - - + + - + - - + + - - + + - - + + - - + + diff --git a/public/tools/manual/src/CommandLine.cc b/public/tools/manual/src/CommandLine.cc index 0d9c4136..a1cd9094 100644 --- a/public/tools/manual/src/CommandLine.cc +++ b/public/tools/manual/src/CommandLine.cc @@ -5,8 +5,8 @@ SInt32 _NeMain(SInt32 argc, Char* argv[]) { SCI_UNUSED(argv); if (argc < 2) { - PrintOut(nullptr, "HELP: manual \n"); - return EXIT_FAILURE; + PrintOut(nullptr, "HELP: manual \n"); + return EXIT_FAILURE; } return EXIT_SUCCESS; diff --git a/public/tools/ping/src/CommandLine.cc b/public/tools/ping/src/CommandLine.cc index 9aae0ea9..7ef58e81 100644 --- a/public/tools/ping/src/CommandLine.cc +++ b/public/tools/ping/src/CommandLine.cc @@ -18,11 +18,11 @@ SInt32 _NeMain(SInt32 argc, Char* argv[]) { return EXIT_FAILURE; } - SInt32 bytes = 64; // Simulated response size - SInt32 time = 100 + (i * 10); // Simulated response time - SInt32 ttl = 64; + SInt32 bytes = 64; // Simulated response size + SInt32 time = 100 + (i * 10); // Simulated response time + SInt32 ttl = 64; - PrintOut(nullptr, "Reply from %s: bytes=%i time=%ims TTL=%i\n", argv[1], bytes, time, ttl); + PrintOut(nullptr, "Reply from %s: bytes=%i time=%ims TTL=%i\n", argv[1], bytes, time, ttl); } return EXIT_SUCCESS; -- cgit v1.2.3 From 1a44b4385b3250cd90e255d7d787ae69e987544b Mon Sep 17 00:00:00 2001 From: Amlal El Mahrouss Date: Tue, 27 May 2025 20:03:26 +0200 Subject: feat: generic_kits: Add X64Chrono inside BenchKit. refactor: libSystem: Refactored as a whole. Signed-off-by: Amlal El Mahrouss --- CODEOWNERS | 2 +- dev/boot/amd64-desktop.make | 2 +- dev/generic_kits/BenchKit/HardwareChrono.h | 9 - dev/generic_kits/BenchKit/X64Chrono.h | 54 +++ dev/kernel/HALKit/AMD64/HalKernelMain.cc | 1 + dev/kernel/KernelKit/UserMgr.h | 2 +- dev/libSystem/AsmProc.h | 15 + dev/libSystem/Codes.h | 58 ++++ dev/libSystem/Macros.h | 126 +++++++ dev/libSystem/SecurityPolicy.h | 12 + dev/libSystem/System.h | 385 +++++++++++++++++++++ dev/libSystem/docs/SPECIFICATION_SYSCALLS.md | 25 ++ dev/libSystem/libSystem.json | 20 ++ dev/libSystem/obj/.keep | 0 dev/libSystem/src/GNUmakefile | 16 + dev/libSystem/src/System.cc | 94 +++++ dev/libSystem/src/SystemCalls+IO.asm | 66 ++++ dev/user/AsmProc.h | 15 - dev/user/Macros.h | 126 ------- dev/user/SecurityPolicy.h | 12 - dev/user/SystemCalls.h | 380 -------------------- dev/user/SystemCodes.h | 58 ---- dev/user/docs/SPECIFICATION_SYSCALLS.md | 25 -- dev/user/obj/.keep | 0 dev/user/src/GNUmakefile | 16 - dev/user/src/SystemCalls+IO.asm | 66 ---- dev/user/src/SystemCalls.cc | 94 ----- dev/user/user.json | 20 -- .../frameworks/CoreFoundation.fwrk/headers/Array.h | 2 +- .../CoreFoundation.fwrk/headers/Foundation.h | 2 +- .../CoreFoundation.fwrk/headers/Property.h | 2 +- .../frameworks/CoreFoundation.fwrk/headers/Ref.h | 2 +- .../frameworks/DiskImage.fwrk/headers/DiskImage.h | 2 +- public/tools/cc/src/CommandLine.cc | 2 +- public/tools/diutil/diutil.json | 2 +- public/tools/ld.dyn/src/CommandLine.cc | 2 +- public/tools/ld.fwrk/src/CommandLine.cc | 2 +- public/tools/manual/src/CommandLine.cc | 2 +- public/tools/mgmt/src/CommandLine.cc | 2 +- public/tools/mk.fwrk/Common.h | 2 +- public/tools/mk.fwrk/src/CommandLine.cc | 2 +- public/tools/mk.hefs/src/CommandLine.cc | 2 +- public/tools/mk.nefs/src/CommandLine.cc | 2 +- public/tools/open/src/CommandLine.cc | 2 +- public/tools/ping/src/CommandLine.cc | 2 +- setup_x64_project.sh | 2 +- tooling/mk_app.py | 2 +- tooling/mk_fwrk.py | 2 +- 48 files changed, 895 insertions(+), 844 deletions(-) delete mode 100644 dev/generic_kits/BenchKit/HardwareChrono.h create mode 100644 dev/generic_kits/BenchKit/X64Chrono.h create mode 100644 dev/libSystem/AsmProc.h create mode 100644 dev/libSystem/Codes.h create mode 100644 dev/libSystem/Macros.h create mode 100644 dev/libSystem/SecurityPolicy.h create mode 100644 dev/libSystem/System.h create mode 100644 dev/libSystem/docs/SPECIFICATION_SYSCALLS.md create mode 100644 dev/libSystem/libSystem.json create mode 100644 dev/libSystem/obj/.keep create mode 100644 dev/libSystem/src/GNUmakefile create mode 100644 dev/libSystem/src/System.cc create mode 100644 dev/libSystem/src/SystemCalls+IO.asm delete mode 100644 dev/user/AsmProc.h delete mode 100644 dev/user/Macros.h delete mode 100644 dev/user/SecurityPolicy.h delete mode 100644 dev/user/SystemCalls.h delete mode 100644 dev/user/SystemCodes.h delete mode 100644 dev/user/docs/SPECIFICATION_SYSCALLS.md delete mode 100644 dev/user/obj/.keep delete mode 100644 dev/user/src/GNUmakefile delete mode 100644 dev/user/src/SystemCalls+IO.asm delete mode 100644 dev/user/src/SystemCalls.cc delete mode 100644 dev/user/user.json (limited to 'public/tools/ping/src/CommandLine.cc') diff --git a/CODEOWNERS b/CODEOWNERS index 3d1f3e45..fa9d0ec8 100644 --- a/CODEOWNERS +++ b/CODEOWNERS @@ -1,5 +1,5 @@ # boot, user, and kernel are owned by amlal@nekernel.org. /dev/kernel/ @amlel-el-mahrouss /dev/boot/ @amlel-el-mahrouss -/dev/user/ @amlel-el-mahrouss +/dev/libSystem/ @amlel-el-mahrouss # some other parts (tooling, frameworks) need ownership too. \ No newline at end of file diff --git a/dev/boot/amd64-desktop.make b/dev/boot/amd64-desktop.make index 113c6295..d39c3bcd 100644 --- a/dev/boot/amd64-desktop.make +++ b/dev/boot/amd64-desktop.make @@ -92,7 +92,7 @@ all: compile-amd64 $(COPY) ../kernel/$(KERNEL) src/root/$(KERNEL) $(COPY) ./modules/SysChk/$(SYSCHK) src/root/$(SYSCHK) $(COPY) ./modules/BootNet/$(BOOTNET) src/root/$(BOOTNET) - $(COPY) ../user/$(SCIKIT) src/root/$(SCIKIT) + $(COPY) ../libSystem/$(SCIKIT) src/root/$(SCIKIT) $(COPY) src/$(BOOTLOADER) src/root/$(BOOTLOADER) $(COPY) ../ddk/$(DDK) src/root/$(DDK) diff --git a/dev/generic_kits/BenchKit/HardwareChrono.h b/dev/generic_kits/BenchKit/HardwareChrono.h deleted file mode 100644 index f6f6fd8c..00000000 --- a/dev/generic_kits/BenchKit/HardwareChrono.h +++ /dev/null @@ -1,9 +0,0 @@ -/* ------------------------------------------- - -Copyright (C) 2025, Amlal El Mahrouss, all rights reserved. - -------------------------------------------- */ - -#pragma once - -#include diff --git a/dev/generic_kits/BenchKit/X64Chrono.h b/dev/generic_kits/BenchKit/X64Chrono.h new file mode 100644 index 00000000..192d1697 --- /dev/null +++ b/dev/generic_kits/BenchKit/X64Chrono.h @@ -0,0 +1,54 @@ +/* ------------------------------------------- + +Copyright (C) 2025, Amlal El Mahrouss, all rights reserved. + +------------------------------------------- */ + +#pragma once + +#include + +#if defined(__NE_AMD64__) + +namespace Kernel { +class X64Chrono; +struct X64ChronoTraits; + +struct X64ChronoTraits { +private: + STATIC UInt64 TickImpl_(void) { + UInt64 a = 0, d = 0; + __asm__ volatile("rdtsc" : "=a"(a), "=d"(d)); + return (d << 32) | a; + } + + friend X64Chrono; +}; + +/// @brief X86_64 hardware chrono implementation using the `rdtsc` instruction. +class X64Chrono : public ChronoInterface { + public: + X64Chrono() = default; + ~X64Chrono() override = default; + + NE_COPY_DEFAULT(X64Chrono); + + public: + void Start() override { fStart = X64ChronoTraits::TickImpl_(); } + + void Stop() override { fStop = X64ChronoTraits::TickImpl_(); } + + void Reset() override { + fStart = 0; + fStop = 0; + } + + UInt64 GetElapsedTime() const override { return fStart - fStop; } + + private: + UInt64 fStart = 0; + UInt64 fStop = 0; +}; +} // namespace Kernel + +#endif // defined(__NE_AMD64__) \ No newline at end of file diff --git a/dev/kernel/HALKit/AMD64/HalKernelMain.cc b/dev/kernel/HALKit/AMD64/HalKernelMain.cc index e7337e62..446a1e85 100644 --- a/dev/kernel/HALKit/AMD64/HalKernelMain.cc +++ b/dev/kernel/HALKit/AMD64/HalKernelMain.cc @@ -14,6 +14,7 @@ #include #include #include +#include #include #include diff --git a/dev/kernel/KernelKit/UserMgr.h b/dev/kernel/KernelKit/UserMgr.h index b7e7ac1d..82f8ca66 100644 --- a/dev/kernel/KernelKit/UserMgr.h +++ b/dev/kernel/KernelKit/UserMgr.h @@ -11,7 +11,7 @@ Revision History: - 04/03/25: Set users directory as /user/ instead of /usr/ + 04/03/25: Set users directory as /libSystem/ instead of /usr/ ------------------------------------------- */ diff --git a/dev/libSystem/AsmProc.h b/dev/libSystem/AsmProc.h new file mode 100644 index 00000000..b707d533 --- /dev/null +++ b/dev/libSystem/AsmProc.h @@ -0,0 +1,15 @@ +/* ------------------------------------------- + + Copyright (C) 2025, Amlal El Mahrouss, all rights reserved. + +------------------------------------------- */ + +#pragma once + +#include +#include + +IMPORT_C VoidPtr sci_syscall_arg_1(SizeT id); +IMPORT_C VoidPtr sci_syscall_arg_2(SizeT id, VoidPtr arg1); +IMPORT_C VoidPtr sci_syscall_arg_3(SizeT id, VoidPtr arg1, VoidPtr arg3); +IMPORT_C VoidPtr sci_syscall_arg_4(SizeT id, VoidPtr arg1, VoidPtr arg3, VoidPtr arg4); diff --git a/dev/libSystem/Codes.h b/dev/libSystem/Codes.h new file mode 100644 index 00000000..0451df64 --- /dev/null +++ b/dev/libSystem/Codes.h @@ -0,0 +1,58 @@ +/* ------------------------------------------- + + Copyright (C) 2024-2025, Amlal El Mahrouss, all rights reserved. + +------------------------------------------- */ + +#pragma once + +#include + +/// @file Codes.h +/// @brief Process Codes type and values. +/// @author Amlal El Mahrouss (amlal@nekernel.org) + +#define err_local_ok() (kLastError == kErrorSuccess) +#define err_local_fail() (kLastError != kErrorSuccess) +#define err_local_get() (kLastError) + +typedef SInt32 ErrRef; + +inline constexpr ErrRef kErrorSuccess = 0; +inline constexpr ErrRef kErrorExecutable = 33; +inline constexpr ErrRef kErrorExecutableLib = 34; +inline constexpr ErrRef kErrorFileNotFound = 35; +inline constexpr ErrRef kErrorDirectoryNotFound = 36; +inline constexpr ErrRef kErrorDiskReadOnly = 37; +inline constexpr ErrRef kErrorDiskIsFull = 38; +inline constexpr ErrRef kErrorProcessFault = 39; +inline constexpr ErrRef kErrorSocketHangUp = 40; +inline constexpr ErrRef kErrorThreadLocalStorage = 41; +inline constexpr ErrRef kErrorMath = 42; +inline constexpr ErrRef kErrorNoNetwork = 43; +inline constexpr ErrRef kErrorHeapOutOfMemory = 44; +inline constexpr ErrRef kErrorNoSuchDisk = 45; +inline constexpr ErrRef kErrorFileExists = 46; +inline constexpr ErrRef kErrorFormatFailed = 47; +inline constexpr ErrRef kErrorNetworkTimeout = 48; +inline constexpr ErrRef kErrorInternal = 49; +inline constexpr ErrRef kErrorForkAlreadyExists = 50; +inline constexpr ErrRef kErrorOutOfTeamSlot = 51; +inline constexpr ErrRef kErrorHeapNotPresent = 52; +inline constexpr ErrRef kErrorNoEntrypoint = 53; +inline constexpr ErrRef kErrorDiskIsCorrupted = 54; +inline constexpr ErrRef kErrorDisk = 55; +inline constexpr ErrRef kErrorInvalidData = 56; +inline constexpr ErrRef kErrorAsync = 57; +inline constexpr ErrRef kErrorNonBlocking = 58; +inline constexpr ErrRef kErrorIPC = 59; +inline constexpr ErrRef kErrorSign = 60; +inline constexpr ErrRef kErrorInvalidCreds = 61; +inline constexpr ErrRef kErrorCDTrayBroken = 62; +inline constexpr ErrRef kErrorUnrecoverableDisk = 63; +inline constexpr ErrRef kErrorFileLocked = 64; +inline constexpr ErrRef kErrorDiskIsTooTiny = 65; +inline constexpr ErrRef kErrorUnimplemented = -1; + +/// @brief The last error reported by the system to the process. +IMPORT_C ErrRef kLastError; diff --git a/dev/libSystem/Macros.h b/dev/libSystem/Macros.h new file mode 100644 index 00000000..52dc904c --- /dev/null +++ b/dev/libSystem/Macros.h @@ -0,0 +1,126 @@ +/* ------------------------------------------- + +Copyright (C) 2024-2025, Amlal El Mahrouss, all rights reserved. + +File: Macros.h +Purpose: libsci Macros header. + +------------------------------------------- */ + +#pragma once + +/***********************************************************************************/ +/// @file libSystem/Macros.h +/// @brief Macros and Core types of the SCI (System Call Interface). +/***********************************************************************************/ + +#include + +#define ATTRIBUTE(X) __attribute__((X)) + +#define IMPORT_CXX extern "C++" +#define IMPORT_C extern "C" + +#define DEPRECATED ATTRIBUTE(deprecated) + +#define EXIT_SUCCESS (0) +#define EXIT_FAILURE (1) + +#define FILE_MAX_LEN (256) + +#ifndef BOOL +#define BOOL bool +#endif + +typedef bool Bool; +typedef bool Boolean; +typedef void Void; + +#ifndef __cplusplus +#define true (1) +#define false (0) +#endif + +#define YES true +#define NO false + +typedef __UINT64_TYPE__ UInt64; +typedef __UINT32_TYPE__ UInt32; +typedef __UINT16_TYPE__ UInt16; +typedef __UINT8_TYPE__ UInt8; + +typedef __SIZE_TYPE__ SizeT; + +typedef __INT64_TYPE__ SInt64; +typedef __INT32_TYPE__ SInt32; +typedef __INT16_TYPE__ SInt16; +typedef __INT8_TYPE__ SInt8; + +typedef void* VoidPtr; +typedef __UINTPTR_TYPE__ UIntPtr; +typedef char Char; + +#ifdef __cplusplus +typedef decltype(nullptr) nullPtr; +typedef nullPtr NullPtr; + +#define SCI_COPY_DELETE(KLASS) \ + KLASS& operator=(const KLASS&) = delete; \ + KLASS(const KLASS&) = delete; + +#define SCI_COPY_DEFAULT(KLASS) \ + KLASS& operator=(const KLASS&) = default; \ + KLASS(const KLASS&) = default; + +#define SCI_MOVE_DELETE(KLASS) \ + KLASS& operator=(KLASS&&) = delete; \ + KLASS(KLASS&&) = delete; + +#define SCI_MOVE_DEFAULT(KLASS) \ + KLASS& operator=(KLASS&&) = default; \ + KLASS(KLASS&&) = default; + +#endif + +IMPORT_C void _rtl_assert(Bool expr, const Char* origin); + +#define MUST_PASS(X) _rtl_assert(X, __FILE__) + +#ifndef ARRAY_SIZE +#define ARRAY_SIZE(X) \ + (((sizeof(X) / sizeof(*(X))) / (static_cast(!(sizeof(X) % sizeof(*(X))))))) +#endif + +#ifndef KIB +#define KIB(X) (UInt64)((X) / 1024) +#endif + +#ifndef kib_cast +#define kib_cast(X) (UInt64)((X) *1024) +#endif + +#ifndef MIB +#define MIB(X) (UInt64)((UInt64) KIB(X) / 1024) +#endif + +#ifndef mib_cast +#define mib_cast(X) (UInt64)((UInt64) kib_cast(X) * 1024) +#endif + +#ifndef GIB +#define GIB(X) (UInt64)((UInt64) MIB(X) / 1024) +#endif + +#ifndef gib_cast +#define gib_cast(X) (UInt64)((UInt64) mib_cast(X) * 1024) +#endif + +#ifndef TIB +#define TIB(X) (UInt64)((UInt64) GIB(X) / 1024) +#endif + +#ifndef tib_cast +#define tib_cast(X) ((UInt64) gib_cast(X) * 1024) +#endif + +#define SCI_UNUSED(X) ((void) X) diff --git a/dev/libSystem/SecurityPolicy.h b/dev/libSystem/SecurityPolicy.h new file mode 100644 index 00000000..812f52e2 --- /dev/null +++ b/dev/libSystem/SecurityPolicy.h @@ -0,0 +1,12 @@ +/* ------------------------------------------- + + Copyright (C) 2025, Amlal El Mahrouss, all rights reserved. + +------------------------------------------- */ + +#pragma once + +#include + +/// @file SecurityPolicy.h +/// @brief Hardened Security Policy, used to restrict access to certain system calls. \ No newline at end of file diff --git a/dev/libSystem/System.h b/dev/libSystem/System.h new file mode 100644 index 00000000..920ea2b2 --- /dev/null +++ b/dev/libSystem/System.h @@ -0,0 +1,385 @@ +/* ------------------------------------------- + +Copyright (C) 2024-2025, Amlal El Mahrouss, all rights reserved. + +File: System.h +Purpose: System Call Interface. + +------------------------------------------- */ + +#ifndef SCI_SYSTEM_CALLS_H +#define SCI_SYSTEM_CALLS_H + +#include + +// ------------------------------------------------------------------------------------------ // +/// @brief Types API. +// ------------------------------------------------------------------------------------------ // + +struct RefType { + UInt32 __hash; + VoidPtr __self; +}; + +typedef RefType* Ref; + +typedef Ref IORef; +typedef Ref FSRef; +typedef Ref DylibRef; +typedef Ref ThreadRef; +typedef Ref SocketRef; +typedef Ref NetworkRef; +typedef Ref MutexRef; +typedef Ref EventRef; +typedef Ref SemaphoreRef; + +// ------------------------------------------------------------------------------------------ // +/// @brief Dynamic Loader API. +// ------------------------------------------------------------------------------------------ // + +/// @brief Get function which is part of the Dylib. +/// @param symbol the symbol to look for +/// @param dll_handle the Dylib handle. +/// @return the proc pointer. +IMPORT_C Ref LdrGetDylibSymbolFromHandle(_Input const Char* symbol, _Input Ref dll_handle); + +/// @brief Open Dylib handle. +/// @param path dll path. +/// @param drv driver letter. +/// @return a dylib ref. +IMPORT_C Ref LdrOpenDylibHandle(_Input const Char* path, _Input const Char* drive_letter); + +/// @brief Close Dylib handle +/// @param dll_handle the dylib ref. +/// @return whether it closed or not. +IMPORT_C UInt32 LdrCloseDylibHandle(_Input Ref* dll_handle); + +// ------------------------------------------------------------------------------------------ // +// File API. +// ------------------------------------------------------------------------------------------ // + +/// @brief Opens a file from a drive. +/// @param fs_path the filesystem path. +/// @param drive_letter drive name, use NULL to use default drive location. +/// @return the file descriptor of the file. +IMPORT_C Ref IoOpenFile(const Char* fs_path, const Char* drive_letter); + +/// @brief Closes a file and flushes its content. +/// @param file_desc the file descriptor. +/// @return Function doesn't return a type. +IMPORT_C Void IoCloseFile(_Input Ref file_desc); + +/// @brief I/O control (ioctl) on a file. +/// @param file_desc the file descriptor. +/// @param ioctl_code the ioctl code. +/// @param in_data the input data. +/// @param out_data the output data. +/// @return the number of bytes written. +/// @note This function is used to control the file descriptor, introduced for HeFS. +IMPORT_C SInt32 IoCtrlFile(_Input Ref file_desc, _Input UInt32 ioctl_code, _Input VoidPtr in_data, + _Output VoidPtr out_data); + +/// @brief Gets the file mime (if any) +/// @param file_desc the file descriptor. +IMPORT_C const Char* IoMimeFile(_Input Ref file_desc); + +/// @brief Gets the dir DIM. +/// @param dir_desc directory descriptor. +/// @note only works in HeFS, will return nil-x/nil if used on any other filesystem. +IMPORT_C const Char* IoDimFile(_Input Ref dir_desc); + +/// @brief Write data to a file ref +/// @param file_desc the file descriptor. +/// @param out_data the data to write. +/// @param sz_data the size of the data to write. +/// @return the number of bytes written. +IMPORT_C UInt32 IoWriteFile(_Input Ref file_desc, _Output VoidPtr out_data, SizeT sz_data); + +/// @brief Read data from a file. +/// @param file_desc the file descriptor. +/// @param out_data the data to read. +/// @param sz_data the size of the data to read. +IMPORT_C UInt32 IoReadFile(_Input Ref file_desc, _Output VoidPtr* out_data, SizeT sz_data); + +/// @brief Rewind the file pointer to the beginning of the file. +/// @param file_desc the file descriptor. +/// @return the number of bytes read. +IMPORT_C UInt64 IoRewindFile(_Input Ref file_desc); + +/// @brief Tell the current position of the file pointer. +/// @param file_desc the file descriptor. +/// @return the current position of the file pointer. +IMPORT_C UInt64 IoTellFile(_Input Ref file_desc); + +/// @brief Seek file offset from file descriptor. +IMPORT_C UInt64 IoSeekFile(_Input Ref file_desc, UInt64 file_offset); + +// ------------------------------------------------------------------------ +// Process API. +// ------------------------------------------------------------------------ + +/// @brief Spawns a Thread Information Block and Global Information Block inside the current +/// process. +/// @param process_id Target Process ID, must be valid. +/// @return > 0 error occurred or already present, = 0 success. +IMPORT_C UInt32 RtlSpawnIB(UIntPtr process_id); + +/// @brief Spawns a process with a unique pid (stored as UIntPtr). +/// @param process_path process filesystem path. +/// @return > 0 process was created. +IMPORT_C UIntPtr RtlSpawnProcess(const Char* process_path, SizeT argc, Char** argv, Char** envp, + SizeT envp_len); + +/// @brief Exits a process with an exit_code. +/// @return if it has succeeded true, otherwise false. +IMPORT_C Bool RtlExitProcess(UIntPtr handle, UIntPtr exit_code); + +// ------------------------------------------------------------------------ +// Memory Manager API. +// ------------------------------------------------------------------------ + +/// @brief Creates a new heap from the process's address space. +/// @param len the length of it. +/// @param flags the flags of it. +/// @return heap pointer. +IMPORT_C VoidPtr MmCreateHeap(_Input SizeT len, _Input UInt32 flags); + +/// @brief Destroys the pointer +/// @param heap the heap itself. +/// @return void. +IMPORT_C SInt32 MmDestroyHeap(_Input VoidPtr heap); + +/// @brief Change protection flags of a memory region. +IMPORT_C SInt32 MmSetHeapFlags(_Input VoidPtr heap, _Input UInt32 flags); + +/// @brief Change protection flags of a memory region. +IMPORT_C UInt32 MmGetHeapFlags(_Input VoidPtr heap); + +/// @brief Fill memory region with CRC32. +IMPORT_C UInt32 MmFillCRC32Heap(_Input VoidPtr heap); + +/// @brief Copy memory region. +IMPORT_C VoidPtr MmCopyMemory(_Input VoidPtr dest, _Input VoidPtr src, _Input SizeT len); + +/// @brief Compare memory regions. +IMPORT_C SInt64 MmCmpMemory(_Input VoidPtr dest, _Input VoidPtr src, _Input SizeT len); + +/// @brief Fill memory region. +IMPORT_C VoidPtr MmFillMemory(_Input VoidPtr dest, _Input SizeT len, _Input UInt8 value); + +/// @brief Compare string regions. +IMPORT_C SInt64 MmStrCmp(_Input const Char* dest, _Input const Char* src); + +/// @brief Get length of string. +IMPORT_C SInt64 MmStrLen(const Char* str); + +// ------------------------------------------------------------------------ +// @brief Error API. +// ------------------------------------------------------------------------ + +IMPORT_C SInt32 ErrGetLastError(Void); + +// ------------------------------------------------------------------------ +// @brief Threading API. +// ------------------------------------------------------------------------ + +/// @brief Exit the current thread. +/// @param exit_code the exit code. +IMPORT_C SInt32 ThrExitCurrentThread(_Input SInt32 exit_code); + +/// @brief Exit the main thread. +/// @param exit_code the exit code. +IMPORT_C SInt32 ThrExitMainThread(_Input SInt32 exit_code); + +/// @brief Exit a thread. +/// @param thread the thread to exit. +/// @param exit_code the exit code. +IMPORT_C SInt32 ThrExitThread(_Input ThreadRef thread, _Input SInt32 exit_code); + +/// @brief Thread procedure function type. +typedef SInt32 (*ThrProcKind)(SInt32 argc, Char** argv); + +/// @brief Creates a thread. +/// @param procedure the thread procedure. +/// @param argument_count number of arguments inside that thread. +/// @param flags Thread flags. +/// @return the thread object. +IMPORT_C ThreadRef ThrCreateThread(const Char* thread_name, ThrProcKind procedure, + SInt32 argument_count, SInt32 flags); + +/// @brief Yields the current thread. +/// @param thread the thread to yield. +IMPORT_C SInt32 ThrYieldThread(ThreadRef thrd); + +/// @brief Joins a thread. +/// @param thread the thread to join. +IMPORT_C SInt32 ThrJoinThread(ThreadRef thrd); + +/// @brief Detach a thread. +/// @param thread the thread to detach. +IMPORT_C SInt32 ThrDetachThread(ThreadRef thrd); + +// ------------------------------------------------------------------------ +// @brief Drive Management API. +// ------------------------------------------------------------------------ + +// ------------------------------------------------------------------------------------------ // +/// @brief Get the default drive letter. +/// @param void. +/// @return the drive letter. +// ------------------------------------------------------------------------------------------ // +IMPORT_C Char* DrvGetDefaultDriveLetter(Void); + +// ------------------------------------------------------------------------------------------ // +/// @brief Get the drive letter from a path. +/// @param path the path. +/// @return the drive letter. +// ------------------------------------------------------------------------------------------ // +IMPORT_C Char* DrvGetDriveLetterFromPath(_Input const Char* path); + +// ------------------------------------------------------------------------------------------ // +/// @brief Get a mounted drive from a letter. +/// @param letter the letter (A..Z). +/// @return the drive object. +// ------------------------------------------------------------------------------------------ // +IMPORT_C Ref DrvGetMountedDrive(_Input Char letter); + +// ------------------------------------------------------------------------------------------ // +/// @brief Mount a drive. +/// @param path the path to mount. +/// @param letter the letter to mount. +// ------------------------------------------------------------------------------------------ // +IMPORT_C Void DrvMountDrive(_Input const Char* path, _Input const Char* letter); + +// ------------------------------------------------------------------------------------------ // +/// @brief Unmount a drive. +/// @param letter the letter to unmount. +// ------------------------------------------------------------------------------------------ // +IMPORT_C Void DrvUnmountDrive(_Input Char letter); + +// ------------------------------------------------------------------------ +// Event handling API, use to listen to OS specific events. +// ------------------------------------------------------------------------ + +// ------------------------------------------------------------------------------------------ // +/// @brief Add an event listener. +/// @param event_name the event name. +/// @param listener the listener to add. +/// @return the event listener. +// ------------------------------------------------------------------------------------------ // + +IMPORT_C Void EvtAddListener(_Input const Char* event_name, _Input Ref listener); + +// ------------------------------------------------------------------------------------------ // +/// @brief Remove an event listener. +/// @param event_name the event name. +/// @param listener the listener to remove. +/// @return the event listener. +// ------------------------------------------------------------------------------------------ // + +IMPORT_C Void EvtRemoveListener(_Input const Char* event_name, _Input Ref listener); + +// ------------------------------------------------------------------------------------------ // +/// @brief Dispatch an event. +/// @param event_name the event name. +/// @param event_data the event data. +/// @return the event data. +// ------------------------------------------------------------------------------------------ // + +IMPORT_C VoidPtr EvtDispatchEvent(_Input const Char* event_name, _Input VoidPtr event_data); + +// ------------------------------------------------------------------------------------------ // +// Power API. +// ------------------------------------------------------------------------------------------ // + +enum { + kPowerCodeInvalid = 0, + kPowerCodeShutdown = 12, + kPowerCodeReboot, + kPowerCodeSleep, + kPowerCodeWake, + kPowerCodeCount, +}; + +IMPORT_C SInt32 PwrReadCode(_Output SInt32& code); + +IMPORT_C SInt32 PwrSendCode(_Output SInt32& code); + +// ------------------------------------------------------------------------------------------ // +// CD-ROM API. +// ------------------------------------------------------------------------------------------ // + +IMPORT_C SInt32 CdEjectDrive(_Input Char drv_letter); + +IMPORT_C SInt32 CdOpenTray(Void); + +IMPORT_C SInt32 CdCloseTray(Void); + +// ------------------------------------------------------------------------------------------ // +// Printer API. +// ------------------------------------------------------------------------------------------ // + +IMPORT_C SInt32 PrintOut(IORef file /* nullptr to direct to stdout */, const Char* fmt, ...); + +IMPORT_C SInt32 PrintIn(IORef file /* nullptr to direct to stdout */, const Char* fmt, ...); + +IMPORT_C IORef PrintCreate(Void); + +IMPORT_C SInt32 PrintRelease(IORef); + +IMPORT_C IORef PrintGet(const Char* path); + +// ------------------------------------------------------------------------------------------ // +// @brief Scheduler/Debug API. +// ------------------------------------------------------------------------------------------ // + +typedef SInt32 AffinityRef; +typedef UInt64 ProcessRef; + +IMPORT_C SInt32 SchedSetAffinity(_Input ProcessRef, SInt32 req, _Input AffinityRef*); + +IMPORT_C SInt32 SchedGetAffinity(_Input ProcessRef, _InOut AffinityRef*); + +IMPORT_C SInt32 SchedFireSignal(_Input ProcessRef, SInt32); + +IMPORT_C SInt32 SchedReadMemory(_Input ProcessRef, SInt32, SInt32); + +IMPORT_C SInt32 SchedWriteMemory(_Input ProcessRef, SInt32, SInt32); + +IMPORT_C UIntPtr SchedGetCurrentProcessID(Void); + +// ------------------------------------------------------------------------------------------ // +// @brief Filesystem API. +// ------------------------------------------------------------------------------------------ // + +IMPORT_C BOOL FsCopy(const Char* path, const Char* dst); + +IMPORT_C BOOL FsMove(const Char* path, const Char* dst); + +IMPORT_C BOOL FsExists(const Char* path); + +IMPORT_C BOOL FsCreateDir(const Char* path); + +IMPORT_C BOOL FsCreateFile(const Char* path); + +IMPORT_C BOOL FsCreateAlias(const Char* path, const Char* from); + +// ------------------------------------------------------------------------------------------ // +// @brief Installable Filesystem API. +// ------------------------------------------------------------------------------------------ // + +IMPORT_C BOOL IfsMount(const Char* path, const Char* drive_letter); + +IMPORT_C BOOL IfsUnmount(const Char* drive_letter); + +IMPORT_C BOOL IfsIsMounted(const Char* drive_letter); + +// ------------------------------------------------------------------------------------------ // +// @brief String Manip API. +// ------------------------------------------------------------------------------------------ // + +IMPORT_C Char* StrFmt(const Char* fmt, ...); + +IMPORT_C UInt64 StrMathToNumber(const Char* in, const Char** endp, const SInt16 base); + +#endif // ifndef SCI_SYSTEM_CALLS_H diff --git a/dev/libSystem/docs/SPECIFICATION_SYSCALLS.md b/dev/libSystem/docs/SPECIFICATION_SYSCALLS.md new file mode 100644 index 00000000..b4b11c8c --- /dev/null +++ b/dev/libSystem/docs/SPECIFICATION_SYSCALLS.md @@ -0,0 +1,25 @@ +=================================== +# 0: General Information +=================================== + +- **Programming Language**: C / C++ +- **Build System**: Make / BTB (Build the Build) +- **Purpose**: System Call Interface (SCI) for NeKernel + +=================================== +# 1: How It Works +=================================== + +- This header provides the raw API surface for accessing NeKernel's system calls. + +- It is **not** directly used by applications. + - Instead, it is abstracted by the **SystemSDK**, which presents a stable, high-level interface. + +- At runtime: + - System calls are routed from user-space code to the **kernel syscall manager**. + - The syscall manager executes the requested operation and returns control to `libSystem`. + - Finally, the result is delivered back to the originating process. + +- This separation ensures that: + - The SCI remains low-level and close to the ABI. + - `SystemSDK` provides portability and shielding from changes in syscall internals. \ No newline at end of file diff --git a/dev/libSystem/libSystem.json b/dev/libSystem/libSystem.json new file mode 100644 index 00000000..fdcd2a56 --- /dev/null +++ b/dev/libSystem/libSystem.json @@ -0,0 +1,20 @@ +{ + "compiler_path": "x86_64-w64-mingw32-g++", + "compiler_std": "c++20", + "headers_path": ["../", "./"], + "sources_path": ["src/*.cc", "src/*.stub.obj"], + "output_name": "libSystem.sys", + "compiler_flags": [ + "-ffreestanding", + "-shared", + "-fPIC", + "-fno-rtti", + "-fno-exceptions", + "-Wl,--subsystem=17" + ], + "cpp_macros": [ + "kLibSystemVersion=0x0100", + "kLibSystemVersionHighest=0x0100", + "kLibSystemVersionLowest=0x0100" + ] +} diff --git a/dev/libSystem/obj/.keep b/dev/libSystem/obj/.keep new file mode 100644 index 00000000..e69de29b diff --git a/dev/libSystem/src/GNUmakefile b/dev/libSystem/src/GNUmakefile new file mode 100644 index 00000000..9b901f9f --- /dev/null +++ b/dev/libSystem/src/GNUmakefile @@ -0,0 +1,16 @@ +################################################## +# (c) Amlal El Mahrouss, all rights reserved. +# This file is for libSystem.sys's syscall stubs. +################################################## + +ASM=nasm +FLAGS=-f win64 + +.PHONY: error +error: + @echo "==> Invalid rule." + @echo "==> Use sci_asm_io_ instead." + +.PHONY: sci_asm_io_x64 +sci_asm_io_x64: + $(ASM) $(FLAGS) SystemCalls+IO.asm -o SystemCalls+IO.stub.obj diff --git a/dev/libSystem/src/System.cc b/dev/libSystem/src/System.cc new file mode 100644 index 00000000..1c28303d --- /dev/null +++ b/dev/libSystem/src/System.cc @@ -0,0 +1,94 @@ +/* ------------------------------------------- + + Copyright (C) 2024-2025, Amlal El Mahrouss, all rights reserved. + +------------------------------------------- */ + +#include +#include + +/// @file SystemCalls.cc +/// @brief Source file for the memory functions/syscalls for libSystem.sys + +IMPORT_C VoidPtr MmCopyMemory(_Input VoidPtr dest, _Input VoidPtr src, _Input SizeT len) { + if (!len || !dest || !src) { + return nullptr; + } + + for (SizeT i = 0; i < len; i++) { + ((Char*) dest)[i] = ((Char*) src)[i]; + } + + return dest; +} + +IMPORT_C SInt64 MmStrLen(const Char* in) { + if (!in) return 0; + + SizeT len{0}; + + do { + ++len; + } while (in[len] != '\0'); + + return len; +} + +IMPORT_C VoidPtr MmFillMemory(_Input VoidPtr dest, _Input SizeT len, _Input UInt8 value) { + if (!len || !dest) { + return nullptr; + } + + for (SizeT i = 0; i < len; i++) { + ((Char*) dest)[i] = value; + } + + return dest; +} + +//-----------------------------------------------------------------------------------------------------------// +/// @brief Systems Calls implementation. +/// @internal +//-----------------------------------------------------------------------------------------------------------// + +IMPORT_C Ref IoOpenFile(_Input const Char* path, _Input const Char* drv_letter) { + return sci_syscall_arg_3(1, reinterpret_cast(const_cast(path)), + reinterpret_cast(const_cast(drv_letter))); +} + +IMPORT_C Void IoCloseFile(_Input Ref desc) { + sci_syscall_arg_2(2, desc); +} + +IMPORT_C UInt64 IoSeekFile(_Input Ref desc, _Input UInt64 off) { + auto ret = (volatile UInt64*) sci_syscall_arg_3(3, reinterpret_cast(desc), + reinterpret_cast(&off)); + + MUST_PASS((*ret) != ~0UL); + return *ret; +} + +IMPORT_C UInt64 IoTellFile(_Input Ref desc) { + auto ret = (volatile UInt64*) sci_syscall_arg_2(4, reinterpret_cast(desc)); + return *ret; +} + +IMPORT_C SInt32 PrintOut(_Input IORef desc, const char* fmt, ...) { + va_list args; + + va_start(args, fmt); + + auto ret = (volatile UInt64*) sci_syscall_arg_4( + 5, reinterpret_cast(desc), reinterpret_cast(const_cast(fmt)), args); + + va_end(args); + + return *ret; +} + +IMPORT_C Void _rtl_assert(Bool expr, const Char* origin) { + if (!expr) { + PrintOut(nullptr, "Assertion failed: %s\r", origin); + PrintOut(nullptr, "Origin: %s\r", origin); + } +} diff --git a/dev/libSystem/src/SystemCalls+IO.asm b/dev/libSystem/src/SystemCalls+IO.asm new file mode 100644 index 00000000..097046af --- /dev/null +++ b/dev/libSystem/src/SystemCalls+IO.asm @@ -0,0 +1,66 @@ +;; /* +;; * ======================================================== +;; * +;; * libSystem/src/SystemCalls+IO.asm +;; * Copyright (C) 2024-2025, Amlal El Mahrouss, all rights reserved. +;; * +;; * ======================================================== +;; */ + +[bits 64] + +section .text + +global sci_syscall_arg_1 +global sci_syscall_arg_2 +global sci_syscall_arg_3 +global sci_syscall_arg_4 + +sci_syscall_arg_1: + push rbp + mov rbp, rsp + + mov r8, rcx + syscall + + pop rbp + + ret + +sci_syscall_arg_2: + push rbp + mov rbp, rsp + + mov r8, rcx + mov r9, rdx + syscall + pop rbp + + ret + +sci_syscall_arg_3: + push rbp + mov rbp, rsp + + mov r8, rcx + mov r9, rdx + mov r10, rbx + + syscall + pop rbp + + ret + +sci_syscall_arg_4: + push rbp + mov rbp, rsp + + mov r8, rcx + mov r9, rdx + mov r10, rbx + mov r11, rax + + syscall + pop rbp + + ret diff --git a/dev/user/AsmProc.h b/dev/user/AsmProc.h deleted file mode 100644 index 4b3b63c1..00000000 --- a/dev/user/AsmProc.h +++ /dev/null @@ -1,15 +0,0 @@ -/* ------------------------------------------- - - Copyright (C) 2025, Amlal El Mahrouss, all rights reserved. - -------------------------------------------- */ - -#pragma once - -#include -#include - -IMPORT_C VoidPtr sci_syscall_arg_1(SizeT id); -IMPORT_C VoidPtr sci_syscall_arg_2(SizeT id, VoidPtr arg1); -IMPORT_C VoidPtr sci_syscall_arg_3(SizeT id, VoidPtr arg1, VoidPtr arg3); -IMPORT_C VoidPtr sci_syscall_arg_4(SizeT id, VoidPtr arg1, VoidPtr arg3, VoidPtr arg4); diff --git a/dev/user/Macros.h b/dev/user/Macros.h deleted file mode 100644 index 71957208..00000000 --- a/dev/user/Macros.h +++ /dev/null @@ -1,126 +0,0 @@ -/* ------------------------------------------- - -Copyright (C) 2024-2025, Amlal El Mahrouss, all rights reserved. - -File: Macros.h -Purpose: libsci Macros header. - -------------------------------------------- */ - -#pragma once - -/***********************************************************************************/ -/// @file user/Macros.h -/// @brief Macros and Core types of the SCI (System Call Interface). -/***********************************************************************************/ - -#include - -#define ATTRIBUTE(X) __attribute__((X)) - -#define IMPORT_CXX extern "C++" -#define IMPORT_C extern "C" - -#define DEPRECATED ATTRIBUTE(deprecated) - -#define EXIT_SUCCESS (0) -#define EXIT_FAILURE (1) - -#define FILE_MAX_LEN (256) - -#ifndef BOOL -#define BOOL bool -#endif - -typedef bool Bool; -typedef bool Boolean; -typedef void Void; - -#ifndef __cplusplus -#define true (1) -#define false (0) -#endif - -#define YES true -#define NO false - -typedef __UINT64_TYPE__ UInt64; -typedef __UINT32_TYPE__ UInt32; -typedef __UINT16_TYPE__ UInt16; -typedef __UINT8_TYPE__ UInt8; - -typedef __SIZE_TYPE__ SizeT; - -typedef __INT64_TYPE__ SInt64; -typedef __INT32_TYPE__ SInt32; -typedef __INT16_TYPE__ SInt16; -typedef __INT8_TYPE__ SInt8; - -typedef void* VoidPtr; -typedef __UINTPTR_TYPE__ UIntPtr; -typedef char Char; - -#ifdef __cplusplus -typedef decltype(nullptr) nullPtr; -typedef nullPtr NullPtr; - -#define SCI_COPY_DELETE(KLASS) \ - KLASS& operator=(const KLASS&) = delete; \ - KLASS(const KLASS&) = delete; - -#define SCI_COPY_DEFAULT(KLASS) \ - KLASS& operator=(const KLASS&) = default; \ - KLASS(const KLASS&) = default; - -#define SCI_MOVE_DELETE(KLASS) \ - KLASS& operator=(KLASS&&) = delete; \ - KLASS(KLASS&&) = delete; - -#define SCI_MOVE_DEFAULT(KLASS) \ - KLASS& operator=(KLASS&&) = default; \ - KLASS(KLASS&&) = default; - -#endif - -IMPORT_C void _rtl_assert(Bool expr, const Char* origin); - -#define MUST_PASS(X) _rtl_assert(X, __FILE__) - -#ifndef ARRAY_SIZE -#define ARRAY_SIZE(X) \ - (((sizeof(X) / sizeof(*(X))) / (static_cast(!(sizeof(X) % sizeof(*(X))))))) -#endif - -#ifndef KIB -#define KIB(X) (UInt64)((X) / 1024) -#endif - -#ifndef kib_cast -#define kib_cast(X) (UInt64)((X) *1024) -#endif - -#ifndef MIB -#define MIB(X) (UInt64)((UInt64) KIB(X) / 1024) -#endif - -#ifndef mib_cast -#define mib_cast(X) (UInt64)((UInt64) kib_cast(X) * 1024) -#endif - -#ifndef GIB -#define GIB(X) (UInt64)((UInt64) MIB(X) / 1024) -#endif - -#ifndef gib_cast -#define gib_cast(X) (UInt64)((UInt64) mib_cast(X) * 1024) -#endif - -#ifndef TIB -#define TIB(X) (UInt64)((UInt64) GIB(X) / 1024) -#endif - -#ifndef tib_cast -#define tib_cast(X) ((UInt64) gib_cast(X) * 1024) -#endif - -#define SCI_UNUSED(X) ((void) X) diff --git a/dev/user/SecurityPolicy.h b/dev/user/SecurityPolicy.h deleted file mode 100644 index a03c928b..00000000 --- a/dev/user/SecurityPolicy.h +++ /dev/null @@ -1,12 +0,0 @@ -/* ------------------------------------------- - - Copyright (C) 2025, Amlal El Mahrouss, all rights reserved. - -------------------------------------------- */ - -#pragma once - -#include - -/// @file SecurityPolicy.h -/// @brief Hardened Security Policy, used to restrict access to certain system calls. \ No newline at end of file diff --git a/dev/user/SystemCalls.h b/dev/user/SystemCalls.h deleted file mode 100644 index d77c0b8f..00000000 --- a/dev/user/SystemCalls.h +++ /dev/null @@ -1,380 +0,0 @@ -/* ------------------------------------------- - -Copyright (C) 2024-2025, Amlal El Mahrouss, all rights reserved. - -File: SystemCalls.h -Purpose: System Call Interface. - -------------------------------------------- */ - -#ifndef SCI_SYSTEM_CALLS_H -#define SCI_SYSTEM_CALLS_H - -#include - -// ------------------------------------------------------------------------------------------ // -/// @brief Types API. -// ------------------------------------------------------------------------------------------ // - -typedef VoidPtr Ref; - -typedef Ref IORef; -typedef Ref FSRef; -typedef Ref DylibRef; -typedef Ref ThreadRef; -typedef Ref SocketRef; -typedef Ref NetworkRef; -typedef Ref MutexRef; -typedef Ref EventRef; -typedef Ref SemaphoreRef; - -// ------------------------------------------------------------------------------------------ // -/// @brief Dynamic Loader API. -// ------------------------------------------------------------------------------------------ // - -/// @brief Get function which is part of the Dylib. -/// @param symbol the symbol to look for -/// @param dll_handle the Dylib handle. -/// @return the proc pointer. -IMPORT_C Ref LdrGetDylibSymbolFromHandle(_Input const Char* symbol, _Input Ref dll_handle); - -/// @brief Open Dylib handle. -/// @param path dll path. -/// @param drv driver letter. -/// @return a dylib ref. -IMPORT_C Ref LdrOpenDylibHandle(_Input const Char* path, _Input const Char* drive_letter); - -/// @brief Close Dylib handle -/// @param dll_handle the dylib ref. -/// @return whether it closed or not. -IMPORT_C UInt32 LdrCloseDylibHandle(_Input Ref* dll_handle); - -// ------------------------------------------------------------------------------------------ // -// File API. -// ------------------------------------------------------------------------------------------ // - -/// @brief Opens a file from a drive. -/// @param fs_path the filesystem path. -/// @param drive_letter drive name, use NULL to use default drive location. -/// @return the file descriptor of the file. -IMPORT_C Ref IoOpenFile(const Char* fs_path, const Char* drive_letter); - -/// @brief Closes a file and flushes its content. -/// @param file_desc the file descriptor. -/// @return Function doesn't return a type. -IMPORT_C Void IoCloseFile(_Input Ref file_desc); - -/// @brief I/O control (ioctl) on a file. -/// @param file_desc the file descriptor. -/// @param ioctl_code the ioctl code. -/// @param in_data the input data. -/// @param out_data the output data. -/// @return the number of bytes written. -/// @note This function is used to control the file descriptor, introduced for HeFS. -IMPORT_C SInt32 IoCtrlFile(_Input Ref file_desc, _Input UInt32 ioctl_code, _Input VoidPtr in_data, - _Output VoidPtr out_data); - -/// @brief Gets the file mime (if any) -/// @param file_desc the file descriptor. -IMPORT_C const Char* IoMimeFile(_Input Ref file_desc); - -/// @brief Gets the dir DIM. -/// @param dir_desc directory descriptor. -/// @note only works in HeFS, will return nil-x/nil if used on any other filesystem. -IMPORT_C const Char* IoDimFile(_Input Ref dir_desc); - -/// @brief Write data to a file ref -/// @param file_desc the file descriptor. -/// @param out_data the data to write. -/// @param sz_data the size of the data to write. -/// @return the number of bytes written. -IMPORT_C UInt32 IoWriteFile(_Input Ref file_desc, _Output VoidPtr out_data, SizeT sz_data); - -/// @brief Read data from a file. -/// @param file_desc the file descriptor. -/// @param out_data the data to read. -/// @param sz_data the size of the data to read. -IMPORT_C UInt32 IoReadFile(_Input Ref file_desc, _Output VoidPtr* out_data, SizeT sz_data); - -/// @brief Rewind the file pointer to the beginning of the file. -/// @param file_desc the file descriptor. -/// @return the number of bytes read. -IMPORT_C UInt64 IoRewindFile(_Input Ref file_desc); - -/// @brief Tell the current position of the file pointer. -/// @param file_desc the file descriptor. -/// @return the current position of the file pointer. -IMPORT_C UInt64 IoTellFile(_Input Ref file_desc); - -/// @brief Seek file offset from file descriptor. -IMPORT_C UInt64 IoSeekFile(_Input Ref file_desc, UInt64 file_offset); - -// ------------------------------------------------------------------------ -// Process API. -// ------------------------------------------------------------------------ - -/// @brief Spawns a Thread Information Block and Global Information Block inside the current -/// process. -/// @param process_id Target Process ID, must be valid. -/// @return > 0 error occurred or already present, = 0 success. -IMPORT_C UInt32 RtlSpawnIB(UIntPtr process_id); - -/// @brief Spawns a process with a unique pid (stored as UIntPtr). -/// @param process_path process filesystem path. -/// @return > 0 process was created. -IMPORT_C UIntPtr RtlSpawnProcess(const Char* process_path, SizeT argc, Char** argv, Char** envp, - SizeT envp_len); - -/// @brief Exits a process with an exit_code. -/// @return if it has succeeded true, otherwise false. -IMPORT_C Bool RtlExitProcess(UIntPtr handle, UIntPtr exit_code); - -// ------------------------------------------------------------------------ -// Memory Manager API. -// ------------------------------------------------------------------------ - -/// @brief Creates a new heap from the process's address space. -/// @param len the length of it. -/// @param flags the flags of it. -/// @return heap pointer. -IMPORT_C VoidPtr MmCreateHeap(_Input SizeT len, _Input UInt32 flags); - -/// @brief Destroys the pointer -/// @param heap the heap itself. -/// @return void. -IMPORT_C SInt32 MmDestroyHeap(_Input VoidPtr heap); - -/// @brief Change protection flags of a memory region. -IMPORT_C SInt32 MmSetHeapFlags(_Input VoidPtr heap, _Input UInt32 flags); - -/// @brief Change protection flags of a memory region. -IMPORT_C UInt32 MmGetHeapFlags(_Input VoidPtr heap); - -/// @brief Fill memory region with CRC32. -IMPORT_C UInt32 MmFillCRC32Heap(_Input VoidPtr heap); - -/// @brief Copy memory region. -IMPORT_C VoidPtr MmCopyMemory(_Input VoidPtr dest, _Input VoidPtr src, _Input SizeT len); - -/// @brief Compare memory regions. -IMPORT_C SInt64 MmCmpMemory(_Input VoidPtr dest, _Input VoidPtr src, _Input SizeT len); - -/// @brief Fill memory region. -IMPORT_C VoidPtr MmFillMemory(_Input VoidPtr dest, _Input SizeT len, _Input UInt8 value); - -/// @brief Compare string regions. -IMPORT_C SInt64 MmStrCmp(_Input const Char* dest, _Input const Char* src); - -/// @brief Get length of string. -IMPORT_C SInt64 MmStrLen(const Char* str); - -// ------------------------------------------------------------------------ -// @brief Error API. -// ------------------------------------------------------------------------ - -IMPORT_C SInt32 ErrGetLastError(Void); - -// ------------------------------------------------------------------------ -// @brief Threading API. -// ------------------------------------------------------------------------ - -/// @brief Exit the current thread. -/// @param exit_code the exit code. -IMPORT_C SInt32 ThrExitCurrentThread(_Input SInt32 exit_code); - -/// @brief Exit the main thread. -/// @param exit_code the exit code. -IMPORT_C SInt32 ThrExitMainThread(_Input SInt32 exit_code); - -/// @brief Exit a thread. -/// @param thread the thread to exit. -/// @param exit_code the exit code. -IMPORT_C SInt32 ThrExitThread(_Input ThreadRef thread, _Input SInt32 exit_code); - -/// @brief Thread procedure function type. -typedef SInt32 (*ThrProcKind)(SInt32 argc, Char** argv); - -/// @brief Creates a thread. -/// @param procedure the thread procedure. -/// @param argument_count number of arguments inside that thread. -/// @param flags Thread flags. -/// @return the thread object. -IMPORT_C ThreadRef ThrCreateThread(const Char* thread_name, ThrProcKind procedure, - SInt32 argument_count, SInt32 flags); - -/// @brief Yields the current thread. -/// @param thread the thread to yield. -IMPORT_C SInt32 ThrYieldThread(ThreadRef thrd); - -/// @brief Joins a thread. -/// @param thread the thread to join. -IMPORT_C SInt32 ThrJoinThread(ThreadRef thrd); - -/// @brief Detach a thread. -/// @param thread the thread to detach. -IMPORT_C SInt32 ThrDetachThread(ThreadRef thrd); - -// ------------------------------------------------------------------------ -// @brief Drive Management API. -// ------------------------------------------------------------------------ - -// ------------------------------------------------------------------------------------------ // -/// @brief Get the default drive letter. -/// @param void. -/// @return the drive letter. -// ------------------------------------------------------------------------------------------ // -IMPORT_C Char* DrvGetDefaultDriveLetter(Void); - -// ------------------------------------------------------------------------------------------ // -/// @brief Get the drive letter from a path. -/// @param path the path. -/// @return the drive letter. -// ------------------------------------------------------------------------------------------ // -IMPORT_C Char* DrvGetDriveLetterFromPath(_Input const Char* path); - -// ------------------------------------------------------------------------------------------ // -/// @brief Get a mounted drive from a letter. -/// @param letter the letter (A..Z). -/// @return the drive object. -// ------------------------------------------------------------------------------------------ // -IMPORT_C Ref DrvGetMountedDrive(_Input Char letter); - -// ------------------------------------------------------------------------------------------ // -/// @brief Mount a drive. -/// @param path the path to mount. -/// @param letter the letter to mount. -// ------------------------------------------------------------------------------------------ // -IMPORT_C Void DrvMountDrive(_Input const Char* path, _Input const Char* letter); - -// ------------------------------------------------------------------------------------------ // -/// @brief Unmount a drive. -/// @param letter the letter to unmount. -// ------------------------------------------------------------------------------------------ // -IMPORT_C Void DrvUnmountDrive(_Input Char letter); - -// ------------------------------------------------------------------------ -// Event handling API, use to listen to OS specific events. -// ------------------------------------------------------------------------ - -// ------------------------------------------------------------------------------------------ // -/// @brief Add an event listener. -/// @param event_name the event name. -/// @param listener the listener to add. -/// @return the event listener. -// ------------------------------------------------------------------------------------------ // - -IMPORT_C Void EvtAddListener(_Input const Char* event_name, _Input Ref listener); - -// ------------------------------------------------------------------------------------------ // -/// @brief Remove an event listener. -/// @param event_name the event name. -/// @param listener the listener to remove. -/// @return the event listener. -// ------------------------------------------------------------------------------------------ // - -IMPORT_C Void EvtRemoveListener(_Input const Char* event_name, _Input Ref listener); - -// ------------------------------------------------------------------------------------------ // -/// @brief Dispatch an event. -/// @param event_name the event name. -/// @param event_data the event data. -/// @return the event data. -// ------------------------------------------------------------------------------------------ // - -IMPORT_C VoidPtr EvtDispatchEvent(_Input const Char* event_name, _Input VoidPtr event_data); - -// ------------------------------------------------------------------------------------------ // -// Power API. -// ------------------------------------------------------------------------------------------ // - -enum { - kPowerCodeInvalid = 0, - kPowerCodeShutdown = 12, - kPowerCodeReboot, - kPowerCodeSleep, - kPowerCodeWake, - kPowerCodeCount, -}; - -IMPORT_C SInt32 PwrReadCode(_Output SInt32& code); - -IMPORT_C SInt32 PwrSendCode(_Output SInt32& code); - -// ------------------------------------------------------------------------------------------ // -// CD-ROM API. -// ------------------------------------------------------------------------------------------ // - -IMPORT_C SInt32 CdEjectDrive(_Input Char drv_letter); - -IMPORT_C SInt32 CdOpenTray(Void); - -IMPORT_C SInt32 CdCloseTray(Void); - -// ------------------------------------------------------------------------------------------ // -// Printer API. -// ------------------------------------------------------------------------------------------ // - -IMPORT_C SInt32 PrintOut(IORef file /* nullptr to direct to stdout */, const Char* fmt, ...); - -IMPORT_C SInt32 PrintIn(IORef file /* nullptr to direct to stdout */, const Char* fmt, ...); - -IMPORT_C IORef PrintCreate(Void); - -IMPORT_C SInt32 PrintRelease(IORef); - -IMPORT_C IORef PrintGet(const Char* path); - -// ------------------------------------------------------------------------------------------ // -// @brief Scheduler/Debug API. -// ------------------------------------------------------------------------------------------ // - -typedef SInt32 AffinityRef; -typedef UInt64 ProcessRef; - -IMPORT_C SInt32 SchedSetAffinity(_Input ProcessRef, SInt32 req, _Input AffinityRef*); - -IMPORT_C SInt32 SchedGetAffinity(_Input ProcessRef, _InOut AffinityRef*); - -IMPORT_C SInt32 SchedFireSignal(_Input ProcessRef, SInt32); - -IMPORT_C SInt32 SchedReadMemory(_Input ProcessRef, SInt32, SInt32); - -IMPORT_C SInt32 SchedWriteMemory(_Input ProcessRef, SInt32, SInt32); - -IMPORT_C UIntPtr SchedGetCurrentProcessID(Void); - -// ------------------------------------------------------------------------------------------ // -// @brief Filesystem API. -// ------------------------------------------------------------------------------------------ // - -IMPORT_C BOOL FsCopy(const Char* path, const Char* dst); - -IMPORT_C BOOL FsMove(const Char* path, const Char* dst); - -IMPORT_C BOOL FsExists(const Char* path); - -IMPORT_C BOOL FsCreateDir(const Char* path); - -IMPORT_C BOOL FsCreateFile(const Char* path); - -IMPORT_C BOOL FsCreateAlias(const Char* path, const Char* from); - -// ------------------------------------------------------------------------------------------ // -// @brief Installable Filesystem API. -// ------------------------------------------------------------------------------------------ // - -IMPORT_C BOOL IfsMount(const Char* path, const Char* drive_letter); - -IMPORT_C BOOL IfsUnmount(const Char* drive_letter); - -IMPORT_C BOOL IfsIsMounted(const Char* drive_letter); - -// ------------------------------------------------------------------------------------------ // -// @brief String Manip API. -// ------------------------------------------------------------------------------------------ // - -IMPORT_C Char* StrFmt(const Char* fmt, ...); - -IMPORT_C UInt64 StrMathToNumber(const Char* in, const Char** endp, const SInt16 base); - -#endif // ifndef SCI_SYSTEM_CALLS_H diff --git a/dev/user/SystemCodes.h b/dev/user/SystemCodes.h deleted file mode 100644 index 90457944..00000000 --- a/dev/user/SystemCodes.h +++ /dev/null @@ -1,58 +0,0 @@ -/* ------------------------------------------- - - Copyright (C) 2024-2025, Amlal El Mahrouss, all rights reserved. - -------------------------------------------- */ - -#pragma once - -#include - -/// @file ProcessCodes.h -/// @brief Process Codes type and values. -/// @author Amlal El Mahrouss (amlal@nekernel.org) - -#define err_local_ok() (kLastError == kErrorSuccess) -#define err_local_fail() (kLastError != kErrorSuccess) -#define err_local_get() (kLastError) - -typedef SInt32 ErrRef; - -inline constexpr ErrRef kErrorSuccess = 0; -inline constexpr ErrRef kErrorExecutable = 33; -inline constexpr ErrRef kErrorExecutableLib = 34; -inline constexpr ErrRef kErrorFileNotFound = 35; -inline constexpr ErrRef kErrorDirectoryNotFound = 36; -inline constexpr ErrRef kErrorDiskReadOnly = 37; -inline constexpr ErrRef kErrorDiskIsFull = 38; -inline constexpr ErrRef kErrorProcessFault = 39; -inline constexpr ErrRef kErrorSocketHangUp = 40; -inline constexpr ErrRef kErrorThreadLocalStorage = 41; -inline constexpr ErrRef kErrorMath = 42; -inline constexpr ErrRef kErrorNoNetwork = 43; -inline constexpr ErrRef kErrorHeapOutOfMemory = 44; -inline constexpr ErrRef kErrorNoSuchDisk = 45; -inline constexpr ErrRef kErrorFileExists = 46; -inline constexpr ErrRef kErrorFormatFailed = 47; -inline constexpr ErrRef kErrorNetworkTimeout = 48; -inline constexpr ErrRef kErrorInternal = 49; -inline constexpr ErrRef kErrorForkAlreadyExists = 50; -inline constexpr ErrRef kErrorOutOfTeamSlot = 51; -inline constexpr ErrRef kErrorHeapNotPresent = 52; -inline constexpr ErrRef kErrorNoEntrypoint = 53; -inline constexpr ErrRef kErrorDiskIsCorrupted = 54; -inline constexpr ErrRef kErrorDisk = 55; -inline constexpr ErrRef kErrorInvalidData = 56; -inline constexpr ErrRef kErrorAsync = 57; -inline constexpr ErrRef kErrorNonBlocking = 58; -inline constexpr ErrRef kErrorIPC = 59; -inline constexpr ErrRef kErrorSign = 60; -inline constexpr ErrRef kErrorInvalidCreds = 61; -inline constexpr ErrRef kErrorCDTrayBroken = 62; -inline constexpr ErrRef kErrorUnrecoverableDisk = 63; -inline constexpr ErrRef kErrorFileLocked = 64; -inline constexpr ErrRef kErrorDiskIsTooTiny = 65; -inline constexpr ErrRef kErrorUnimplemented = -1; - -/// @brief The last error reported by the system to the process. -IMPORT_C ErrRef kLastError; diff --git a/dev/user/docs/SPECIFICATION_SYSCALLS.md b/dev/user/docs/SPECIFICATION_SYSCALLS.md deleted file mode 100644 index b4b11c8c..00000000 --- a/dev/user/docs/SPECIFICATION_SYSCALLS.md +++ /dev/null @@ -1,25 +0,0 @@ -=================================== -# 0: General Information -=================================== - -- **Programming Language**: C / C++ -- **Build System**: Make / BTB (Build the Build) -- **Purpose**: System Call Interface (SCI) for NeKernel - -=================================== -# 1: How It Works -=================================== - -- This header provides the raw API surface for accessing NeKernel's system calls. - -- It is **not** directly used by applications. - - Instead, it is abstracted by the **SystemSDK**, which presents a stable, high-level interface. - -- At runtime: - - System calls are routed from user-space code to the **kernel syscall manager**. - - The syscall manager executes the requested operation and returns control to `libSystem`. - - Finally, the result is delivered back to the originating process. - -- This separation ensures that: - - The SCI remains low-level and close to the ABI. - - `SystemSDK` provides portability and shielding from changes in syscall internals. \ No newline at end of file diff --git a/dev/user/obj/.keep b/dev/user/obj/.keep deleted file mode 100644 index e69de29b..00000000 diff --git a/dev/user/src/GNUmakefile b/dev/user/src/GNUmakefile deleted file mode 100644 index 9b901f9f..00000000 --- a/dev/user/src/GNUmakefile +++ /dev/null @@ -1,16 +0,0 @@ -################################################## -# (c) Amlal El Mahrouss, all rights reserved. -# This file is for libSystem.sys's syscall stubs. -################################################## - -ASM=nasm -FLAGS=-f win64 - -.PHONY: error -error: - @echo "==> Invalid rule." - @echo "==> Use sci_asm_io_ instead." - -.PHONY: sci_asm_io_x64 -sci_asm_io_x64: - $(ASM) $(FLAGS) SystemCalls+IO.asm -o SystemCalls+IO.stub.obj diff --git a/dev/user/src/SystemCalls+IO.asm b/dev/user/src/SystemCalls+IO.asm deleted file mode 100644 index 097046af..00000000 --- a/dev/user/src/SystemCalls+IO.asm +++ /dev/null @@ -1,66 +0,0 @@ -;; /* -;; * ======================================================== -;; * -;; * libSystem/src/SystemCalls+IO.asm -;; * Copyright (C) 2024-2025, Amlal El Mahrouss, all rights reserved. -;; * -;; * ======================================================== -;; */ - -[bits 64] - -section .text - -global sci_syscall_arg_1 -global sci_syscall_arg_2 -global sci_syscall_arg_3 -global sci_syscall_arg_4 - -sci_syscall_arg_1: - push rbp - mov rbp, rsp - - mov r8, rcx - syscall - - pop rbp - - ret - -sci_syscall_arg_2: - push rbp - mov rbp, rsp - - mov r8, rcx - mov r9, rdx - syscall - pop rbp - - ret - -sci_syscall_arg_3: - push rbp - mov rbp, rsp - - mov r8, rcx - mov r9, rdx - mov r10, rbx - - syscall - pop rbp - - ret - -sci_syscall_arg_4: - push rbp - mov rbp, rsp - - mov r8, rcx - mov r9, rdx - mov r10, rbx - mov r11, rax - - syscall - pop rbp - - ret diff --git a/dev/user/src/SystemCalls.cc b/dev/user/src/SystemCalls.cc deleted file mode 100644 index f004718c..00000000 --- a/dev/user/src/SystemCalls.cc +++ /dev/null @@ -1,94 +0,0 @@ -/* ------------------------------------------- - - Copyright (C) 2024-2025, Amlal El Mahrouss, all rights reserved. - -------------------------------------------- */ - -#include -#include - -/// @file SystemCalls.cc -/// @brief Source file for the memory functions/syscalls for libSystem.sys - -IMPORT_C VoidPtr MmCopyMemory(_Input VoidPtr dest, _Input VoidPtr src, _Input SizeT len) { - if (!len || !dest || !src) { - return nullptr; - } - - for (SizeT i = 0; i < len; i++) { - ((Char*) dest)[i] = ((Char*) src)[i]; - } - - return dest; -} - -IMPORT_C SInt64 MmStrLen(const Char* in) { - if (!in) return 0; - - SizeT len{0}; - - do { - ++len; - } while (in[len] != '\0'); - - return len; -} - -IMPORT_C VoidPtr MmFillMemory(_Input VoidPtr dest, _Input SizeT len, _Input UInt8 value) { - if (!len || !dest) { - return nullptr; - } - - for (SizeT i = 0; i < len; i++) { - ((Char*) dest)[i] = value; - } - - return dest; -} - -//-----------------------------------------------------------------------------------------------------------// -/// @brief Systems Calls implementation. -/// @internal -//-----------------------------------------------------------------------------------------------------------// - -IMPORT_C Ref IoOpenFile(_Input const Char* path, _Input const Char* drv_letter) { - return sci_syscall_arg_3(1, reinterpret_cast(const_cast(path)), - reinterpret_cast(const_cast(drv_letter))); -} - -IMPORT_C Void IoCloseFile(_Input Ref desc) { - sci_syscall_arg_2(2, desc); -} - -IMPORT_C UInt64 IoSeekFile(_Input Ref desc, _Input UInt64 off) { - auto ret = (volatile UInt64*) sci_syscall_arg_3(3, reinterpret_cast(desc), - reinterpret_cast(&off)); - - MUST_PASS((*ret) != ~0UL); - return *ret; -} - -IMPORT_C UInt64 IoTellFile(_Input Ref desc) { - auto ret = (volatile UInt64*) sci_syscall_arg_2(4, reinterpret_cast(desc)); - return *ret; -} - -IMPORT_C SInt32 PrintOut(_Input IORef desc, const char* fmt, ...) { - va_list args; - - va_start(args, fmt); - - auto ret = (volatile UInt64*) sci_syscall_arg_4( - 5, reinterpret_cast(desc), reinterpret_cast(const_cast(fmt)), args); - - va_end(args); - - return *ret; -} - -IMPORT_C Void _rtl_assert(Bool expr, const Char* origin) { - if (!expr) { - PrintOut(nullptr, "Assertion failed: %s\r", origin); - PrintOut(nullptr, "Origin: %s\r", origin); - } -} diff --git a/dev/user/user.json b/dev/user/user.json deleted file mode 100644 index 2267175e..00000000 --- a/dev/user/user.json +++ /dev/null @@ -1,20 +0,0 @@ -{ - "compiler_path": "x86_64-w64-mingw32-g++", - "compiler_std": "c++20", - "headers_path": ["../", "./"], - "sources_path": ["src/*.cc", "src/*.stub.obj"], - "output_name": "libSystem.sys", - "compiler_flags": [ - "-ffreestanding", - "-shared", - "-fPIC", - "-fno-rtti", - "-fno-exceptions", - "-Wl,--subsystem=17" - ], - "cpp_macros": [ - "kSCIVersion=0x0100", - "kSCIVersionHighest=0x0100", - "kSCIVersionLowest=0x0100" - ] -} diff --git a/public/frameworks/CoreFoundation.fwrk/headers/Array.h b/public/frameworks/CoreFoundation.fwrk/headers/Array.h index 0b4a8dbf..55e75e5e 100644 --- a/public/frameworks/CoreFoundation.fwrk/headers/Array.h +++ b/public/frameworks/CoreFoundation.fwrk/headers/Array.h @@ -6,7 +6,7 @@ #pragma once -#include +#include namespace CF { template diff --git a/public/frameworks/CoreFoundation.fwrk/headers/Foundation.h b/public/frameworks/CoreFoundation.fwrk/headers/Foundation.h index 194b7bb7..1f295ea5 100644 --- a/public/frameworks/CoreFoundation.fwrk/headers/Foundation.h +++ b/public/frameworks/CoreFoundation.fwrk/headers/Foundation.h @@ -10,7 +10,7 @@ #pragma once -#include +#include namespace CF { class CFString; diff --git a/public/frameworks/CoreFoundation.fwrk/headers/Property.h b/public/frameworks/CoreFoundation.fwrk/headers/Property.h index 58e881e5..4da173c7 100644 --- a/public/frameworks/CoreFoundation.fwrk/headers/Property.h +++ b/public/frameworks/CoreFoundation.fwrk/headers/Property.h @@ -8,7 +8,7 @@ #define _PROPS_H #include -#include +#include #define kMaxPropLen (256U) diff --git a/public/frameworks/CoreFoundation.fwrk/headers/Ref.h b/public/frameworks/CoreFoundation.fwrk/headers/Ref.h index c18c6161..cb72a034 100644 --- a/public/frameworks/CoreFoundation.fwrk/headers/Ref.h +++ b/public/frameworks/CoreFoundation.fwrk/headers/Ref.h @@ -9,7 +9,7 @@ #define _REF_H_ #include -#include +#include namespace CF { template diff --git a/public/frameworks/DiskImage.fwrk/headers/DiskImage.h b/public/frameworks/DiskImage.fwrk/headers/DiskImage.h index fc37ab59..efc21253 100644 --- a/public/frameworks/DiskImage.fwrk/headers/DiskImage.h +++ b/public/frameworks/DiskImage.fwrk/headers/DiskImage.h @@ -9,7 +9,7 @@ #pragma once -#include +#include #ifndef __DISK_IMAGE_CDROM__ #define kDISectorSz (512) diff --git a/public/tools/cc/src/CommandLine.cc b/public/tools/cc/src/CommandLine.cc index 719a1555..f1c72b64 100644 --- a/public/tools/cc/src/CommandLine.cc +++ b/public/tools/cc/src/CommandLine.cc @@ -4,7 +4,7 @@ * Copyright (c) 2024-2025 Amlal El Mahrouss */ -#include +#include /// @brief Placeholder program. diff --git a/public/tools/diutil/diutil.json b/public/tools/diutil/diutil.json index a7a49697..a863634b 100644 --- a/public/tools/diutil/diutil.json +++ b/public/tools/diutil/diutil.json @@ -2,7 +2,7 @@ "compiler_path": "x86_64-w64-mingw32-g++", "compiler_std": "c++20", "headers_path": ["./", "../../../dev/kernel", "../../../public/frameworks/", "../../../dev/", "./"], - "sources_path": ["src/CommandLine.cc", "../../../public/frameworks/DiskImage.fwrk/src/*.cc", "../../../dev/user/src/*.cc"], + "sources_path": ["src/CommandLine.cc", "../../../public/frameworks/DiskImage.fwrk/src/*.cc", "../../../dev/libSystem/src/*.cc"], "output_name": "./dist/diutil", "cpp_macros": [ "kDUTILVersion=0x0100", diff --git a/public/tools/ld.dyn/src/CommandLine.cc b/public/tools/ld.dyn/src/CommandLine.cc index 377f22fa..e76c34a7 100644 --- a/public/tools/ld.dyn/src/CommandLine.cc +++ b/public/tools/ld.dyn/src/CommandLine.cc @@ -4,7 +4,7 @@ * Copyright (c) 2024-2025 Amlal El Mahrouss */ -#include +#include /// @brief Library loader. diff --git a/public/tools/ld.fwrk/src/CommandLine.cc b/public/tools/ld.fwrk/src/CommandLine.cc index 0fbaaf2e..e7a6e5ca 100644 --- a/public/tools/ld.fwrk/src/CommandLine.cc +++ b/public/tools/ld.fwrk/src/CommandLine.cc @@ -4,7 +4,7 @@ * Copyright (c) 2024-2025 Amlal El Mahrouss */ -#include +#include /// @brief This program loads a code framework into Kernel's memory. diff --git a/public/tools/manual/src/CommandLine.cc b/public/tools/manual/src/CommandLine.cc index a1cd9094..0704384a 100644 --- a/public/tools/manual/src/CommandLine.cc +++ b/public/tools/manual/src/CommandLine.cc @@ -1,4 +1,4 @@ -#include +#include SInt32 _NeMain(SInt32 argc, Char* argv[]) { SCI_UNUSED(argc); diff --git a/public/tools/mgmt/src/CommandLine.cc b/public/tools/mgmt/src/CommandLine.cc index 45990d08..f3840d01 100644 --- a/public/tools/mgmt/src/CommandLine.cc +++ b/public/tools/mgmt/src/CommandLine.cc @@ -1,4 +1,4 @@ -#include +#include SInt32 _NeMain(SInt32 argc, Char* argv[]) { return EXIT_FAILURE; diff --git a/public/tools/mk.fwrk/Common.h b/public/tools/mk.fwrk/Common.h index be016be6..89e52471 100644 --- a/public/tools/mk.fwrk/Common.h +++ b/public/tools/mk.fwrk/Common.h @@ -7,6 +7,6 @@ #define APPS_COMMON_H #include -#include +#include #endif // APPS_COMMON_H diff --git a/public/tools/mk.fwrk/src/CommandLine.cc b/public/tools/mk.fwrk/src/CommandLine.cc index 202f21bb..4ef7240a 100644 --- a/public/tools/mk.fwrk/src/CommandLine.cc +++ b/public/tools/mk.fwrk/src/CommandLine.cc @@ -7,7 +7,7 @@ #include #include -#include +#include #include diff --git a/public/tools/mk.hefs/src/CommandLine.cc b/public/tools/mk.hefs/src/CommandLine.cc index dd8be97f..711009d5 100644 --- a/public/tools/mk.hefs/src/CommandLine.cc +++ b/public/tools/mk.hefs/src/CommandLine.cc @@ -4,7 +4,7 @@ * Copyright (c) 2025 Amlal El Mahrouss */ -#include +#include /// @brief Placeholder program. diff --git a/public/tools/mk.nefs/src/CommandLine.cc b/public/tools/mk.nefs/src/CommandLine.cc index dd8be97f..711009d5 100644 --- a/public/tools/mk.nefs/src/CommandLine.cc +++ b/public/tools/mk.nefs/src/CommandLine.cc @@ -4,7 +4,7 @@ * Copyright (c) 2025 Amlal El Mahrouss */ -#include +#include /// @brief Placeholder program. diff --git a/public/tools/open/src/CommandLine.cc b/public/tools/open/src/CommandLine.cc index f2378599..6fa4e2f2 100644 --- a/public/tools/open/src/CommandLine.cc +++ b/public/tools/open/src/CommandLine.cc @@ -4,7 +4,7 @@ * Copyright (c) 2024-2025 Amlal El Mahrouss */ -#include +#include /// @brief This program opens an application from **OPEN_APP_BASE_PATH** /// @file CommandLine.cc diff --git a/public/tools/ping/src/CommandLine.cc b/public/tools/ping/src/CommandLine.cc index 7ef58e81..f5c82b80 100644 --- a/public/tools/ping/src/CommandLine.cc +++ b/public/tools/ping/src/CommandLine.cc @@ -1,4 +1,4 @@ -#include +#include SInt32 _NeMain(SInt32 argc, Char* argv[]) { SCI_UNUSED(argc); diff --git a/setup_x64_project.sh b/setup_x64_project.sh index a6115ba7..ba7d4b3f 100755 --- a/setup_x64_project.sh +++ b/setup_x64_project.sh @@ -8,7 +8,7 @@ cd dev/user cd src make sci_asm_io_x64 cd .. -btb user.json +btb libSystem.json cd ../ddk btb ddk.json cd ../boot diff --git a/tooling/mk_app.py b/tooling/mk_app.py index a40c6dee..5ee6d5b7 100755 --- a/tooling/mk_app.py +++ b/tooling/mk_app.py @@ -64,7 +64,7 @@ def create_directory_structure(base_path, project_name): proj_cpp_path = os.path.join(base_path, project_name, f"src/CommandLine.cc") - cpp_file = "#include \n\nSInt32 _NeMain(SInt32 argc, Char* argv[]) {\n\treturn EXIT_FAILURE;\n}" + cpp_file = "#include \n\nSInt32 _NeMain(SInt32 argc, Char* argv[]) {\n\treturn EXIT_FAILURE;\n}" with open(proj_cpp_path, 'w') as cpp_file_io: cpp_file_io.write(cpp_file) diff --git a/tooling/mk_fwrk.py b/tooling/mk_fwrk.py index 78659686..e4e5d7de 100755 --- a/tooling/mk_fwrk.py +++ b/tooling/mk_fwrk.py @@ -70,7 +70,7 @@ def create_directory_structure(base_path_fwrk, project_file_name, project_name): proj_cpp_path = os.path.join(base_path_fwrk, project_name, f"src/DylibMain.cc") - cpp_file = "#include \n\nSInt32 _DylibAttach(SInt32 argc, Char* argv[]) {\n\treturn EXIT_FAILURE;\n}" + cpp_file = "#include \n\nSInt32 _DylibAttach(SInt32 argc, Char* argv[]) {\n\treturn EXIT_FAILURE;\n}" with open(proj_cpp_path, 'w') as cpp_file_io: cpp_file_io.write(cpp_file) -- cgit v1.2.3