From fb790b07aeba8e22e4190cf3e1834d11ecde6c96 Mon Sep 17 00:00:00 2001 From: Amlal Date: Fri, 25 Apr 2025 13:08:33 +0200 Subject: dev: better .clang-format, ran format command. Signed-off-by: Amlal --- dev/kernel/KernelKit/BinaryMutex.h | 50 +- dev/kernel/KernelKit/CodeMgr.h | 61 +-- dev/kernel/KernelKit/CoreProcessScheduler.h | 282 +++++------ dev/kernel/KernelKit/DebugOutput.h | 268 +++++----- dev/kernel/KernelKit/Defines.h | 4 +- dev/kernel/KernelKit/DeviceMgr.h | 207 ++++---- dev/kernel/KernelKit/DriveMgr.h | 317 ++++++------ dev/kernel/KernelKit/FileMgr.h | 652 ++++++++++++------------- dev/kernel/KernelKit/HardwareThreadScheduler.h | 251 +++++----- dev/kernel/KernelKit/IDylibObject.h | 60 +-- dev/kernel/KernelKit/IPEFDylibObject.h | 156 +++--- dev/kernel/KernelKit/KPC.h | 101 ++-- dev/kernel/KernelKit/KernelProcessScheduler.h | 2 +- dev/kernel/KernelKit/LoaderInterface.h | 40 +- dev/kernel/KernelKit/LockDelegate.h | 109 ++--- dev/kernel/KernelKit/MSDOS.h | 51 +- dev/kernel/KernelKit/MemoryMgr.h | 140 +++--- dev/kernel/KernelKit/PCI/DMA.h | 125 +++-- dev/kernel/KernelKit/PCI/DMA.inl | 25 +- dev/kernel/KernelKit/PCI/Database.h | 77 ++- dev/kernel/KernelKit/PCI/Device.h | 135 +++-- dev/kernel/KernelKit/PCI/Express.h | 4 +- dev/kernel/KernelKit/PCI/IO.h | 76 ++- dev/kernel/KernelKit/PCI/IOArray+AMD64.inl | 77 ++- dev/kernel/KernelKit/PCI/Iterator.h | 40 +- dev/kernel/KernelKit/PCI/PCI.h | 89 ++-- dev/kernel/KernelKit/PE.h | 191 ++++---- dev/kernel/KernelKit/PECodeMgr.h | 98 ++-- dev/kernel/KernelKit/PEF.h | 153 +++--- dev/kernel/KernelKit/PEFCodeMgr.h | 103 ++-- dev/kernel/KernelKit/ProcessScheduler.h | 6 +- dev/kernel/KernelKit/Semaphore.h | 13 +- dev/kernel/KernelKit/ThreadLocalStorage.h | 9 +- dev/kernel/KernelKit/ThreadLocalStorage.inl | 74 ++- dev/kernel/KernelKit/Timer.h | 138 +++--- dev/kernel/KernelKit/User.h | 95 ++-- dev/kernel/KernelKit/UserProcessScheduler.h | 472 +++++++++--------- dev/kernel/KernelKit/UserProcessScheduler.inl | 72 ++- dev/kernel/KernelKit/XCOFF.h | 46 +- 39 files changed, 2290 insertions(+), 2579 deletions(-) (limited to 'dev/kernel/KernelKit') diff --git a/dev/kernel/KernelKit/BinaryMutex.h b/dev/kernel/KernelKit/BinaryMutex.h index 660d2e71..5b7200f9 100644 --- a/dev/kernel/KernelKit/BinaryMutex.h +++ b/dev/kernel/KernelKit/BinaryMutex.h @@ -1,41 +1,39 @@ /* ------------------------------------------- - Copyright (C) 2024-2025, Amlal El Mahrouss, all rights reserved. + Copyright (C) 2024-2025, Amlal El Mahrouss, all rights reserved. ------------------------------------------- */ #pragma once -#include -#include #include +#include +#include -namespace Kernel -{ - class USER_PROCESS; +namespace Kernel { +class USER_PROCESS; - /// @brief Access control class, which locks a task until one is done. - class BinaryMutex final - { - public: - explicit BinaryMutex() = default; - ~BinaryMutex() = default; +/// @brief Access control class, which locks a task until one is done. +class BinaryMutex final { + public: + explicit BinaryMutex() = default; + ~BinaryMutex() = default; - public: - bool IsLocked() const; - bool Unlock() noexcept; + public: + bool IsLocked() const; + bool Unlock() noexcept; - public: - BOOL WaitForProcess(const Int16& sec) noexcept; + public: + BOOL WaitForProcess(const Int16& sec) noexcept; - public: - bool Lock(USER_PROCESS& process); - bool LockOrWait(USER_PROCESS& process, TimerInterface* timer); + public: + bool Lock(USER_PROCESS& process); + bool LockOrWait(USER_PROCESS& process, TimerInterface* timer); - public: - NE_COPY_DEFAULT(BinaryMutex) + public: + NE_COPY_DEFAULT(BinaryMutex) - private: - USER_PROCESS fLockingProcess; - }; -} // namespace Kernel + private: + USER_PROCESS fLockingProcess; +}; +} // namespace Kernel diff --git a/dev/kernel/KernelKit/CodeMgr.h b/dev/kernel/KernelKit/CodeMgr.h index 47c05d2e..bb287b24 100644 --- a/dev/kernel/KernelKit/CodeMgr.h +++ b/dev/kernel/KernelKit/CodeMgr.h @@ -1,43 +1,44 @@ /* ------------------------------------------- - Copyright (C) 2024-2025, Amlal El Mahrouss, all rights reserved. + Copyright (C) 2024-2025, Amlal El Mahrouss, all rights reserved. - File: CodeMgr.h - Purpose: Code Mgr. + File: CodeMgr.h + Purpose: Code Mgr. - Revision History: + Revision History: - 30/01/24: Added file (amlel) - 3/8/24: Add UPP struct. + 30/01/24: Added file (amlel) + 3/8/24: Add UPP struct. ------------------------------------------- */ #pragma once +#include #include #include -#include -namespace Kernel -{ - /// @brief Main process entrypoint. - typedef void (*rtl_main_kind)(SizeT argc, Char** argv, Char** envp, SizeT envp_len); - - /// @brief C++ Constructor entrypoint. - typedef void (*rtl_ctor_kind)(void); - - /// @brief C++ Destructor entrypoint. - typedef void (*rtl_dtor_kind)(void); - - /// @brief Executes a new process from a function. Kernel code only. - /// @note This sets up a new stack, anything on the main function that calls the Kernel will not be accessible. - /// @param main the start of the process. - /// @return The team's process id. - ProcessID rtl_create_kernel_process(rtl_main_kind main, const Char* process_name) noexcept; - - /// @brief Executes a new process from a function. User code only. - /// @note This sets up a new stack, anything on the main function that calls the Kernel will not be accessible. - /// @param main the start of the process. - /// @return The team's process id. - ProcessID rtl_create_user_process(rtl_main_kind main, const Char* process_name) noexcept; -} // namespace Kernel +namespace Kernel { +/// @brief Main process entrypoint. +typedef void (*rtl_main_kind)(SizeT argc, Char** argv, Char** envp, SizeT envp_len); + +/// @brief C++ Constructor entrypoint. +typedef void (*rtl_ctor_kind)(void); + +/// @brief C++ Destructor entrypoint. +typedef void (*rtl_dtor_kind)(void); + +/// @brief Executes a new process from a function. Kernel code only. +/// @note This sets up a new stack, anything on the main function that calls the Kernel will not be +/// accessible. +/// @param main the start of the process. +/// @return The team's process id. +ProcessID rtl_create_kernel_process(rtl_main_kind main, const Char* process_name) noexcept; + +/// @brief Executes a new process from a function. User code only. +/// @note This sets up a new stack, anything on the main function that calls the Kernel will not be +/// accessible. +/// @param main the start of the process. +/// @return The team's process id. +ProcessID rtl_create_user_process(rtl_main_kind main, const Char* process_name) noexcept; +} // namespace Kernel diff --git a/dev/kernel/KernelKit/CoreProcessScheduler.h b/dev/kernel/KernelKit/CoreProcessScheduler.h index bd493140..3b581ffe 100644 --- a/dev/kernel/KernelKit/CoreProcessScheduler.h +++ b/dev/kernel/KernelKit/CoreProcessScheduler.h @@ -1,6 +1,6 @@ /* ------------------------------------------- - Copyright (C) 2024-2025, Amlal El Mahrouss, all rights reserved. + Copyright (C) 2024-2025, Amlal El Mahrouss, all rights reserved. ------------------------------------------- */ @@ -9,153 +9,133 @@ #include #include -namespace Kernel -{ - class USER_PROCESS; - class KERNEL_PROCESS; - class UserProcessTeam; - - /***********************************************************************************/ - /// @brief Subsystem enum type. - /***********************************************************************************/ - - enum class ProcessSubsystem : Int32 - { - kProcessSubsystemSecurity = 100, - kProcessSubsystemApplication, - kProcessSubsystemService, - kProcessSubsystemDriver, - kProcessSubsystemInvalid = 256U, - kProcessSubsystemCount = 4, - }; - - typedef UInt64 PTime; - - /***********************************************************************************/ - //! @brief Local Process identifier. - /***********************************************************************************/ - typedef Int64 ProcessID; - - /***********************************************************************************/ - //! @brief Local Process status enum. - /***********************************************************************************/ - enum class ProcessStatusKind : Int32 - { - kInvalid, - kStarting, - kRunning, - kKilled, - kFrozen, - kFinished, - kCount, - }; - - /***********************************************************************************/ - //! @brief Affinity is the amount of nano-seconds this process is going to run. - /***********************************************************************************/ - enum class AffinityKind : Int32 - { - kRealTime = 500, - kVeryHigh = 250, - kHigh = 200, - kStandard = 1000, - kLowUsage = 1500, - kVeryLowUsage = 2000, - }; - - /***********************************************************************************/ - //! Operators for AffinityKind - /***********************************************************************************/ - - inline bool operator<(AffinityKind lhs, AffinityKind rhs) - { - Int32 lhs_int = static_cast(lhs); - Int32 rhs_int = static_cast(rhs); - - return lhs_int < rhs_int; - } - - inline bool operator>(AffinityKind lhs, AffinityKind rhs) - { - Int32 lhs_int = static_cast(lhs); - Int32 rhs_int = static_cast(rhs); - - return lhs_int > rhs_int; - } - - inline bool operator<=(AffinityKind lhs, AffinityKind rhs) - { - Int32 lhs_int = static_cast(lhs); - Int32 rhs_int = static_cast(rhs); - - return lhs_int <= rhs_int; - } - - inline bool operator>=(AffinityKind lhs, AffinityKind rhs) - { - Int32 lhs_int = static_cast(lhs); - Int32 rhs_int = static_cast(rhs); - - return lhs_int >= rhs_int; - } - - using ProcessTime = UInt64; - using PID = Int64; - - /***********************************************************************************/ - /// @note For User manager, tells where we run the code. - /***********************************************************************************/ - enum class ProcessLevelRing : Int32 - { - kRingStdUser = 1, - kRingSuperUser = 2, - kRingGuestUser = 5, - kRingCount = 5, - }; - - /***********************************************************************************/ - /// @brief Helper type to describe a code image. - /***********************************************************************************/ - using ImagePtr = VoidPtr; - - /***********************************************************************************/ - /// @brief Helper class to contain a process's image and blob. - /***********************************************************************************/ - struct PROCESS_IMAGE final - { - explicit PROCESS_IMAGE() = default; - - ImagePtr fCode; - ImagePtr fBlob; - - Bool HasCode() - { - return this->fCode != nullptr; - } - - Bool HasImage() - { - return this->fBlob != nullptr; - } - - ErrorOr Leak() - { - if (this->fCode) - { - return ErrorOr{this->fCode}; - } - - return ErrorOr{kErrorInvalidData}; - } - - ErrorOr LeakBlob() - { - if (this->fBlob) - { - return ErrorOr{this->fBlob}; - } - - return ErrorOr{kErrorInvalidData}; - } - }; -} // namespace Kernel +namespace Kernel { +class USER_PROCESS; +class KERNEL_PROCESS; +class UserProcessTeam; + +/***********************************************************************************/ +/// @brief Subsystem enum type. +/***********************************************************************************/ + +enum class ProcessSubsystem : Int32 { + kProcessSubsystemSecurity = 100, + kProcessSubsystemApplication, + kProcessSubsystemService, + kProcessSubsystemDriver, + kProcessSubsystemInvalid = 256U, + kProcessSubsystemCount = 4, +}; + +typedef UInt64 PTime; + +/***********************************************************************************/ +//! @brief Local Process identifier. +/***********************************************************************************/ +typedef Int64 ProcessID; + +/***********************************************************************************/ +//! @brief Local Process status enum. +/***********************************************************************************/ +enum class ProcessStatusKind : Int32 { + kInvalid, + kStarting, + kRunning, + kKilled, + kFrozen, + kFinished, + kCount, +}; + +/***********************************************************************************/ +//! @brief Affinity is the amount of nano-seconds this process is going to run. +/***********************************************************************************/ +enum class AffinityKind : Int32 { + kRealTime = 500, + kVeryHigh = 250, + kHigh = 200, + kStandard = 1000, + kLowUsage = 1500, + kVeryLowUsage = 2000, +}; + +/***********************************************************************************/ +//! Operators for AffinityKind +/***********************************************************************************/ + +inline bool operator<(AffinityKind lhs, AffinityKind rhs) { + Int32 lhs_int = static_cast(lhs); + Int32 rhs_int = static_cast(rhs); + + return lhs_int < rhs_int; +} + +inline bool operator>(AffinityKind lhs, AffinityKind rhs) { + Int32 lhs_int = static_cast(lhs); + Int32 rhs_int = static_cast(rhs); + + return lhs_int > rhs_int; +} + +inline bool operator<=(AffinityKind lhs, AffinityKind rhs) { + Int32 lhs_int = static_cast(lhs); + Int32 rhs_int = static_cast(rhs); + + return lhs_int <= rhs_int; +} + +inline bool operator>=(AffinityKind lhs, AffinityKind rhs) { + Int32 lhs_int = static_cast(lhs); + Int32 rhs_int = static_cast(rhs); + + return lhs_int >= rhs_int; +} + +using ProcessTime = UInt64; +using PID = Int64; + +/***********************************************************************************/ +/// @note For User manager, tells where we run the code. +/***********************************************************************************/ +enum class ProcessLevelRing : Int32 { + kRingStdUser = 1, + kRingSuperUser = 2, + kRingGuestUser = 5, + kRingCount = 5, +}; + +/***********************************************************************************/ +/// @brief Helper type to describe a code image. +/***********************************************************************************/ +using ImagePtr = VoidPtr; + +/***********************************************************************************/ +/// @brief Helper class to contain a process's image and blob. +/***********************************************************************************/ +struct PROCESS_IMAGE final { + explicit PROCESS_IMAGE() = default; + + ImagePtr fCode; + ImagePtr fBlob; + + Bool HasCode() { return this->fCode != nullptr; } + + Bool HasImage() { return this->fBlob != nullptr; } + + ErrorOr Leak() { + if (this->fCode) { + return ErrorOr{this->fCode}; + } + + return ErrorOr{kErrorInvalidData}; + } + + ErrorOr LeakBlob() { + if (this->fBlob) { + return ErrorOr{this->fBlob}; + } + + return ErrorOr{kErrorInvalidData}; + } +}; +} // namespace Kernel diff --git a/dev/kernel/KernelKit/DebugOutput.h b/dev/kernel/KernelKit/DebugOutput.h index 6d740138..7110a941 100644 --- a/dev/kernel/KernelKit/DebugOutput.h +++ b/dev/kernel/KernelKit/DebugOutput.h @@ -1,13 +1,13 @@ /* ------------------------------------------- - Copyright (C) 2024-2025, Amlal El Mahrouss, all rights reserved. + Copyright (C) 2024-2025, Amlal El Mahrouss, all rights reserved. ------------------------------------------- */ #pragma once -#include #include +#include #include #include @@ -19,183 +19,159 @@ #define kDebugMag3 'G' #define kDebugSourceFile 23 -#define kDebugLine 33 -#define kDebugTeam 43 -#define kDebugEOP 49 - -namespace Kernel -{ - class TerminalDevice; - class DTraceDevice; - - inline TerminalDevice end_line(); - inline TerminalDevice number(const Long& x); - inline TerminalDevice hex_number(const Long& x); - - // @brief Emulates a VT100 terminal. - class TerminalDevice final NE_DEVICE - { - public: - TerminalDevice(void (*print)(IDeviceObject*, const Char*), void (*gets)(IDeviceObject*, const Char*)) - : IDeviceObject(print, gets) - { - } - - ~TerminalDevice() override; - - /// @brief returns device name (terminal name) - /// @return string type (const Char*) - const Char* Name() const override - { - return ("TerminalDevice"); - } - - NE_COPY_DEFAULT(TerminalDevice) - - STATIC TerminalDevice The() noexcept; - }; - - inline TerminalDevice end_line() - { - TerminalDevice self = TerminalDevice::The(); - - self.operator<<("\r"); - return self; - } - - inline TerminalDevice carriage_return() - { - TerminalDevice self = TerminalDevice::The(); - - self.operator<<("\r"); - return self; - } - - inline TerminalDevice tabulate() - { - TerminalDevice self = TerminalDevice::The(); +#define kDebugLine 33 +#define kDebugTeam 43 +#define kDebugEOP 49 + +namespace Kernel { +class TerminalDevice; +class DTraceDevice; + +inline TerminalDevice end_line(); +inline TerminalDevice number(const Long& x); +inline TerminalDevice hex_number(const Long& x); + +// @brief Emulates a VT100 terminal. +class TerminalDevice final NE_DEVICE { + public: + TerminalDevice(void (*print)(IDeviceObject*, const Char*), + void (*gets)(IDeviceObject*, const Char*)) + : IDeviceObject(print, gets) {} + + ~TerminalDevice() override; + + /// @brief returns device name (terminal name) + /// @return string type (const Char*) + const Char* Name() const override { return ("TerminalDevice"); } + + NE_COPY_DEFAULT(TerminalDevice) + + STATIC TerminalDevice The() noexcept; +}; + +inline TerminalDevice end_line() { + TerminalDevice self = TerminalDevice::The(); + + self.operator<<("\r"); + return self; +} + +inline TerminalDevice carriage_return() { + TerminalDevice self = TerminalDevice::The(); + + self.operator<<("\r"); + return self; +} + +inline TerminalDevice tabulate() { + TerminalDevice self = TerminalDevice::The(); - self.operator<<("\t"); - return self; - } + self.operator<<("\t"); + return self; +} - /// @brief emulate a terminal bell, like the VT100 does. - inline TerminalDevice bell() - { - TerminalDevice self = TerminalDevice::The(); +/// @brief emulate a terminal bell, like the VT100 does. +inline TerminalDevice bell() { + TerminalDevice self = TerminalDevice::The(); - self.operator<<("\a"); - return self; - } + self.operator<<("\a"); + return self; +} - namespace Detail - { - inline TerminalDevice _write_number(const Long& x, TerminalDevice& term) - { - UInt64 y = (x > 0 ? x : -x) / 10; - UInt64 h = (x > 0 ? x : -x) % 10; +namespace Detail { + inline TerminalDevice _write_number(const Long& x, TerminalDevice& term) { + UInt64 y = (x > 0 ? x : -x) / 10; + UInt64 h = (x > 0 ? x : -x) % 10; - if (y) - _write_number(y, term); + if (y) _write_number(y, term); - /* fail if the number is not base-10 */ - if (h > 10) - { - _write_number('?', term); - return term; - } + /* fail if the number is not base-10 */ + if (h > 10) { + _write_number('?', term); + return term; + } - if (y == ~0UL) - y = -y; + if (y == ~0UL) y = -y; - const Char kNumbers[11] = "0123456789"; + const Char kNumbers[11] = "0123456789"; - Char buf[2]; - buf[0] = kNumbers[h]; - buf[1] = 0; + Char buf[2]; + buf[0] = kNumbers[h]; + buf[1] = 0; - term.operator<<(buf); - return term; - } + term.operator<<(buf); + return term; + } - inline TerminalDevice _write_number_hex(const Long& x, TerminalDevice& term) - { - UInt64 y = (x > 0 ? x : -x) / 16; - UInt64 h = (x > 0 ? x : -x) % 16; + inline TerminalDevice _write_number_hex(const Long& x, TerminalDevice& term) { + UInt64 y = (x > 0 ? x : -x) / 16; + UInt64 h = (x > 0 ? x : -x) % 16; - if (y) - _write_number_hex(y, term); + if (y) _write_number_hex(y, term); - /* fail if the hex number is not base-16 */ - if (h > 16) - { - _write_number_hex('?', term); - return term; - } + /* fail if the hex number is not base-16 */ + if (h > 16) { + _write_number_hex('?', term); + return term; + } - if (y == ~0UL) - y = -y; + if (y == ~0UL) y = -y; - const Char kNumbers[17] = "0123456789ABCDEF"; + const Char kNumbers[17] = "0123456789ABCDEF"; - Char buf[2]; - buf[0] = kNumbers[h]; - buf[1] = 0; + Char buf[2]; + buf[0] = kNumbers[h]; + buf[1] = 0; - term.operator<<(buf); - return term; - } - } // namespace Detail + term.operator<<(buf); + return term; + } +} // namespace Detail - inline TerminalDevice hex_number(const Long& x) - { - TerminalDevice self = TerminalDevice::The(); +inline TerminalDevice hex_number(const Long& x) { + TerminalDevice self = TerminalDevice::The(); - Detail::_write_number_hex(x, self); - self.operator<<("h"); + Detail::_write_number_hex(x, self); + self.operator<<("h"); - return self; - } + return self; +} - inline TerminalDevice number(const Long& x) - { - TerminalDevice self = TerminalDevice::The(); +inline TerminalDevice number(const Long& x) { + TerminalDevice self = TerminalDevice::The(); - Detail::_write_number(x, self); + Detail::_write_number(x, self); - return self; - } + return self; +} - inline TerminalDevice get_console_in(Char* buf) - { - TerminalDevice self = TerminalDevice::The(); +inline TerminalDevice get_console_in(Char* buf) { + TerminalDevice self = TerminalDevice::The(); - self >> buf; + self >> buf; - return self; - } + return self; +} - inline constexpr SizeT kDebugTypeLen = 256U; +inline constexpr SizeT kDebugTypeLen = 256U; - typedef Char rt_debug_type[kDebugTypeLen]; +typedef Char rt_debug_type[kDebugTypeLen]; - class DebuggerPortHeader final - { - public: - Int16 fPort; - Int16 fPortBsy; - }; +class DebuggerPortHeader final { + public: + Int16 fPort; + Int16 fPortBsy; +}; - inline TerminalDevice& operator<<(TerminalDevice& src, const Long& num) - { - src = number(num); - return src; - } -} // namespace Kernel +inline TerminalDevice& operator<<(TerminalDevice& src, const Long& num) { + src = number(num); + return src; +} +} // namespace Kernel #ifdef kout #undef kout -#endif // ifdef kout +#endif // ifdef kout #define kout TerminalDevice::The() diff --git a/dev/kernel/KernelKit/Defines.h b/dev/kernel/KernelKit/Defines.h index 1356f340..2c170940 100644 --- a/dev/kernel/KernelKit/Defines.h +++ b/dev/kernel/KernelKit/Defines.h @@ -1,6 +1,6 @@ /* ------------------------------------------- - Copyright (C) 2024-2025, Amlal El Mahrouss, all rights reserved. + Copyright (C) 2024-2025, Amlal El Mahrouss, all rights reserved. ------------------------------------------- */ @@ -8,7 +8,7 @@ #include -#define KERNELKIT_VERSION "0.0.1" +#define KERNELKIT_VERSION "0.0.1" #define KERNELKIT_VERSION_BCD 0x0001 class UserProcessScheduler; diff --git a/dev/kernel/KernelKit/DeviceMgr.h b/dev/kernel/KernelKit/DeviceMgr.h index 9cfc54dd..8da52699 100644 --- a/dev/kernel/KernelKit/DeviceMgr.h +++ b/dev/kernel/KernelKit/DeviceMgr.h @@ -1,6 +1,6 @@ /* ------------------------------------------- - Copyright (C) 2024-2025, Amlal El Mahrouss, all rights reserved. + Copyright (C) 2024-2025, Amlal El Mahrouss, all rights reserved. ------------------------------------------- */ @@ -8,8 +8,8 @@ Revision History: - 31/01/24: Add kDeviceCnt (amlel) - 15/11/24: Add NE_DEVICE macro, to inherit from device object. + 31/01/24: Add kDeviceCnt (amlel) + 15/11/24: Add NE_DEVICE macro, to inherit from device object. ------------------------------------------- */ @@ -28,114 +28,93 @@ // Last Rev: Wed, Apr 3, 2024 9:09:41 AM -namespace Kernel -{ - template - class IDeviceObject; - - /***********************************************************************************/ - /// @brief Device contract interface, represents an HW device. - /***********************************************************************************/ - template - class IDeviceObject - { - public: - explicit IDeviceObject(void (*Out)(IDeviceObject*, T), void (*In)(IDeviceObject*, T)) - : fOut(Out), fIn(In) - { - } - - virtual ~IDeviceObject() = default; - - public: - IDeviceObject& operator=(const IDeviceObject&) = default; - IDeviceObject(const IDeviceObject&) = default; - - public: - virtual IDeviceObject& operator<<(T Data) - { - fOut(this, Data); - return *this; - } - - virtual IDeviceObject& operator>>(T Data) - { - fIn(this, Data); - return *this; - } - - virtual const char* Name() const - { - return "/dev/null"; - } - - operator bool() - { - return fOut && fIn; - } - - Bool operator!() - { - return !fOut || !fIn; - } - - protected: - Void (*fOut)(IDeviceObject*, T Data) = {nullptr}; - Void (*fIn)(IDeviceObject*, T Data) = {nullptr}; - }; - - /// - /// @brief Input Output abstract class. - /// Used mainly to communicate between OS to hardware. - /// - template - class IOBuf final - { - public: - explicit IOBuf(T dma_addr) - : fData(dma_addr) - { - // At least pass something valid when instancating this struct. - MUST_PASS(fData); - } - - IOBuf& operator=(const IOBuf&) = default; - IOBuf(const IOBuf&) = default; - - ~IOBuf() = default; - - public: - template - R operator->() const - { - return fData; - } - - template - R& operator[](Size index) const - { - return fData[index]; - } - - private: - T fData; - }; - - ///! @brief Device enum types. - enum - { - kDeviceTypeIDE, - kDeviceTypeEthernet, - kDeviceTypeWiFi, - kDeviceTypeFW, - kDeviceTypeBT, - kDeviceTypeRS232, - kDeviceTypeSCSI, - kDeviceTypeAHCI, - kDeviceTypeMBCI, - kDeviceTypeATA, - kDeviceTypeUSB, - kDeviceTypeMediaCtrl, // MM controller - kDeviceTypeCount, - }; -} // namespace Kernel +namespace Kernel { +template +class IDeviceObject; + +/***********************************************************************************/ +/// @brief Device contract interface, represents an HW device. +/***********************************************************************************/ +template +class IDeviceObject { + public: + explicit IDeviceObject(void (*Out)(IDeviceObject*, T), void (*In)(IDeviceObject*, T)) + : fOut(Out), fIn(In) {} + + virtual ~IDeviceObject() = default; + + public: + IDeviceObject& operator=(const IDeviceObject&) = default; + IDeviceObject(const IDeviceObject&) = default; + + public: + virtual IDeviceObject& operator<<(T Data) { + fOut(this, Data); + return *this; + } + + virtual IDeviceObject& operator>>(T Data) { + fIn(this, Data); + return *this; + } + + virtual const char* Name() const { return "/dev/null"; } + + operator bool() { return fOut && fIn; } + + Bool operator!() { return !fOut || !fIn; } + + protected: + Void (*fOut)(IDeviceObject*, T Data) = {nullptr}; + Void (*fIn)(IDeviceObject*, T Data) = {nullptr}; +}; + +/// +/// @brief Input Output abstract class. +/// Used mainly to communicate between OS to hardware. +/// +template +class IOBuf final { + public: + explicit IOBuf(T dma_addr) : fData(dma_addr) { + // At least pass something valid when instancating this struct. + MUST_PASS(fData); + } + + IOBuf& operator=(const IOBuf&) = default; + IOBuf(const IOBuf&) = default; + + ~IOBuf() = default; + + public: + template + R operator->() const { + return fData; + } + + template + R& operator[](Size index) const { + return fData[index]; + } + + private: + T fData; +}; + +///! @brief Device enum types. +enum { + kDeviceTypeIDE, + kDeviceTypeEthernet, + kDeviceTypeWiFi, + kDeviceTypeFW, + kDeviceTypeBT, + kDeviceTypeRS232, + kDeviceTypeSCSI, + kDeviceTypeAHCI, + kDeviceTypeMBCI, + kDeviceTypeATA, + kDeviceTypeUSB, + kDeviceTypeMediaCtrl, // MM controller + kDeviceTypeCount, +}; +} // namespace Kernel diff --git a/dev/kernel/KernelKit/DriveMgr.h b/dev/kernel/KernelKit/DriveMgr.h index 9dc8162b..e0bed8f5 100644 --- a/dev/kernel/KernelKit/DriveMgr.h +++ b/dev/kernel/KernelKit/DriveMgr.h @@ -1,191 +1,170 @@ /* ------------------------------------------- - Copyright (C) 2024-2025, Amlal El Mahrouss, all rights reserved. + Copyright (C) 2024-2025, Amlal El Mahrouss, all rights reserved. ------------------------------------------- */ #ifndef INC_DRIVE_MANAGER_H #define INC_DRIVE_MANAGER_H -#include #include #include #include #include +#include #include #include #include -#define kDriveMaxCount (4U) -#define kDriveSectorSz (512U) +#define kDriveMaxCount (4U) +#define kDriveSectorSz (512U) #define kDriveInvalidID (-1) -#define kDriveNameLen (32) +#define kDriveNameLen (32) #define drv_sector_cnt(SIZE, SECTOR_SZ) (((SIZE) + (SECTOR_SZ)) / (SECTOR_SZ)) -namespace Kernel -{ - enum - { - kInvalidDrive = -1, - - /// Storage types, combine with flags. - kBlockDevice = 0xAD, - kMassStorageDrive = 0xDA, - kFloppyDrive = 0xCD, - kOpticalDrive = 0xDC, // CD-ROM/DVD-ROM/Blu-Ray - kTapeDrive = 0xD7, - - /// Storage flags, combine with types. - kReadOnlyDrive = 0x10, // Read only drive - kEPMDrive = 0x11, // Explicit Partition Map. - kVEPMDrive = 0x12, // ESP w/ EPM partition. - kMBRDrive = 0x13, // PC classic partition scheme - kGPTDrive = 0x14, // PC new partition scheme - kUnformattedDrive = 0x15, - kStorageCount = 9, - }; - - /// @brief Media drive trait type. - struct DriveTrait final - { - Char fName[kDriveNameLen]; // /System, /boot, //./Devices/USB... - Int32 fKind; // fMassStorage, fFloppy, fOpticalDrive. - Int32 fFlags; // fReadOnly, fEPMDrive... - - /// @brief Packet drive (StorageKit compilant.) - struct DrivePacket final - { - VoidPtr fPacketContent{nullptr}; //! packet body. - Char fPacketMime[kDriveNameLen] = "*/*"; //! identify what we're sending. - SizeT fPacketSize{0UL}; //! packet size - UInt32 fPacketCRC32{0UL}; //! sanity crc, in case if good is set to false - Boolean fPacketGood{YES}; - Lba fPacketLba{0UL}; - Boolean fPacketReadOnly{NO}; - } fPacket; - - Lba fLbaStart{0}, fLbaEnd{0}; - SizeT fSectorSz{512}; - - Void (*fInput)(DrivePacket packet); - Void (*fOutput)(DrivePacket packet); - Void (*fVerify)(DrivePacket packet); - Void (*fInit)(DrivePacket packet); - const Char* (*fProtocol)(Void); - }; - - ///! drive as a device. - typedef DriveTrait* DriveTraitPtr; - - /** - * @brief Mounted drives interface. - * @note This class has all of it's drive set to nullptr, allocate them using - * GetAddressOf(index). - */ - class MountpointInterface final - { - public: - explicit MountpointInterface() = default; - ~MountpointInterface() = default; - - NE_COPY_DEFAULT(MountpointInterface) - - public: - DriveTrait& A() - { - return mA; - } - - DriveTrait& B() - { - return mB; - } - - DriveTrait& C() - { - return mC; - } - - DriveTrait& D() - { - return mD; - } - - enum - { - kDriveIndexA = 0, - kDriveIndexB, - kDriveIndexC, - kDriveIndexD, - kDriveIndexInvalid, - }; - - DriveTraitPtr GetAddressOf(const Int32& index) - { - err_local_get() = kErrorSuccess; - - switch (index) - { - case kDriveIndexA: - return &mA; - case kDriveIndexB: - return &mB; - case kDriveIndexC: - return &mC; - case kDriveIndexD: - return &mD; - default: { - err_local_get() = kErrorNoSuchDisk; - kout << "No such disc letter.\n"; - - break; - } - } - - return nullptr; - } - - private: - DriveTrait mA, mB, mC, mD; - }; - - /// @brief Unimplemented drive. - /// @param pckt the packet to read. - /// @return - Void io_drv_unimplemented(DriveTrait::DrivePacket* pckt) noexcept; - - /// @brief Gets the drive kind (ATA, SCSI, AHCI...) - /// @param void none. - /// @return the drive kind (ATA, Flash, NVM) - const Char* io_drv_kind(Void); - - /// @brief Makes a new drive. - /// @return the new drive as a trait. - DriveTrait io_construct_blank_drive(Void) noexcept; - - /// @brief Fetches the main drive. - /// @return the new drive as a trait. - DriveTrait io_construct_main_drive(Void) noexcept; - - namespace Detect - { - Void io_detect_drive(DriveTrait& trait); - } - - /// @brief Read from newfs disk. - /// @param Mnt mounted interface. - /// @param DrvTrait drive info - /// @param DrvIndex drive index. - /// @return - Int32 fs_ifs_read(MountpointInterface* Mnt, DriveTrait& DrvTrait, Int32 DrvIndex); - - /// @brief Write to ifs disk. - /// @param Mnt mounted interface. - /// @param DrvTrait drive info - /// @param DrvIndex drive index. - /// @return - Int32 fs_ifs_write(MountpointInterface* Mnt, DriveTrait& DrvTrait, Int32 DrvIndex); -} // namespace Kernel +namespace Kernel { +enum { + kInvalidDrive = -1, + + /// Storage types, combine with flags. + kBlockDevice = 0xAD, + kMassStorageDrive = 0xDA, + kFloppyDrive = 0xCD, + kOpticalDrive = 0xDC, // CD-ROM/DVD-ROM/Blu-Ray + kTapeDrive = 0xD7, + + /// Storage flags, combine with types. + kReadOnlyDrive = 0x10, // Read only drive + kEPMDrive = 0x11, // Explicit Partition Map. + kVEPMDrive = 0x12, // ESP w/ EPM partition. + kMBRDrive = 0x13, // PC classic partition scheme + kGPTDrive = 0x14, // PC new partition scheme + kUnformattedDrive = 0x15, + kStorageCount = 9, +}; + +/// @brief Media drive trait type. +struct DriveTrait final { + Char fName[kDriveNameLen]; // /System, /boot, //./Devices/USB... + Int32 fKind; // fMassStorage, fFloppy, fOpticalDrive. + Int32 fFlags; // fReadOnly, fEPMDrive... + + /// @brief Packet drive (StorageKit compilant.) + struct DrivePacket final { + VoidPtr fPacketContent{nullptr}; //! packet body. + Char fPacketMime[kDriveNameLen] = "*/*"; //! identify what we're sending. + SizeT fPacketSize{0UL}; //! packet size + UInt32 fPacketCRC32{0UL}; //! sanity crc, in case if good is set to false + Boolean fPacketGood{YES}; + Lba fPacketLba{0UL}; + Boolean fPacketReadOnly{NO}; + } fPacket; + + Lba fLbaStart{0}, fLbaEnd{0}; + SizeT fSectorSz{512}; + + Void (*fInput)(DrivePacket packet); + Void (*fOutput)(DrivePacket packet); + Void (*fVerify)(DrivePacket packet); + Void (*fInit)(DrivePacket packet); + const Char* (*fProtocol)(Void); +}; + +///! drive as a device. +typedef DriveTrait* DriveTraitPtr; + +/** + * @brief Mounted drives interface. + * @note This class has all of it's drive set to nullptr, allocate them using + * GetAddressOf(index). + */ +class MountpointInterface final { + public: + explicit MountpointInterface() = default; + ~MountpointInterface() = default; + + NE_COPY_DEFAULT(MountpointInterface) + + public: + DriveTrait& A() { return mA; } + + DriveTrait& B() { return mB; } + + DriveTrait& C() { return mC; } + + DriveTrait& D() { return mD; } + + enum { + kDriveIndexA = 0, + kDriveIndexB, + kDriveIndexC, + kDriveIndexD, + kDriveIndexInvalid, + }; + + DriveTraitPtr GetAddressOf(const Int32& index) { + err_local_get() = kErrorSuccess; + + switch (index) { + case kDriveIndexA: + return &mA; + case kDriveIndexB: + return &mB; + case kDriveIndexC: + return &mC; + case kDriveIndexD: + return &mD; + default: { + err_local_get() = kErrorNoSuchDisk; + kout << "No such disc letter.\n"; + + break; + } + } + + return nullptr; + } + + private: + DriveTrait mA, mB, mC, mD; +}; + +/// @brief Unimplemented drive. +/// @param pckt the packet to read. +/// @return +Void io_drv_unimplemented(DriveTrait::DrivePacket* pckt) noexcept; + +/// @brief Gets the drive kind (ATA, SCSI, AHCI...) +/// @param void none. +/// @return the drive kind (ATA, Flash, NVM) +const Char* io_drv_kind(Void); + +/// @brief Makes a new drive. +/// @return the new drive as a trait. +DriveTrait io_construct_blank_drive(Void) noexcept; + +/// @brief Fetches the main drive. +/// @return the new drive as a trait. +DriveTrait io_construct_main_drive(Void) noexcept; + +namespace Detect { + Void io_detect_drive(DriveTrait& trait); +} + +/// @brief Read from newfs disk. +/// @param Mnt mounted interface. +/// @param DrvTrait drive info +/// @param DrvIndex drive index. +/// @return +Int32 fs_ifs_read(MountpointInterface* Mnt, DriveTrait& DrvTrait, Int32 DrvIndex); + +/// @brief Write to ifs disk. +/// @param Mnt mounted interface. +/// @param DrvTrait drive info +/// @param DrvIndex drive index. +/// @return +Int32 fs_ifs_write(MountpointInterface* Mnt, DriveTrait& DrvTrait, Int32 DrvIndex); +} // namespace Kernel #endif /* ifndef INC_DRIVE_MANAGER_H */ diff --git a/dev/kernel/KernelKit/FileMgr.h b/dev/kernel/KernelKit/FileMgr.h index f4acdae9..465d0afb 100644 --- a/dev/kernel/KernelKit/FileMgr.h +++ b/dev/kernel/KernelKit/FileMgr.h @@ -1,9 +1,9 @@ /* ------------------------------------------- - Copyright (C) 2024-2025, Amlal El Mahrouss Labs, all rights reserved. + Copyright (C) 2024-2025, Amlal El Mahrouss Labs, all rights reserved. - File: FileMgr.h - Purpose: Kernel file manager. + File: FileMgr.h + Purpose: Kernel file manager. ------------------------------------------- */ @@ -11,10 +11,10 @@ Revision History: - 31/01/24: Update documentation (amlel) - 05/07/24: NeFS support, and fork support, updated constants and specs - as well. - 18/01/25: Patches to FileStream class. + 31/01/24: Update documentation (amlel) + 05/07/24: NeFS support, and fork support, updated constants and specs + as well. + 18/01/25: Patches to FileStream class. ------------------------------------------- */ @@ -26,21 +26,21 @@ #include #include -#include -#include #include -#include -#include +#include #include +#include #include +#include +#include /// @brief Filesystem manager, abstraction over mounted filesystem. /// Works like the VFS or IFS. -#define kRestrictR "r" -#define kRestrictRB "rb" -#define kRestrictW "w" -#define kRestrictWR "rw" +#define kRestrictR "r" +#define kRestrictRB "rb" +#define kRestrictW "w" +#define kRestrictWR "rw" #define kRestrictWRB "rwb" #define kRestrictMax (5U) @@ -48,343 +48,303 @@ #define node_cast(PTR) reinterpret_cast(PTR) /** - @note Refer to first enum. + @note Refer to first enum. */ -#define kFileOpsCount (4U) +#define kFileOpsCount (4U) #define kFileMimeGeneric "ne-application-kind/all" /** @brief invalid position. (n-pos) */ #define kNPos (SizeT)(-1); -namespace Kernel -{ - enum - { - kFileWriteAll = 100, - kFileReadAll = 101, - kFileReadChunk = 102, - kFileWriteChunk = 103, - kFileIOCnt = (kFileWriteChunk - kFileWriteAll) + 1, - // file flags - kFileFlagRsrc = 104, - kFileFlagData = 105, - }; - - typedef VoidPtr NodePtr; - - /** - @brief Filesystem Mgr Interface class - @brief Used to provide common I/O for a specific filesystem. +namespace Kernel { +enum { + kFileWriteAll = 100, + kFileReadAll = 101, + kFileReadChunk = 102, + kFileWriteChunk = 103, + kFileIOCnt = (kFileWriteChunk - kFileWriteAll) + 1, + // file flags + kFileFlagRsrc = 104, + kFileFlagData = 105, +}; + +typedef VoidPtr NodePtr; + +/** +@brief Filesystem Mgr Interface class +@brief Used to provide common I/O for a specific filesystem. */ - class IFilesystemMgr - { - public: - explicit IFilesystemMgr() = default; - virtual ~IFilesystemMgr() = default; - - public: - NE_COPY_DEFAULT(IFilesystemMgr) - - public: - /// @brief Mounts a new filesystem into an active state. - /// @param interface the filesystem interface - /// @return - static bool Mount(IFilesystemMgr* interface); - - /// @brief Unmounts the active filesystem - /// @return - static IFilesystemMgr* Unmount(); - - /// @brief Getter, gets the active filesystem. - /// @return - static IFilesystemMgr* GetMounted(); - - public: - virtual NodePtr Create(_Input const Char* path) = 0; - virtual NodePtr CreateAlias(_Input const Char* path) = 0; - virtual NodePtr CreateDirectory(_Input const Char* path) = 0; - virtual NodePtr CreateSwapFile(const Char* path) = 0; - - public: - virtual bool Remove(_Input const Char* path) = 0; - - public: - virtual NodePtr Open(_Input const Char* path, _Input const Char* r) = 0; - - public: - virtual Void Write(_Input NodePtr node, _Input VoidPtr data, _Input Int32 flags, _Input SizeT size) = 0; - - virtual _Output VoidPtr Read(_Input NodePtr node, - _Input Int32 flags, - _Input SizeT sz) = 0; - - virtual Void Write(_Input const Char* name, - _Input NodePtr node, - _Input VoidPtr data, - _Input Int32 flags, - _Input SizeT size) = 0; - - virtual _Output VoidPtr Read(_Input const Char* name, - _Input NodePtr node, - _Input Int32 flags, - _Input SizeT sz) = 0; - - public: - virtual bool Seek(_Input NodePtr node, _Input SizeT off) = 0; - - public: - virtual SizeT Tell(_Input NodePtr node) = 0; - virtual bool Rewind(_Input NodePtr node) = 0; - }; +class IFilesystemMgr { + public: + explicit IFilesystemMgr() = default; + virtual ~IFilesystemMgr() = default; + + public: + NE_COPY_DEFAULT(IFilesystemMgr) + + public: + /// @brief Mounts a new filesystem into an active state. + /// @param interface the filesystem interface + /// @return + static bool Mount(IFilesystemMgr* interface); + + /// @brief Unmounts the active filesystem + /// @return + static IFilesystemMgr* Unmount(); + + /// @brief Getter, gets the active filesystem. + /// @return + static IFilesystemMgr* GetMounted(); + + public: + virtual NodePtr Create(_Input const Char* path) = 0; + virtual NodePtr CreateAlias(_Input const Char* path) = 0; + virtual NodePtr CreateDirectory(_Input const Char* path) = 0; + virtual NodePtr CreateSwapFile(const Char* path) = 0; + + public: + virtual bool Remove(_Input const Char* path) = 0; + + public: + virtual NodePtr Open(_Input const Char* path, _Input const Char* r) = 0; + + public: + virtual Void Write(_Input NodePtr node, _Input VoidPtr data, _Input Int32 flags, + _Input SizeT size) = 0; + + virtual _Output VoidPtr Read(_Input NodePtr node, _Input Int32 flags, _Input SizeT sz) = 0; + + virtual Void Write(_Input const Char* name, _Input NodePtr node, _Input VoidPtr data, + _Input Int32 flags, _Input SizeT size) = 0; + + virtual _Output VoidPtr Read(_Input const Char* name, _Input NodePtr node, _Input Int32 flags, + _Input SizeT sz) = 0; + + public: + virtual bool Seek(_Input NodePtr node, _Input SizeT off) = 0; + + public: + virtual SizeT Tell(_Input NodePtr node) = 0; + virtual bool Rewind(_Input NodePtr node) = 0; +}; #ifdef __FSKIT_INCLUDES_NEFS__ - /** - * @brief Based of IFilesystemMgr, takes care of managing NeFS - * disks. - */ - class NeFileSystemMgr final : public IFilesystemMgr - { - public: - explicit NeFileSystemMgr(); - ~NeFileSystemMgr() override; - - public: - NE_COPY_DEFAULT(NeFileSystemMgr) - - public: - NodePtr Create(const Char* path) override; - NodePtr CreateAlias(const Char* path) override; - NodePtr CreateDirectory(const Char* path) override; - NodePtr CreateSwapFile(const Char* path) override; - - public: - bool Remove(_Input const Char* path) override; - NodePtr Open(_Input const Char* path, _Input const Char* r) override; - Void Write(_Input NodePtr node, _Input VoidPtr data, _Input Int32 flags, _Input SizeT sz) override; - VoidPtr Read(_Input NodePtr node, _Input Int32 flags, _Input SizeT sz) override; - bool Seek(_Input NodePtr node, _Input SizeT off) override; - SizeT Tell(_Input NodePtr node) override; - bool Rewind(_Input NodePtr node) override; - - Void Write(_Input const Char* name, - _Input NodePtr node, - _Input VoidPtr data, - _Input Int32 flags, - _Input SizeT size) override; - - _Output VoidPtr Read(_Input const Char* name, - _Input NodePtr node, - _Input Int32 flags, - _Input SizeT sz) override; - - public: - /// @brief Get NeFS parser class. - /// @return The filesystem parser class. - NeFileSystemParser* GetParser() noexcept; - - private: - NeFileSystemParser* mParser{nullptr}; - }; - -#endif // ifdef __FSKIT_INCLUDES_NEFS__ - - /** - * FileStream class. - * @tparam Encoding file encoding (char, wchar_t...) - * @tparam FSClass Filesystem contract who takes care of it. - */ - template - class FileStream final - { - public: - explicit FileStream(const Encoding* path, const Encoding* restrict_type); - ~FileStream(); - - public: - FileStream& operator=(const FileStream&); - FileStream(const FileStream&); - - public: - ErrorOr Write(SizeT offset, const VoidPtr data, SizeT len) noexcept - { - if (this->fFileRestrict != kFileMgrRestrictReadWrite && - this->fFileRestrict != kFileMgrRestrictReadWriteBinary && - this->fFileRestrict != kFileMgrRestrictWrite && - this->fFileRestrict != kFileMgrRestrictWriteBinary) - return ErrorOr(kErrorInvalidData); - - if (data == nullptr) - return ErrorOr(kErrorInvalidData); - - auto man = FSClass::GetMounted(); - - if (man) - { - man->Write(offset, fFile, data, len); - return ErrorOr(0); - } - - return ErrorOr(kErrorInvalidData); - } - - ErrorOr Write(const Char* name, const VoidPtr data, SizeT len) noexcept - { - if (this->fFileRestrict != kFileMgrRestrictReadWrite && - this->fFileRestrict != kFileMgrRestrictReadWriteBinary && - this->fFileRestrict != kFileMgrRestrictWrite && - this->fFileRestrict != kFileMgrRestrictWriteBinary) - return ErrorOr(kErrorInvalidData); - - if (data == nullptr) - return ErrorOr(kErrorInvalidData); - - auto man = FSClass::GetMounted(); - - if (man) - { - man->Write(name, fFile, data, 0, len); - return ErrorOr(0); - } - - return ErrorOr(kErrorInvalidData); - } - - VoidPtr Read(const Char* name, SizeT sz) noexcept - { - if (this->fFileRestrict != kFileMgrRestrictReadWrite && - this->fFileRestrict != kFileMgrRestrictReadWriteBinary && - this->fFileRestrict != kFileMgrRestrictRead && - this->fFileRestrict != kFileMgrRestrictReadBinary) - return nullptr; - - NE_UNUSED(sz); - - auto man = FSClass::GetMounted(); - - if (man) - { - VoidPtr ret = man->Read(name, fFile, kFileReadAll, 0); - return ret; - } - - return nullptr; - } - - VoidPtr Read(SizeT offset, SizeT sz) - { - if (this->fFileRestrict != kFileMgrRestrictReadWrite && - this->fFileRestrict != kFileMgrRestrictReadWriteBinary && - this->fFileRestrict != kFileMgrRestrictRead && - this->fFileRestrict != kFileMgrRestrictReadBinary) - return nullptr; - - auto man = FSClass::GetMounted(); - - if (man) - { - man->Seek(fFile, offset); - auto ret = man->Read(fFile, kFileReadChunk, sz); - - return ret; - } - - return nullptr; - } - - public: - /// @brief Leak node pointer. - /// @return The node pointer. - NodePtr Leak() - { - return fFile; - } - - /// @brief Leak MIME. - /// @return The MIME. - Char* MIME() noexcept - { - return const_cast(fMime); - } - - enum - { - kFileMgrRestrictRead, - kFileMgrRestrictReadBinary, - kFileMgrRestrictWrite, - kFileMgrRestrictWriteBinary, - kFileMgrRestrictReadWrite, - kFileMgrRestrictReadWriteBinary, - }; - - private: - NodePtr fFile{nullptr}; - Int32 fFileRestrict{kFileMgrRestrictReadBinary}; - const Char* fMime{kFileMimeGeneric}; - }; - - using FileStreamUTF8 = FileStream; - using FileStreamUTF16 = FileStream; - - typedef UInt64 CursorType; - - inline static const auto kRestrictStrLen = 8U; - - /// @brief restrict information about the file descriptor. - struct FileRestrictKind final - { - Char fRestrict[kRestrictStrLen]; - Int32 fMappedTo; - }; - - /// @brief constructor - template - inline FileStream::FileStream(const Encoding* path, - const Encoding* restrict_type) - : fFile(Class::GetMounted()->Open(path, restrict_type)) - { - SizeT kRestrictCount = kRestrictMax; - const FileRestrictKind kRestrictList[] = { - { - .fRestrict = kRestrictR, - .fMappedTo = kFileMgrRestrictRead, - }, - { - .fRestrict = kRestrictRB, - .fMappedTo = kFileMgrRestrictReadBinary, - }, - { - .fRestrict = kRestrictWRB, - .fMappedTo = kFileMgrRestrictReadWriteBinary, - }, - { - .fRestrict = kRestrictW, - .fMappedTo = kFileMgrRestrictWrite, - }, - { - .fRestrict = kRestrictWR, - .fMappedTo = kFileMgrRestrictReadWrite, - }}; - - for (SizeT index = 0; index < kRestrictCount; ++index) - { - if (rt_string_cmp(restrict_type, kRestrictList[index].fRestrict, - rt_string_len(kRestrictList[index].fRestrict)) == 0) - { - fFileRestrict = kRestrictList[index].fMappedTo; - break; - } - } - - kout << "new file: " << path << ".\r"; - } - - /// @brief destructor of the file stream. - template - inline FileStream::~FileStream() - { - mm_delete_heap(fFile); - } -} // namespace Kernel - -#endif // ifndef INC_FILEMGR_H +/** + * @brief Based of IFilesystemMgr, takes care of managing NeFS + * disks. + */ +class NeFileSystemMgr final : public IFilesystemMgr { + public: + explicit NeFileSystemMgr(); + ~NeFileSystemMgr() override; + + public: + NE_COPY_DEFAULT(NeFileSystemMgr) + + public: + NodePtr Create(const Char* path) override; + NodePtr CreateAlias(const Char* path) override; + NodePtr CreateDirectory(const Char* path) override; + NodePtr CreateSwapFile(const Char* path) override; + + public: + bool Remove(_Input const Char* path) override; + NodePtr Open(_Input const Char* path, _Input const Char* r) override; + Void Write(_Input NodePtr node, _Input VoidPtr data, _Input Int32 flags, + _Input SizeT sz) override; + VoidPtr Read(_Input NodePtr node, _Input Int32 flags, _Input SizeT sz) override; + bool Seek(_Input NodePtr node, _Input SizeT off) override; + SizeT Tell(_Input NodePtr node) override; + bool Rewind(_Input NodePtr node) override; + + Void Write(_Input const Char* name, _Input NodePtr node, _Input VoidPtr data, _Input Int32 flags, + _Input SizeT size) override; + + _Output VoidPtr Read(_Input const Char* name, _Input NodePtr node, _Input Int32 flags, + _Input SizeT sz) override; + + public: + /// @brief Get NeFS parser class. + /// @return The filesystem parser class. + NeFileSystemParser* GetParser() noexcept; + + private: + NeFileSystemParser* mParser{nullptr}; +}; + +#endif // ifdef __FSKIT_INCLUDES_NEFS__ + +/** + * FileStream class. + * @tparam Encoding file encoding (char, wchar_t...) + * @tparam FSClass Filesystem contract who takes care of it. + */ +template +class FileStream final { + public: + explicit FileStream(const Encoding* path, const Encoding* restrict_type); + ~FileStream(); + + public: + FileStream& operator=(const FileStream&); + FileStream(const FileStream&); + + public: + ErrorOr Write(SizeT offset, const VoidPtr data, SizeT len) noexcept { + if (this->fFileRestrict != kFileMgrRestrictReadWrite && + this->fFileRestrict != kFileMgrRestrictReadWriteBinary && + this->fFileRestrict != kFileMgrRestrictWrite && + this->fFileRestrict != kFileMgrRestrictWriteBinary) + return ErrorOr(kErrorInvalidData); + + if (data == nullptr) return ErrorOr(kErrorInvalidData); + + auto man = FSClass::GetMounted(); + + if (man) { + man->Write(offset, fFile, data, len); + return ErrorOr(0); + } + + return ErrorOr(kErrorInvalidData); + } + + ErrorOr Write(const Char* name, const VoidPtr data, SizeT len) noexcept { + if (this->fFileRestrict != kFileMgrRestrictReadWrite && + this->fFileRestrict != kFileMgrRestrictReadWriteBinary && + this->fFileRestrict != kFileMgrRestrictWrite && + this->fFileRestrict != kFileMgrRestrictWriteBinary) + return ErrorOr(kErrorInvalidData); + + if (data == nullptr) return ErrorOr(kErrorInvalidData); + + auto man = FSClass::GetMounted(); + + if (man) { + man->Write(name, fFile, data, 0, len); + return ErrorOr(0); + } + + return ErrorOr(kErrorInvalidData); + } + + VoidPtr Read(const Char* name, SizeT sz) noexcept { + if (this->fFileRestrict != kFileMgrRestrictReadWrite && + this->fFileRestrict != kFileMgrRestrictReadWriteBinary && + this->fFileRestrict != kFileMgrRestrictRead && + this->fFileRestrict != kFileMgrRestrictReadBinary) + return nullptr; + + NE_UNUSED(sz); + + auto man = FSClass::GetMounted(); + + if (man) { + VoidPtr ret = man->Read(name, fFile, kFileReadAll, 0); + return ret; + } + + return nullptr; + } + + VoidPtr Read(SizeT offset, SizeT sz) { + if (this->fFileRestrict != kFileMgrRestrictReadWrite && + this->fFileRestrict != kFileMgrRestrictReadWriteBinary && + this->fFileRestrict != kFileMgrRestrictRead && + this->fFileRestrict != kFileMgrRestrictReadBinary) + return nullptr; + + auto man = FSClass::GetMounted(); + + if (man) { + man->Seek(fFile, offset); + auto ret = man->Read(fFile, kFileReadChunk, sz); + + return ret; + } + + return nullptr; + } + + public: + /// @brief Leak node pointer. + /// @return The node pointer. + NodePtr Leak() { return fFile; } + + /// @brief Leak MIME. + /// @return The MIME. + Char* MIME() noexcept { return const_cast(fMime); } + + enum { + kFileMgrRestrictRead, + kFileMgrRestrictReadBinary, + kFileMgrRestrictWrite, + kFileMgrRestrictWriteBinary, + kFileMgrRestrictReadWrite, + kFileMgrRestrictReadWriteBinary, + }; + + private: + NodePtr fFile{nullptr}; + Int32 fFileRestrict{kFileMgrRestrictReadBinary}; + const Char* fMime{kFileMimeGeneric}; +}; + +using FileStreamUTF8 = FileStream; +using FileStreamUTF16 = FileStream; + +typedef UInt64 CursorType; + +inline static const auto kRestrictStrLen = 8U; + +/// @brief restrict information about the file descriptor. +struct FileRestrictKind final { + Char fRestrict[kRestrictStrLen]; + Int32 fMappedTo; +}; + +/// @brief constructor +template +inline FileStream::FileStream(const Encoding* path, const Encoding* restrict_type) + : fFile(Class::GetMounted()->Open(path, restrict_type)) { + SizeT kRestrictCount = kRestrictMax; + const FileRestrictKind kRestrictList[] = {{ + .fRestrict = kRestrictR, + .fMappedTo = kFileMgrRestrictRead, + }, + { + .fRestrict = kRestrictRB, + .fMappedTo = kFileMgrRestrictReadBinary, + }, + { + .fRestrict = kRestrictWRB, + .fMappedTo = kFileMgrRestrictReadWriteBinary, + }, + { + .fRestrict = kRestrictW, + .fMappedTo = kFileMgrRestrictWrite, + }, + { + .fRestrict = kRestrictWR, + .fMappedTo = kFileMgrRestrictReadWrite, + }}; + + for (SizeT index = 0; index < kRestrictCount; ++index) { + if (rt_string_cmp(restrict_type, kRestrictList[index].fRestrict, + rt_string_len(kRestrictList[index].fRestrict)) == 0) { + fFileRestrict = kRestrictList[index].fMappedTo; + break; + } + } + + kout << "new file: " << path << ".\r"; +} + +/// @brief destructor of the file stream. +template +inline FileStream::~FileStream() { + mm_delete_heap(fFile); +} +} // namespace Kernel + +#endif // ifndef INC_FILEMGR_H diff --git a/dev/kernel/KernelKit/HardwareThreadScheduler.h b/dev/kernel/KernelKit/HardwareThreadScheduler.h index 4d2ebc73..4f7746ef 100644 --- a/dev/kernel/KernelKit/HardwareThreadScheduler.h +++ b/dev/kernel/KernelKit/HardwareThreadScheduler.h @@ -1,6 +1,6 @@ /* ------------------------------------------- - Copyright (C) 2024-2025, Amlal El Mahrouss, all rights reserved. + Copyright (C) 2024-2025, Amlal El Mahrouss, all rights reserved. ------------------------------------------- */ @@ -16,134 +16,121 @@ #define kMaxAPInsideSched (8U) -namespace Kernel -{ - class HardwareThread; - class HardwareThreadScheduler; - - using ThreadID = UInt32; - - enum ThreadKind - { - kAPInvalid, - kAPSystemReserved, // System reserved thread, well user can't use it - kAPStandard, // user thread, cannot be used by Kernel - kAPRealTime, // fallback thread, cannot be used by user if not clear or - // used by Kernel. - kAPBoot, // The core we booted from, the mama. - kAPCount, - }; - - typedef enum ThreadKind ThreadKind; - typedef ThreadID ThreadID; - - /***********************************************************************************/ - /// - /// \name HardwareThread - /// \brief Abstraction over the CPU's core, used to run processes or threads. - /// - /***********************************************************************************/ - - class HardwareThread final - { - public: - explicit HardwareThread(); - ~HardwareThread(); - - public: - NE_COPY_DEFAULT(HardwareThread) - - public: - operator bool(); - - public: - void Wake(const BOOL wakeup = false) noexcept; - void Busy(const BOOL busy = false) noexcept; - - public: - BOOL Switch(VoidPtr image, Ptr8 stack_ptr, HAL::StackFramePtr frame, const ThreadID& pid); - BOOL IsWakeup() noexcept; - - public: - HAL::StackFramePtr StackFrame() noexcept; - const ThreadKind& Kind() noexcept; - bool IsBusy() noexcept; - const ThreadID& ID() noexcept; - - private: - HAL::StackFramePtr fStack{nullptr}; - ThreadKind fKind{ThreadKind::kAPStandard}; - ThreadID fID{0}; - ThreadID fPID{0}; - Bool fWakeup{NO}; - Bool fBusy{NO}; - UInt64 fPTime{0}; - - private: - friend class HardwareThreadScheduler; - friend class UserProcessHelper; - }; - - /// - /// \name HardwareThreadScheduler - /// \brief Class to manage the thread scheduling. - /// - - class HardwareThreadScheduler final : public ISchedulable - { - private: - friend class UserProcessHelper; - - public: - explicit HardwareThreadScheduler(); - ~HardwareThreadScheduler(); - NE_COPY_DEFAULT(HardwareThreadScheduler) - - public: - HAL::StackFramePtr Leak() noexcept; - - public: - Ref operator[](SizeT idx); - bool operator!() noexcept; - operator bool() noexcept; - - Bool IsUser() override - { - return Yes; - } - - Bool IsKernel() override - { - return No; - } - - Bool HasMP() override - { - return kHandoverHeader->f_HardwareTables.f_MultiProcessingEnabled; - } - - public: - /// @brief Shared instance of the MP Mgr. - /// @return the reference to the mp manager class. - STATIC HardwareThreadScheduler& The(); - - public: - /// @brief Returns the amount of threads present in the system. - /// @returns SizeT the amount of cores present. - SizeT Capacity() noexcept; - - private: - Array fThreadList; - ThreadID fCurrentThread{0}; - }; - - /// @brief wakes up thread. - /// wakes up thread from hang. - Void mp_wakeup_thread(HAL::StackFramePtr stack); - - /// @brief makes thread sleep. - /// hooks and hangs thread to prevent code from executing. - Void mp_hang_thread(HAL::StackFramePtr stack); -} // namespace Kernel - -#endif // !__INC_MP_MANAGER_H__ +namespace Kernel { +class HardwareThread; +class HardwareThreadScheduler; + +using ThreadID = UInt32; + +enum ThreadKind { + kAPInvalid, + kAPSystemReserved, // System reserved thread, well user can't use it + kAPStandard, // user thread, cannot be used by Kernel + kAPRealTime, // fallback thread, cannot be used by user if not clear or + // used by Kernel. + kAPBoot, // The core we booted from, the mama. + kAPCount, +}; + +typedef enum ThreadKind ThreadKind; +typedef ThreadID ThreadID; + +/***********************************************************************************/ +/// +/// \name HardwareThread +/// \brief Abstraction over the CPU's core, used to run processes or threads. +/// +/***********************************************************************************/ + +class HardwareThread final { + public: + explicit HardwareThread(); + ~HardwareThread(); + + public: + NE_COPY_DEFAULT(HardwareThread) + + public: + operator bool(); + + public: + void Wake(const BOOL wakeup = false) noexcept; + void Busy(const BOOL busy = false) noexcept; + + public: + BOOL Switch(VoidPtr image, Ptr8 stack_ptr, HAL::StackFramePtr frame, const ThreadID& pid); + BOOL IsWakeup() noexcept; + + public: + HAL::StackFramePtr StackFrame() noexcept; + const ThreadKind& Kind() noexcept; + bool IsBusy() noexcept; + const ThreadID& ID() noexcept; + + private: + HAL::StackFramePtr fStack{nullptr}; + ThreadKind fKind{ThreadKind::kAPStandard}; + ThreadID fID{0}; + ThreadID fPID{0}; + Bool fWakeup{NO}; + Bool fBusy{NO}; + UInt64 fPTime{0}; + + private: + friend class HardwareThreadScheduler; + friend class UserProcessHelper; +}; + +/// +/// \name HardwareThreadScheduler +/// \brief Class to manage the thread scheduling. +/// + +class HardwareThreadScheduler final : public ISchedulable { + private: + friend class UserProcessHelper; + + public: + explicit HardwareThreadScheduler(); + ~HardwareThreadScheduler(); + NE_COPY_DEFAULT(HardwareThreadScheduler) + + public: + HAL::StackFramePtr Leak() noexcept; + + public: + Ref operator[](SizeT idx); + bool operator!() noexcept; + operator bool() noexcept; + + Bool IsUser() override { return Yes; } + + Bool IsKernel() override { return No; } + + Bool HasMP() override { return kHandoverHeader->f_HardwareTables.f_MultiProcessingEnabled; } + + public: + /// @brief Shared instance of the MP Mgr. + /// @return the reference to the mp manager class. + STATIC HardwareThreadScheduler& The(); + + public: + /// @brief Returns the amount of threads present in the system. + /// @returns SizeT the amount of cores present. + SizeT Capacity() noexcept; + + private: + Array fThreadList; + ThreadID fCurrentThread{0}; +}; + +/// @brief wakes up thread. +/// wakes up thread from hang. +Void mp_wakeup_thread(HAL::StackFramePtr stack); + +/// @brief makes thread sleep. +/// hooks and hangs thread to prevent code from executing. +Void mp_hang_thread(HAL::StackFramePtr stack); +} // namespace Kernel + +#endif // !__INC_MP_MANAGER_H__ diff --git a/dev/kernel/KernelKit/IDylibObject.h b/dev/kernel/KernelKit/IDylibObject.h index 52c55bf5..7a7cd913 100644 --- a/dev/kernel/KernelKit/IDylibObject.h +++ b/dev/kernel/KernelKit/IDylibObject.h @@ -9,40 +9,34 @@ #pragma once -#include #include +#include #define NE_DYLIB_OBJECT : public IDylibObject -namespace Kernel -{ - /// @brief Dylib class object. A handle to a shared library. - class IDylibObject - { - public: - explicit IDylibObject() = default; - virtual ~IDylibObject() = default; - - struct DLL_TRAITS final - { - VoidPtr ImageObject{nullptr}; - VoidPtr ImageEntrypointOffset{nullptr}; - - Bool IsValid() - { - return ImageObject && ImageEntrypointOffset; - } - }; - - NE_COPY_DEFAULT(IDylibObject) - - virtual DLL_TRAITS** GetAddressOf() = 0; - virtual DLL_TRAITS* Get() = 0; - - virtual Void Mount(DLL_TRAITS* to_mount) = 0; - virtual Void Unmount() = 0; - }; - - /// @brief Pure implementation, missing method/function handler. - EXTERN_C void __zka_pure_call(void); -} // namespace Kernel +namespace Kernel { +/// @brief Dylib class object. A handle to a shared library. +class IDylibObject { + public: + explicit IDylibObject() = default; + virtual ~IDylibObject() = default; + + struct DLL_TRAITS final { + VoidPtr ImageObject{nullptr}; + VoidPtr ImageEntrypointOffset{nullptr}; + + Bool IsValid() { return ImageObject && ImageEntrypointOffset; } + }; + + NE_COPY_DEFAULT(IDylibObject) + + virtual DLL_TRAITS** GetAddressOf() = 0; + virtual DLL_TRAITS* Get() = 0; + + virtual Void Mount(DLL_TRAITS* to_mount) = 0; + virtual Void Unmount() = 0; +}; + +/// @brief Pure implementation, missing method/function handler. +EXTERN_C void __zka_pure_call(void); +} // namespace Kernel diff --git a/dev/kernel/KernelKit/IPEFDylibObject.h b/dev/kernel/KernelKit/IPEFDylibObject.h index a708fb6c..4031bd85 100644 --- a/dev/kernel/KernelKit/IPEFDylibObject.h +++ b/dev/kernel/KernelKit/IPEFDylibObject.h @@ -10,97 +10,77 @@ #ifndef __KERNELKIT_SHARED_OBJECT_H__ #define __KERNELKIT_SHARED_OBJECT_H__ +#include #include -#include #include #include -#include +#include + +namespace Kernel { +/** + * @brief Shared Library class + * Load library from this class + */ +class IPEFDylibObject final NE_DYLIB_OBJECT { + public: + explicit IPEFDylibObject() = default; + ~IPEFDylibObject() = default; + + public: + NE_COPY_DEFAULT(IPEFDylibObject) + + private: + DLL_TRAITS* fMounted{nullptr}; + + public: + DLL_TRAITS** GetAddressOf() { return &fMounted; } + + DLL_TRAITS* Get() { return fMounted; } + + public: + void Mount(DLL_TRAITS* to_mount) { + if (!to_mount || !to_mount->ImageObject) return; + + fMounted = to_mount; + + if (fLoader && to_mount) { + delete fLoader; + fLoader = nullptr; + } + + if (!fLoader) { + fLoader = new PEFLoader(fMounted->ImageObject); + } + } + + void Unmount() { + if (fMounted) fMounted = nullptr; + }; + + template + SymbolType Load(const Char* symbol_name, SizeT len, Int32 kind) { + if (symbol_name == nullptr || *symbol_name == 0) return nullptr; + if (len > kPathLen || len < 1) return nullptr; + + auto ret = reinterpret_cast(fLoader->FindSymbol(symbol_name, kind)); + + if (!ret) { + if (kind == kPefCode) return (VoidPtr) &__zka_pure_call; + + return nullptr; + } + + return ret; + } + + private: + PEFLoader* fLoader{nullptr}; +}; + +typedef IPEFDylibObject* IDylibRef; -namespace Kernel -{ - /** - * @brief Shared Library class - * Load library from this class - */ - class IPEFDylibObject final NE_DYLIB_OBJECT - { - public: - explicit IPEFDylibObject() = default; - ~IPEFDylibObject() = default; - - public: - NE_COPY_DEFAULT(IPEFDylibObject) - - private: - DLL_TRAITS* fMounted{nullptr}; - - public: - DLL_TRAITS** GetAddressOf() - { - return &fMounted; - } - - DLL_TRAITS* Get() - { - return fMounted; - } - - public: - void Mount(DLL_TRAITS* to_mount) - { - if (!to_mount || !to_mount->ImageObject) - return; - - fMounted = to_mount; - - if (fLoader && to_mount) - { - delete fLoader; - fLoader = nullptr; - } - - if (!fLoader) - { - fLoader = new PEFLoader(fMounted->ImageObject); - } - } - - void Unmount() - { - if (fMounted) - fMounted = nullptr; - }; - - template - SymbolType Load(const Char* symbol_name, SizeT len, Int32 kind) - { - if (symbol_name == nullptr || *symbol_name == 0) - return nullptr; - if (len > kPathLen || len < 1) - return nullptr; - - auto ret = - reinterpret_cast(fLoader->FindSymbol(symbol_name, kind)); - - if (!ret) - { - if (kind == kPefCode) - return (VoidPtr)&__zka_pure_call; - - return nullptr; - } - - return ret; - } - - private: - PEFLoader* fLoader{nullptr}; - }; - - typedef IPEFDylibObject* IDylibRef; - - EXTERN_C IDylibRef rtl_init_dylib_pef(USER_PROCESS& header); - EXTERN_C Void rtl_fini_dylib_pef(USER_PROCESS& header, IDylibRef lib, Bool* successful); -} // namespace Kernel +EXTERN_C IDylibRef rtl_init_dylib_pef(USER_PROCESS& header); +EXTERN_C Void rtl_fini_dylib_pef(USER_PROCESS& header, IDylibRef lib, Bool* successful); +} // namespace Kernel #endif /* ifndef __KERNELKIT_SHARED_OBJECT_H__ */ diff --git a/dev/kernel/KernelKit/KPC.h b/dev/kernel/KernelKit/KPC.h index 67bbea81..e195d5ad 100644 --- a/dev/kernel/KernelKit/KPC.h +++ b/dev/kernel/KernelKit/KPC.h @@ -1,6 +1,6 @@ /* ------------------------------------------- - Copyright (C) 2024-2025, Amlal El Mahrouss, all rights reserved. + Copyright (C) 2024-2025, Amlal El Mahrouss, all rights reserved. ------------------------------------------- */ @@ -11,57 +11,60 @@ /// @file KPC.h /// @brief Kernel Procedure Code. -#define err_local_ok() (Kernel::UserProcessScheduler::The().CurrentProcess().Leak().GetLocalCode() == Kernel::kErrorSuccess) -#define err_local_fail() (Kernel::UserProcessScheduler::The().CurrentProcess().Leak().GetLocalCode() != Kernel::kErrorSuccess) -#define err_local_get() (Kernel::UserProcessScheduler::The().CurrentProcess().Leak().GetLocalCode()) +#define err_local_ok() \ + (Kernel::UserProcessScheduler::The().CurrentProcess().Leak().GetLocalCode() == \ + Kernel::kErrorSuccess) +#define err_local_fail() \ + (Kernel::UserProcessScheduler::The().CurrentProcess().Leak().GetLocalCode() != \ + Kernel::kErrorSuccess) +#define err_local_get() (Kernel::UserProcessScheduler::The().CurrentProcess().Leak().GetLocalCode()) -#define err_global_ok() (Kernel::kErrorLocalNumber == Kernel::kErrorSuccess) +#define err_global_ok() (Kernel::kErrorLocalNumber == Kernel::kErrorSuccess) #define err_global_fail() (Kernel::kErrorLocalNumber != Kernel::kErrorSuccess) -#define err_global_get() (Kernel::kErrorLocalNumber) +#define err_global_get() (Kernel::kErrorLocalNumber) -namespace Kernel -{ - typedef Int32 KPCError; +namespace Kernel { +typedef Int32 KPCError; - inline KPCError kErrorLocalNumber = 0UL; +inline KPCError kErrorLocalNumber = 0UL; - inline constexpr KPCError kErrorSuccess = 0; - inline constexpr KPCError kErrorExecutable = 33; - inline constexpr KPCError kErrorExecutableLib = 34; - inline constexpr KPCError kErrorFileNotFound = 35; - inline constexpr KPCError kErrorDirectoryNotFound = 36; - inline constexpr KPCError kErrorDiskReadOnly = 37; - inline constexpr KPCError kErrorDiskIsFull = 38; - inline constexpr KPCError kErrorProcessFault = 39; - inline constexpr KPCError kErrorSocketHangUp = 40; - inline constexpr KPCError kErrorThreadLocalStorage = 41; - inline constexpr KPCError kErrorMath = 42; - inline constexpr KPCError kErrorNoNetwork = 43; - inline constexpr KPCError kErrorHeapOutOfMemory = 44; - inline constexpr KPCError kErrorNoSuchDisk = 45; - inline constexpr KPCError kErrorFileExists = 46; - inline constexpr KPCError kErrorFormatFailed = 47; - inline constexpr KPCError kErrorNetworkTimeout = 48; - inline constexpr KPCError kErrorInternal = 49; - inline constexpr KPCError kErrorForkAlreadyExists = 50; - inline constexpr KPCError kErrorOutOfTeamSlot = 51; - inline constexpr KPCError kErrorHeapNotPresent = 52; - inline constexpr KPCError kErrorNoEntrypoint = 53; - inline constexpr KPCError kErrorDiskIsCorrupted = 54; - inline constexpr KPCError kErrorDisk = 55; - inline constexpr KPCError kErrorInvalidData = 56; - inline constexpr KPCError kErrorAsync = 57; - inline constexpr KPCError kErrorNonBlocking = 58; - inline constexpr KPCError kErrorIPC = 59; - inline constexpr KPCError kErrorSign = 60; - inline constexpr KPCError kErrorInvalidCreds = 61; - inline constexpr KPCError kErrorCDTrayBroken = 62; - inline constexpr KPCError kErrorUnrecoverableDisk = 63; - inline constexpr KPCError kErrorFileLocked = 64; - inline constexpr KPCError kErrorUnimplemented = -1; +inline constexpr KPCError kErrorSuccess = 0; +inline constexpr KPCError kErrorExecutable = 33; +inline constexpr KPCError kErrorExecutableLib = 34; +inline constexpr KPCError kErrorFileNotFound = 35; +inline constexpr KPCError kErrorDirectoryNotFound = 36; +inline constexpr KPCError kErrorDiskReadOnly = 37; +inline constexpr KPCError kErrorDiskIsFull = 38; +inline constexpr KPCError kErrorProcessFault = 39; +inline constexpr KPCError kErrorSocketHangUp = 40; +inline constexpr KPCError kErrorThreadLocalStorage = 41; +inline constexpr KPCError kErrorMath = 42; +inline constexpr KPCError kErrorNoNetwork = 43; +inline constexpr KPCError kErrorHeapOutOfMemory = 44; +inline constexpr KPCError kErrorNoSuchDisk = 45; +inline constexpr KPCError kErrorFileExists = 46; +inline constexpr KPCError kErrorFormatFailed = 47; +inline constexpr KPCError kErrorNetworkTimeout = 48; +inline constexpr KPCError kErrorInternal = 49; +inline constexpr KPCError kErrorForkAlreadyExists = 50; +inline constexpr KPCError kErrorOutOfTeamSlot = 51; +inline constexpr KPCError kErrorHeapNotPresent = 52; +inline constexpr KPCError kErrorNoEntrypoint = 53; +inline constexpr KPCError kErrorDiskIsCorrupted = 54; +inline constexpr KPCError kErrorDisk = 55; +inline constexpr KPCError kErrorInvalidData = 56; +inline constexpr KPCError kErrorAsync = 57; +inline constexpr KPCError kErrorNonBlocking = 58; +inline constexpr KPCError kErrorIPC = 59; +inline constexpr KPCError kErrorSign = 60; +inline constexpr KPCError kErrorInvalidCreds = 61; +inline constexpr KPCError kErrorCDTrayBroken = 62; +inline constexpr KPCError kErrorUnrecoverableDisk = 63; +inline constexpr KPCError kErrorFileLocked = 64; +inline constexpr KPCError kErrorUnimplemented = -1; - /// @brief Does a system wide bug check. - /// @param void no params are needed. - /// @return if error-free: false, otherwise true. - Boolean err_bug_check_raise(Void) noexcept; -} // namespace Kernel +/// @brief Does a system wide bug check. +/// @param void no params are needed. +/// @return if error-free: false, otherwise true. +Boolean err_bug_check_raise(Void) noexcept; +} // namespace Kernel diff --git a/dev/kernel/KernelKit/KernelProcessScheduler.h b/dev/kernel/KernelKit/KernelProcessScheduler.h index 47d61ff7..24d40a36 100644 --- a/dev/kernel/KernelKit/KernelProcessScheduler.h +++ b/dev/kernel/KernelKit/KernelProcessScheduler.h @@ -1,6 +1,6 @@ /* ------------------------------------------- - Copyright (C) 2025, Amlal El Mahrouss, all rights reserved. + Copyright (C) 2025, Amlal El Mahrouss, all rights reserved. ------------------------------------------- */ diff --git a/dev/kernel/KernelKit/LoaderInterface.h b/dev/kernel/KernelKit/LoaderInterface.h index 259b8521..42046a53 100644 --- a/dev/kernel/KernelKit/LoaderInterface.h +++ b/dev/kernel/KernelKit/LoaderInterface.h @@ -1,34 +1,32 @@ /* ------------------------------------------- - Copyright (C) 2024-2025, Amlal El Mahrouss, all rights reserved. + Copyright (C) 2024-2025, Amlal El Mahrouss, all rights reserved. ------------------------------------------- */ #pragma once #include -#include #include #include +#include -namespace Kernel -{ - /// @brief This interface is used to make loader contracts (MSCOFF, PEF). - /// @author @Amlal-El-Mahrouss - class LoaderInterface - { - public: - explicit LoaderInterface() = default; - virtual ~LoaderInterface() = default; +namespace Kernel { +/// @brief This interface is used to make loader contracts (MSCOFF, PEF). +/// @author @Amlal-El-Mahrouss +class LoaderInterface { + public: + explicit LoaderInterface() = default; + virtual ~LoaderInterface() = default; - NE_COPY_DEFAULT(LoaderInterface) + NE_COPY_DEFAULT(LoaderInterface) - public: - virtual _Output ErrorOr GetBlob() = 0; - virtual _Output const Char* AsString() = 0; - virtual _Output const Char* MIME() = 0; - virtual _Output const Char* Path() = 0; - virtual _Output ErrorOr FindStart() = 0; - virtual _Output VoidPtr FindSymbol(_Input const Char* name, _Input Int32 kind) = 0; - }; -} // namespace Kernel + public: + virtual _Output ErrorOr GetBlob() = 0; + virtual _Output const Char* AsString() = 0; + virtual _Output const Char* MIME() = 0; + virtual _Output const Char* Path() = 0; + virtual _Output ErrorOr FindStart() = 0; + virtual _Output VoidPtr FindSymbol(_Input const Char* name, _Input Int32 kind) = 0; +}; +} // namespace Kernel diff --git a/dev/kernel/KernelKit/LockDelegate.h b/dev/kernel/KernelKit/LockDelegate.h index ac54d9c5..18ab0cf5 100644 --- a/dev/kernel/KernelKit/LockDelegate.h +++ b/dev/kernel/KernelKit/LockDelegate.h @@ -1,6 +1,6 @@ /* ------------------------------------------- - Copyright (C) 2024-2025, Amlal El Mahrouss, all rights reserved. + Copyright (C) 2024-2025, Amlal El Mahrouss, all rights reserved. ------------------------------------------- */ @@ -9,63 +9,50 @@ #include #include -namespace Kernel -{ - enum - { - kLockInvalid, - kLockDone = 200, - kLockTimedOut, - kLockCount = 3, - }; - - /// @brief Lock condition pointer. - typedef Boolean* LockPtr; - - /// @brief Locking delegate class, hangs until limit. - /// @tparam N the amount of cycles to wait. - template - class LockDelegate final - { - public: - LockDelegate() = delete; - - public: - explicit LockDelegate(LockPtr expr) - { - auto spin = 0U; - - while (spin < N) - { - if (*expr) - { - fLockStatus | kLockDone; - break; - } - - ++spin; - } - - if (spin > N) - fLockStatus | kLockTimedOut; - } - - ~LockDelegate() = default; - - LockDelegate& operator=(const LockDelegate&) = delete; - LockDelegate(const LockDelegate&) = delete; - - bool Done() - { - return fLockStatus[kLockDone] == kLockDone; - } - - bool HasTimedOut() - { - return fLockStatus[kLockTimedOut] != kLockTimedOut; - } - - private: - Atom fLockStatus; - }; -} // namespace Kernel +namespace Kernel { +enum { + kLockInvalid, + kLockDone = 200, + kLockTimedOut, + kLockCount = 3, +}; + +/// @brief Lock condition pointer. +typedef Boolean* LockPtr; + +/// @brief Locking delegate class, hangs until limit. +/// @tparam N the amount of cycles to wait. +template +class LockDelegate final { + public: + LockDelegate() = delete; + + public: + explicit LockDelegate(LockPtr expr) { + auto spin = 0U; + + while (spin < N) { + if (*expr) { + fLockStatus | kLockDone; + break; + } + + ++spin; + } + + if (spin > N) fLockStatus | kLockTimedOut; + } + + ~LockDelegate() = default; + + LockDelegate& operator=(const LockDelegate&) = delete; + LockDelegate(const LockDelegate&) = delete; + + bool Done() { return fLockStatus[kLockDone] == kLockDone; } + + bool HasTimedOut() { return fLockStatus[kLockTimedOut] != kLockTimedOut; } + + private: + Atom fLockStatus; +}; +} // namespace Kernel diff --git a/dev/kernel/KernelKit/MSDOS.h b/dev/kernel/KernelKit/MSDOS.h index 23d582ca..a0751a6f 100644 --- a/dev/kernel/KernelKit/MSDOS.h +++ b/dev/kernel/KernelKit/MSDOS.h @@ -1,13 +1,13 @@ /* ------------------------------------------- - Copyright (C) 2024-2025, Amlal El Mahrouss, all rights reserved. + Copyright (C) 2024-2025, Amlal El Mahrouss, all rights reserved. - File: MSDOS.h - Purpose: MS-DOS header for Kernel. + File: MSDOS.h + Purpose: MS-DOS header for Kernel. - Revision History: + Revision History: - 30/01/24: Added file (amlel) + 30/01/24: Added file (amlel) ------------------------------------------- */ @@ -26,27 +26,26 @@ typedef Kernel::UInt32 DosWord; typedef Kernel::Long DosLong; -typedef struct _DosHeader -{ - Kernel::UInt8 eMagic[2]; - DosWord eMagLen; - DosWord ePagesCount; - DosWord eCrlc; - DosWord eCParHdr; - DosWord eMinAlloc; - DosWord eMaxAlloc; - DosWord eStackSeg; - DosWord eStackPtr; - DosWord eChksum; - DosWord eIp; - DosWord eCs; - DosWord eLfarlc; - DosWord eOvno; - DosWord eRes[4]; - DosWord eOemid; - DosWord eOeminfo; - DosWord eRes2[10]; - DosLong eLfanew; +typedef struct _DosHeader { + Kernel::UInt8 eMagic[2]; + DosWord eMagLen; + DosWord ePagesCount; + DosWord eCrlc; + DosWord eCParHdr; + DosWord eMinAlloc; + DosWord eMaxAlloc; + DosWord eStackSeg; + DosWord eStackPtr; + DosWord eChksum; + DosWord eIp; + DosWord eCs; + DosWord eLfarlc; + DosWord eOvno; + DosWord eRes[4]; + DosWord eOemid; + DosWord eOeminfo; + DosWord eRes2[10]; + DosLong eLfanew; } DosHeader, *DosHeaderPtr; #endif /* ifndef __MSDOS_EXEC__ */ diff --git a/dev/kernel/KernelKit/MemoryMgr.h b/dev/kernel/KernelKit/MemoryMgr.h index ac11ac29..2274e24e 100644 --- a/dev/kernel/KernelKit/MemoryMgr.h +++ b/dev/kernel/KernelKit/MemoryMgr.h @@ -1,6 +1,6 @@ /* ------------------------------------------- - Copyright (C) 2024-2025, Amlal El Mahrouss, all rights reserved. + Copyright (C) 2024-2025, Amlal El Mahrouss, all rights reserved. ------------------------------------------- */ @@ -11,77 +11,73 @@ /// @file: MemoryMgr.h /// @brief: Memory allocation support for the NeKernel. -#include #include +#include #include -namespace Kernel -{ - /// @brief Declare pointer as free. - /// @param heap_ptr the pointer. - /// @return a status code regarding the deallocation. - Int32 mm_delete_heap(VoidPtr heap_ptr); - - /// @brief Declare a new size for heap_ptr. - /// @param heap_ptr the pointer. - /// @return unsupported always returns nullptr. - VoidPtr mm_realloc_heap(VoidPtr heap_ptr, SizeT new_sz); - - /// @brief Check if pointer is a valid Kernel pointer. - /// @param heap_ptr the pointer - /// @return if it exists it returns true. - Boolean mm_is_valid_heap(VoidPtr heap_ptr); - - /// @brief Allocate chunk of memory. - /// @param sz Size of pointer - /// @param wr Read Write bit. - /// @param user User enable bit. - /// @return The newly allocated pointer, or nullptr. - VoidPtr mm_new_heap(SizeT sz, Bool wr, Bool user, SizeT pad_amount = 0); - - /// @brief Protect the heap with a CRC value. - /// @param heap_ptr pointer. - /// @return if it valid: point has crc now., otherwise fail. - Boolean mm_protect_heap(VoidPtr heap_ptr); - - /// @brief Makes a Kernel page. - /// @param heap_ptr the page pointer. - /// @return status code - Int32 mm_make_page(VoidPtr heap_ptr); - - /// @brief Overwrites and set the flags of a heap header. - /// @param heap_ptr the pointer to update. - /// @param flags the flags to set. - Int32 mm_make_flags(VoidPtr heap_ptr, UInt64 flags); - - /// @brief Gets the flags of a heap header. - /// @param heap_ptr the pointer to get. - UInt64 mm_get_flags(VoidPtr heap_ptr); - - /// @brief Allocate C++ class. - /// @param cls The class to allocate. - /// @param args The args to pass. - template - inline BOOL mm_new_class(_Input _Output T** cls, _Input Args&&... args) - { - if (*cls) - { - err_global_get() = Kernel::kErrorInvalidData; - return NO; - } - - *cls = new T(move(args)...); - return *cls; - } - - /// @brief Delete and nullify C++ class. - /// @param cls The class to delete. - template - inline Void mm_delete_class(_Input _Output T** cls) - { - delete *cls; - *cls = nullptr; - } -} // namespace Kernel - -#endif // !INC_KERNEL_HEAP_H +namespace Kernel { +/// @brief Declare pointer as free. +/// @param heap_ptr the pointer. +/// @return a status code regarding the deallocation. +Int32 mm_delete_heap(VoidPtr heap_ptr); + +/// @brief Declare a new size for heap_ptr. +/// @param heap_ptr the pointer. +/// @return unsupported always returns nullptr. +VoidPtr mm_realloc_heap(VoidPtr heap_ptr, SizeT new_sz); + +/// @brief Check if pointer is a valid Kernel pointer. +/// @param heap_ptr the pointer +/// @return if it exists it returns true. +Boolean mm_is_valid_heap(VoidPtr heap_ptr); + +/// @brief Allocate chunk of memory. +/// @param sz Size of pointer +/// @param wr Read Write bit. +/// @param user User enable bit. +/// @return The newly allocated pointer, or nullptr. +VoidPtr mm_new_heap(SizeT sz, Bool wr, Bool user, SizeT pad_amount = 0); + +/// @brief Protect the heap with a CRC value. +/// @param heap_ptr pointer. +/// @return if it valid: point has crc now., otherwise fail. +Boolean mm_protect_heap(VoidPtr heap_ptr); + +/// @brief Makes a Kernel page. +/// @param heap_ptr the page pointer. +/// @return status code +Int32 mm_make_page(VoidPtr heap_ptr); + +/// @brief Overwrites and set the flags of a heap header. +/// @param heap_ptr the pointer to update. +/// @param flags the flags to set. +Int32 mm_make_flags(VoidPtr heap_ptr, UInt64 flags); + +/// @brief Gets the flags of a heap header. +/// @param heap_ptr the pointer to get. +UInt64 mm_get_flags(VoidPtr heap_ptr); + +/// @brief Allocate C++ class. +/// @param cls The class to allocate. +/// @param args The args to pass. +template +inline BOOL mm_new_class(_Input _Output T** cls, _Input Args&&... args) { + if (*cls) { + err_global_get() = Kernel::kErrorInvalidData; + return NO; + } + + *cls = new T(move(args)...); + return *cls; +} + +/// @brief Delete and nullify C++ class. +/// @param cls The class to delete. +template +inline Void mm_delete_class(_Input _Output T** cls) { + delete *cls; + *cls = nullptr; +} +} // namespace Kernel + +#endif // !INC_KERNEL_HEAP_H diff --git a/dev/kernel/KernelKit/PCI/DMA.h b/dev/kernel/KernelKit/PCI/DMA.h index b2d3cfa8..28256389 100644 --- a/dev/kernel/KernelKit/PCI/DMA.h +++ b/dev/kernel/KernelKit/PCI/DMA.h @@ -1,6 +1,6 @@ /* ------------------------------------------- - Copyright (C) 2024-2025, Amlal El Mahrouss, all rights reserved. + Copyright (C) 2024-2025, Amlal El Mahrouss, all rights reserved. ------------------------------------------- */ @@ -12,70 +12,63 @@ #include #include -namespace Kernel -{ - enum class DmaKind - { - PCI, // Bus mastering is required to be turned on. Basiaclly a request - // control system. 64-Bit access depends on the PAE bit and the device - // (if Double Address Cycle is available) - ISA, // Four DMA channels 0-3; 8 bit transfers and only a megabyte of RAM. - Invalid, - }; - - class DMAWrapper final - { - public: - explicit DMAWrapper() = delete; - - public: - explicit DMAWrapper(nullPtr) = delete; - explicit DMAWrapper(voidPtr Ptr, DmaKind Kind = DmaKind::PCI) - : fAddress(Ptr), fKind(Kind) - { - } - - public: - DMAWrapper& operator=(voidPtr Ptr); - - public: - DMAWrapper& operator=(const DMAWrapper&) = default; - DMAWrapper(const DMAWrapper&) = default; - - public: - ~DMAWrapper() = default; - - template - T* operator->(); - - template - T* Get(UIntPtr off = 0); - - public: - operator bool(); - bool operator!(); - - public: - bool Write(UIntPtr& bit, const UInt32& offset); - UIntPtr Read(const UInt32& offset); - Boolean Check(UIntPtr offset) const; - - public: - UIntPtr operator[](UIntPtr& offset); - - private: - voidPtr fAddress{nullptr}; - DmaKind fKind{DmaKind::Invalid}; - - private: - friend class DMAFactory; - }; - - class DMAFactory final - { - public: - static OwnPtr> Construct(OwnPtr& dma); - }; -} // namespace Kernel +namespace Kernel { +enum class DmaKind { + PCI, // Bus mastering is required to be turned on. Basiaclly a request + // control system. 64-Bit access depends on the PAE bit and the device + // (if Double Address Cycle is available) + ISA, // Four DMA channels 0-3; 8 bit transfers and only a megabyte of RAM. + Invalid, +}; + +class DMAWrapper final { + public: + explicit DMAWrapper() = delete; + + public: + explicit DMAWrapper(nullPtr) = delete; + explicit DMAWrapper(voidPtr Ptr, DmaKind Kind = DmaKind::PCI) : fAddress(Ptr), fKind(Kind) {} + + public: + DMAWrapper& operator=(voidPtr Ptr); + + public: + DMAWrapper& operator=(const DMAWrapper&) = default; + DMAWrapper(const DMAWrapper&) = default; + + public: + ~DMAWrapper() = default; + + template + T* operator->(); + + template + T* Get(UIntPtr off = 0); + + public: + operator bool(); + bool operator!(); + + public: + bool Write(UIntPtr& bit, const UInt32& offset); + UIntPtr Read(const UInt32& offset); + Boolean Check(UIntPtr offset) const; + + public: + UIntPtr operator[](UIntPtr& offset); + + private: + voidPtr fAddress{nullptr}; + DmaKind fKind{DmaKind::Invalid}; + + private: + friend class DMAFactory; +}; + +class DMAFactory final { + public: + static OwnPtr> Construct(OwnPtr& dma); +}; +} // namespace Kernel #include diff --git a/dev/kernel/KernelKit/PCI/DMA.inl b/dev/kernel/KernelKit/PCI/DMA.inl index 89381149..4df24371 100644 --- a/dev/kernel/KernelKit/PCI/DMA.inl +++ b/dev/kernel/KernelKit/PCI/DMA.inl @@ -1,20 +1,17 @@ /* ------------------------------------------- - Copyright (C) 2024-2025, Amlal El Mahrouss, all rights reserved. + Copyright (C) 2024-2025, Amlal El Mahrouss, all rights reserved. ------------------------------------------- */ -namespace Kernel -{ - template - T* DMAWrapper::operator->() - { - return this->fAddress; - } +namespace Kernel { +template +T* DMAWrapper::operator->() { + return this->fAddress; +} - template - T* DMAWrapper::Get(UIntPtr offset) - { - return reinterpret_cast((UIntPtr)this->fAddress + offset); - } -} // namespace Kernel +template +T* DMAWrapper::Get(UIntPtr offset) { + return reinterpret_cast((UIntPtr) this->fAddress + offset); +} +} // namespace Kernel diff --git a/dev/kernel/KernelKit/PCI/Database.h b/dev/kernel/KernelKit/PCI/Database.h index e97640f7..6da653dd 100644 --- a/dev/kernel/KernelKit/PCI/Database.h +++ b/dev/kernel/KernelKit/PCI/Database.h @@ -1,6 +1,6 @@ /* ------------------------------------------- - Copyright (C) 2024-2025, Amlal El Mahrouss, all rights reserved. + Copyright (C) 2024-2025, Amlal El Mahrouss, all rights reserved. ------------------------------------------- */ #pragma once @@ -8,51 +8,44 @@ #include #include -namespace Kernel -{ - namespace Types - { - // https://wiki.osdev.org/PCI - enum class PciDeviceKind : UChar - { - MassStorageController = 0x1, - NetworkController = 0x2, - DisplayController = 0x3, - MultimediaController = 0x4, - MemoryController = 0x5, - Bridge = 0x6, - CommunicationController = 0x7, - GenericSystemPeripheral = 0x8, - InputDeviceController = 0x9, - DockingStation = 0xa, - Processor = 0xb, - SerialBusController = 0xc, - WirelessController = 0xd, - IntelligentController = 0xe, - SatelliteCommunicationsController = 0xf, - CoProcessor = 0x40, - Unassgined = 0xf, - Invalid = Unassgined, - }; - } // namespace Types -} // namespace Kernel - -inline BOOL operator!=(const Kernel::Types::PciDeviceKind& lhs, Kernel::UChar rhs) -{ - return rhs != (Kernel::UChar)lhs; +namespace Kernel { +namespace Types { + // https://wiki.osdev.org/PCI + enum class PciDeviceKind : UChar { + MassStorageController = 0x1, + NetworkController = 0x2, + DisplayController = 0x3, + MultimediaController = 0x4, + MemoryController = 0x5, + Bridge = 0x6, + CommunicationController = 0x7, + GenericSystemPeripheral = 0x8, + InputDeviceController = 0x9, + DockingStation = 0xa, + Processor = 0xb, + SerialBusController = 0xc, + WirelessController = 0xd, + IntelligentController = 0xe, + SatelliteCommunicationsController = 0xf, + CoProcessor = 0x40, + Unassgined = 0xf, + Invalid = Unassgined, + }; +} // namespace Types +} // namespace Kernel + +inline BOOL operator!=(const Kernel::Types::PciDeviceKind& lhs, Kernel::UChar rhs) { + return rhs != (Kernel::UChar) lhs; } -inline BOOL operator==(const Kernel::Types::PciDeviceKind& lhs, Kernel::UChar rhs) -{ - return rhs == (Kernel::UChar)lhs; +inline BOOL operator==(const Kernel::Types::PciDeviceKind& lhs, Kernel::UChar rhs) { + return rhs == (Kernel::UChar) lhs; } -inline BOOL operator!=(Kernel::UChar lhs, const Kernel::Types::PciDeviceKind& rhs) -{ - return lhs != (Kernel::UChar)rhs; +inline BOOL operator!=(Kernel::UChar lhs, const Kernel::Types::PciDeviceKind& rhs) { + return lhs != (Kernel::UChar) rhs; } -inline BOOL operator==(Kernel::UChar lhs, const Kernel::Types::PciDeviceKind& rhs) -{ - return lhs == (Kernel::UChar)rhs; +inline BOOL operator==(Kernel::UChar lhs, const Kernel::Types::PciDeviceKind& rhs) { + return lhs == (Kernel::UChar) rhs; } \ No newline at end of file diff --git a/dev/kernel/KernelKit/PCI/Device.h b/dev/kernel/KernelKit/PCI/Device.h index 0c434b0b..d9bb4e70 100644 --- a/dev/kernel/KernelKit/PCI/Device.h +++ b/dev/kernel/KernelKit/PCI/Device.h @@ -1,78 +1,73 @@ /* ------------------------------------------- - Copyright (C) 2024-2025, Amlal El Mahrouss, all rights reserved. + Copyright (C) 2024-2025, Amlal El Mahrouss, all rights reserved. ------------------------------------------- */ #pragma once #include -namespace Kernel::PCI -{ - enum class PciConfigKind : UShort - { - ConfigAddress = 0xCF8, - ConfigData = 0xCFC, - CommandReg = 0x0004, - Invalid = 0xFFFF, - }; - - /// @brief Device interface class - class Device final - { - public: - Device() = default; - - public: - Device(UShort bus, UShort device, UShort function, UInt32 bar); - - Device& operator=(const Device&) = default; - Device(const Device&) = default; - - ~Device(); - - public: - UInt Read(UInt bar, Size szData); - void Write(UInt bar, UIntPtr data, Size szData); - - public: - operator bool(); - - public: - template - UInt Read(UInt bar) - { - static_assert(sizeof(T) <= sizeof(UInt32), "64-bit PCI addressing is unsupported"); - return Read(bar, sizeof(T)); - } - - template - void Write(UInt bar, UIntPtr data) - { - static_assert(sizeof(T) <= sizeof(UInt32), "64-bit PCI addressing is unsupported"); - Write(bar, data, sizeof(T)); - } - - public: - UShort DeviceId(); - UShort VendorId(); - UShort InterfaceId(); - UChar Class(); - UChar Subclass(); - UChar ProgIf(); - UChar HeaderType(); - UIntPtr Bar(UInt32 bar_in); - - public: - void EnableMmio(); - void BecomeBusMaster(); // for PCI-DMA, PC-DMA does not need that. - - UShort Vendor(); - - private: - UShort fBus; - UShort fDevice; - UShort fFunction; - UInt32 fBar; - }; -} // namespace Kernel::PCI +namespace Kernel::PCI { +enum class PciConfigKind : UShort { + ConfigAddress = 0xCF8, + ConfigData = 0xCFC, + CommandReg = 0x0004, + Invalid = 0xFFFF, +}; + +/// @brief Device interface class +class Device final { + public: + Device() = default; + + public: + Device(UShort bus, UShort device, UShort function, UInt32 bar); + + Device& operator=(const Device&) = default; + Device(const Device&) = default; + + ~Device(); + + public: + UInt Read(UInt bar, Size szData); + void Write(UInt bar, UIntPtr data, Size szData); + + public: + operator bool(); + + public: + template + UInt Read(UInt bar) { + static_assert(sizeof(T) <= sizeof(UInt32), "64-bit PCI addressing is unsupported"); + return Read(bar, sizeof(T)); + } + + template + void Write(UInt bar, UIntPtr data) { + static_assert(sizeof(T) <= sizeof(UInt32), "64-bit PCI addressing is unsupported"); + Write(bar, data, sizeof(T)); + } + + public: + UShort DeviceId(); + UShort VendorId(); + UShort InterfaceId(); + UChar Class(); + UChar Subclass(); + UChar ProgIf(); + UChar HeaderType(); + UIntPtr Bar(UInt32 bar_in); + + public: + void EnableMmio(); + void BecomeBusMaster(); // for PCI-DMA, PC-DMA does not need that. + + UShort Vendor(); + + private: + UShort fBus; + UShort fDevice; + UShort fFunction; + UInt32 fBar; +}; +} // namespace Kernel::PCI diff --git a/dev/kernel/KernelKit/PCI/Express.h b/dev/kernel/KernelKit/PCI/Express.h index b8b4df4d..4d94830c 100644 --- a/dev/kernel/KernelKit/PCI/Express.h +++ b/dev/kernel/KernelKit/PCI/Express.h @@ -1,12 +1,12 @@ /* ------------------------------------------- - Copyright (C) 2024-2025, Amlal El Mahrouss, all rights reserved. + Copyright (C) 2024-2025, Amlal El Mahrouss, all rights reserved. ------------------------------------------- */ #pragma once -#include #include +#include #define PCI_EXPRESS_BUS_COUNT (4096) diff --git a/dev/kernel/KernelKit/PCI/IO.h b/dev/kernel/KernelKit/PCI/IO.h index 78fcef76..bd5751ec 100644 --- a/dev/kernel/KernelKit/PCI/IO.h +++ b/dev/kernel/KernelKit/PCI/IO.h @@ -1,6 +1,6 @@ /* ------------------------------------------- - Copyright (C) 2024-2025, Amlal El Mahrouss, all rights reserved. + Copyright (C) 2024-2025, Amlal El Mahrouss, all rights reserved. ------------------------------------------- */ @@ -11,65 +11,53 @@ #include #include -namespace Kernel -{ - template - class IOArray final - { - public: - IOArray() = delete; +namespace Kernel { +template +class IOArray final { + public: + IOArray() = delete; - IOArray(nullPtr) = delete; + IOArray(nullPtr) = delete; - explicit IOArray(Array& ports) - : fPorts(ports) - { - } + explicit IOArray(Array& ports) : fPorts(ports) {} - ~IOArray() - { - } + ~IOArray() {} - IOArray& operator=(const IOArray&) = default; + IOArray& operator=(const IOArray&) = default; - IOArray(const IOArray&) = default; + IOArray(const IOArray&) = default; - operator bool() - { - return !fPorts.Empty(); - } + operator bool() { return !fPorts.Empty(); } - public: - template - T In(SizeT index); + public: + template + T In(SizeT index); - template - void Out(SizeT index, T value); + template + void Out(SizeT index, T value); - private: - Array fPorts; - }; + private: + Array fPorts; +}; - inline constexpr UInt16 kMaxPorts = 16; +inline constexpr UInt16 kMaxPorts = 16; - using IOArray16 = IOArray; +using IOArray16 = IOArray; - template - inline Array make_ports(UShort base) - { - Array ports; +template +inline Array make_ports(UShort base) { + Array ports; - for (UShort i = 0; i < Sz; ++i) - { - ports[i] = base + i; - } + for (UShort i = 0; i < Sz; ++i) { + ports[i] = base + i; + } - return ports; - } -} // namespace Kernel + return ports; +} +} // namespace Kernel #ifdef __x86_64__ #include #else #error Please provide platform specific code for the I/O -#endif // ifdef __x86_64__ +#endif // ifdef __x86_64__ diff --git a/dev/kernel/KernelKit/PCI/IOArray+AMD64.inl b/dev/kernel/KernelKit/PCI/IOArray+AMD64.inl index 57539e7e..842062e3 100644 --- a/dev/kernel/KernelKit/PCI/IOArray+AMD64.inl +++ b/dev/kernel/KernelKit/PCI/IOArray+AMD64.inl @@ -1,54 +1,49 @@ /* ------------------------------------------- - Copyright (C) 2024-2025, Amlal El Mahrouss, all rights reserved. + Copyright (C) 2024-2025, Amlal El Mahrouss, all rights reserved. - File: IO-Impl-AMD64.h - Purpose: I/O for AMD64. + File: IO-Impl-AMD64.h + Purpose: I/O for AMD64. - Revision History: + Revision History: - 30/01/24: Add file. (amlel) - 02/02/24: Update I/O routines. (amlel) + 30/01/24: Add file. (amlel) + 02/02/24: Update I/O routines. (amlel) ------------------------------------------- */ -namespace Kernel -{ - template - template - T IOArray::In(SizeT index) - { - switch (sizeof(T)) - { +namespace Kernel { +template +template +T IOArray::In(SizeT index) { + switch (sizeof(T)) { #ifdef __NE_AMD64__ - case 4: - return HAL::rt_in32(fPorts[index].Leak()); - case 2: - return HAL::rt_in16(fPorts[index].Leak()); - case 1: - return HAL::rt_in8(fPorts[index].Leak()); + case 4: + return HAL::rt_in32(fPorts[index].Leak()); + case 2: + return HAL::rt_in16(fPorts[index].Leak()); + case 1: + return HAL::rt_in8(fPorts[index].Leak()); #endif - default: - return 0xFFFF; - } - } + default: + return 0xFFFF; + } +} - template - template - void IOArray::Out(SizeT index, T value) - { - switch (sizeof(T)) - { +template +template +void IOArray::Out(SizeT index, T value) { + switch (sizeof(T)) { #ifdef __NE_AMD64__ - case 4: - HAL::rt_out32(fPorts[index].Leak(), value); - case 2: - HAL::rt_out16(fPorts[index].Leak(), value); - case 1: - HAL::rt_out8(fPorts[index].Leak(), value); + case 4: + HAL::rt_out32(fPorts[index].Leak(), value); + case 2: + HAL::rt_out16(fPorts[index].Leak(), value); + case 1: + HAL::rt_out8(fPorts[index].Leak(), value); #endif - default: - break; - } - } -} // namespace Kernel \ No newline at end of file + default: + break; + } +} +} // namespace Kernel \ No newline at end of file diff --git a/dev/kernel/KernelKit/PCI/Iterator.h b/dev/kernel/KernelKit/PCI/Iterator.h index 8b91f85f..10924bc8 100644 --- a/dev/kernel/KernelKit/PCI/Iterator.h +++ b/dev/kernel/KernelKit/PCI/Iterator.h @@ -1,6 +1,6 @@ /* ------------------------------------------- - Copyright (C) 2024-2025, Amlal El Mahrouss, all rights reserved. + Copyright (C) 2024-2025, Amlal El Mahrouss, all rights reserved. ------------------------------------------- */ @@ -13,31 +13,29 @@ #include #include -#define NE_BUS_COUNT (256) -#define NE_DEVICE_COUNT (33) +#define NE_BUS_COUNT (256) +#define NE_DEVICE_COUNT (33) #define NE_FUNCTION_COUNT (8) -namespace Kernel::PCI -{ - class Iterator final - { - public: - Iterator() = delete; +namespace Kernel::PCI { +class Iterator final { + public: + Iterator() = delete; - public: - explicit Iterator(const Types::PciDeviceKind& deviceType); + public: + explicit Iterator(const Types::PciDeviceKind& deviceType); - Iterator& operator=(const Iterator&) = default; - Iterator(const Iterator&) = default; + Iterator& operator=(const Iterator&) = default; + Iterator(const Iterator&) = default; - ~Iterator(); + ~Iterator(); - public: - Ref operator[](const Size& sz); + public: + Ref operator[](const Size& sz); - private: - Array fDevices; - }; -} // namespace Kernel::PCI + private: + Array fDevices; +}; +} // namespace Kernel::PCI -#endif // __PCI_ITERATOR_H__ +#endif // __PCI_ITERATOR_H__ diff --git a/dev/kernel/KernelKit/PCI/PCI.h b/dev/kernel/KernelKit/PCI/PCI.h index 02b08864..7b30d455 100644 --- a/dev/kernel/KernelKit/PCI/PCI.h +++ b/dev/kernel/KernelKit/PCI/PCI.h @@ -1,6 +1,6 @@ /* ------------------------------------------- - Copyright (C) 2024-2025, Amlal El Mahrouss, all rights reserved. + Copyright (C) 2024-2025, Amlal El Mahrouss, all rights reserved. ------------------------------------------- */ @@ -9,51 +9,46 @@ #include #define kPCIConfigAddressPort (0xCF8) -#define kPCIConfigDataPort (0xCFC) +#define kPCIConfigDataPort (0xCFC) #define kPCIDeviceCount (32) -#define kPCIFuncCount (8) -#define kPCIBusCount (256U) - -namespace Kernel::PCI -{ - // model - struct DeviceHeader - { - UInt16 VendorId; - UInt16 DeviceId; - UInt8 Command; - UInt8 Status; - UInt8 RevisionId; - UInt8 ProgIf; - UInt8 SubClass; - UInt8 Class; - UInt8 CacheLineSz; - UInt8 LatencyTimer; - UInt8 HeaderType; - UInt8 Bist; - UInt8 Bus; - UInt8 Device; - UInt8 Function; - }; - - namespace Detail - { - class BAR - { - public: - UIntPtr BAR; - SizeT Size; - }; - } // namespace Detail - - class BAR - { - public: - Detail::BAR BAR1; - Detail::BAR BAR2; - Detail::BAR BAR3; - Detail::BAR BAR4; - Detail::BAR BAR5; - }; -} // namespace Kernel::PCI +#define kPCIFuncCount (8) +#define kPCIBusCount (256U) + +namespace Kernel::PCI { +// model +struct DeviceHeader { + UInt16 VendorId; + UInt16 DeviceId; + UInt8 Command; + UInt8 Status; + UInt8 RevisionId; + UInt8 ProgIf; + UInt8 SubClass; + UInt8 Class; + UInt8 CacheLineSz; + UInt8 LatencyTimer; + UInt8 HeaderType; + UInt8 Bist; + UInt8 Bus; + UInt8 Device; + UInt8 Function; +}; + +namespace Detail { + class BAR { + public: + UIntPtr BAR; + SizeT Size; + }; +} // namespace Detail + +class BAR { + public: + Detail::BAR BAR1; + Detail::BAR BAR2; + Detail::BAR BAR3; + Detail::BAR BAR4; + Detail::BAR BAR5; +}; +} // namespace Kernel::PCI diff --git a/dev/kernel/KernelKit/PE.h b/dev/kernel/KernelKit/PE.h index e2184918..b961e901 100644 --- a/dev/kernel/KernelKit/PE.h +++ b/dev/kernel/KernelKit/PE.h @@ -1,13 +1,13 @@ /* ------------------------------------------- - Copyright (C) 2024-2025, Amlal El Mahrouss, all rights reserved. + Copyright (C) 2024-2025, Amlal El Mahrouss, all rights reserved. - File: PE.h - Purpose: Portable Executable for Kernel. + File: PE.h + Purpose: Portable Executable for Kernel. - Revision History: + Revision History: - 30/01/24: Added file (amlel) + 30/01/24: Added file (amlel) ------------------------------------------- */ @@ -24,117 +24,108 @@ #define kPeMachineAMD64 (0x8664) #define kPeMachineARM64 (0xaa64) -typedef struct LDR_EXEC_HEADER final -{ - Kernel::UInt32 Signature; - Kernel::UInt16 Machine; - Kernel::UInt16 NumberOfSections; - Kernel::UInt32 TimeDateStamp; - Kernel::UInt32 PointerToSymbolTable; - Kernel::UInt32 NumberOfSymbols; - Kernel::UInt16 SizeOfOptionalHeader; - Kernel::UInt16 Characteristics; +typedef struct LDR_EXEC_HEADER final { + Kernel::UInt32 Signature; + Kernel::UInt16 Machine; + Kernel::UInt16 NumberOfSections; + Kernel::UInt32 TimeDateStamp; + Kernel::UInt32 PointerToSymbolTable; + Kernel::UInt32 NumberOfSymbols; + Kernel::UInt16 SizeOfOptionalHeader; + Kernel::UInt16 Characteristics; } LDR_EXEC_HEADER, *LDR_EXEC_HEADER_PTR; -typedef struct LDR_OPTIONAL_HEADER final -{ - Kernel::UInt16 Magic; // 0x010b - PE32, 0x020b - PE32+ (64 bit) - Kernel::UInt8 MajorLinkerVersion; - Kernel::UInt8 MinorLinkerVersion; - Kernel::UInt32 SizeOfCode; - Kernel::UInt32 SizeOfInitializedData; - Kernel::UInt32 SizeOfUninitializedData; - Kernel::UInt32 AddressOfEntryPoint; - Kernel::UInt32 BaseOfCode; - Kernel::UInt32 BaseOfData; - Kernel::UInt32 ImageBase; - Kernel::UInt32 SectionAlignment; - Kernel::UInt32 FileAlignment; - Kernel::UInt16 MajorOperatingSystemVersion; - Kernel::UInt16 MinorOperatingSystemVersion; - Kernel::UInt16 MajorImageVersion; - Kernel::UInt16 MinorImageVersion; - Kernel::UInt16 MajorSubsystemVersion; - Kernel::UInt16 MinorSubsystemVersion; - Kernel::UInt32 Win32VersionValue; - Kernel::UInt32 SizeOfImage; - Kernel::UInt32 SizeOfHeaders; - Kernel::UInt32 CheckSum; - Kernel::UInt16 Subsystem; - Kernel::UInt16 DllCharacteristics; - Kernel::UInt32 SizeOfStackReserve; - Kernel::UInt32 SizeOfStackCommit; - Kernel::UInt32 SizeOfHeapReserve; - Kernel::UInt32 SizeOfHeapCommit; - Kernel::UInt32 LoaderFlags; - Kernel::UInt32 NumberOfRvaAndSizes; +typedef struct LDR_OPTIONAL_HEADER final { + Kernel::UInt16 Magic; // 0x010b - PE32, 0x020b - PE32+ (64 bit) + Kernel::UInt8 MajorLinkerVersion; + Kernel::UInt8 MinorLinkerVersion; + Kernel::UInt32 SizeOfCode; + Kernel::UInt32 SizeOfInitializedData; + Kernel::UInt32 SizeOfUninitializedData; + Kernel::UInt32 AddressOfEntryPoint; + Kernel::UInt32 BaseOfCode; + Kernel::UInt32 BaseOfData; + Kernel::UInt32 ImageBase; + Kernel::UInt32 SectionAlignment; + Kernel::UInt32 FileAlignment; + Kernel::UInt16 MajorOperatingSystemVersion; + Kernel::UInt16 MinorOperatingSystemVersion; + Kernel::UInt16 MajorImageVersion; + Kernel::UInt16 MinorImageVersion; + Kernel::UInt16 MajorSubsystemVersion; + Kernel::UInt16 MinorSubsystemVersion; + Kernel::UInt32 Win32VersionValue; + Kernel::UInt32 SizeOfImage; + Kernel::UInt32 SizeOfHeaders; + Kernel::UInt32 CheckSum; + Kernel::UInt16 Subsystem; + Kernel::UInt16 DllCharacteristics; + Kernel::UInt32 SizeOfStackReserve; + Kernel::UInt32 SizeOfStackCommit; + Kernel::UInt32 SizeOfHeapReserve; + Kernel::UInt32 SizeOfHeapCommit; + Kernel::UInt32 LoaderFlags; + Kernel::UInt32 NumberOfRvaAndSizes; } LDR_OPTIONAL_HEADER, *LDR_OPTIONAL_HEADER_PTR; -typedef struct LDR_SECTION_HEADER final -{ - Kernel::Char Name[8]; - Kernel::UInt32 VirtualSize; - Kernel::UInt32 VirtualAddress; - Kernel::UInt32 SizeOfRawData; - Kernel::UInt32 PointerToRawData; - Kernel::UInt32 PointerToRelocations; - Kernel::UInt32 PointerToLineNumbers; - Kernel::UInt16 NumberOfRelocations; - Kernel::UInt16 NumberOfLinenumbers; - Kernel::UInt32 Characteristics; +typedef struct LDR_SECTION_HEADER final { + Kernel::Char Name[8]; + Kernel::UInt32 VirtualSize; + Kernel::UInt32 VirtualAddress; + Kernel::UInt32 SizeOfRawData; + Kernel::UInt32 PointerToRawData; + Kernel::UInt32 PointerToRelocations; + Kernel::UInt32 PointerToLineNumbers; + Kernel::UInt16 NumberOfRelocations; + Kernel::UInt16 NumberOfLinenumbers; + Kernel::UInt32 Characteristics; } LDR_SECTION_HEADER, *LDR_SECTION_HEADER_PTR; -enum kExecDataDirParams -{ - kExecExport, - kExecImport, - kExecInvalid, - kExecCount, +enum kExecDataDirParams { + kExecExport, + kExecImport, + kExecInvalid, + kExecCount, }; -typedef struct LDR_EXPORT_DIRECTORY -{ - Kernel::UInt32 Characteristics; - Kernel::UInt32 TimeDateStamp; - Kernel::UInt16 MajorVersion; - Kernel::UInt16 MinorVersion; - Kernel::UInt32 Name; - Kernel::UInt32 Base; - Kernel::UInt32 NumberOfFunctions; - Kernel::UInt32 NumberOfNames; - Kernel::UInt32 AddressOfFunctions; // export table rva - Kernel::UInt32 AddressOfNames; - Kernel::UInt32 AddressOfNameOrdinal; // ordinal table rva +typedef struct LDR_EXPORT_DIRECTORY { + Kernel::UInt32 Characteristics; + Kernel::UInt32 TimeDateStamp; + Kernel::UInt16 MajorVersion; + Kernel::UInt16 MinorVersion; + Kernel::UInt32 Name; + Kernel::UInt32 Base; + Kernel::UInt32 NumberOfFunctions; + Kernel::UInt32 NumberOfNames; + Kernel::UInt32 AddressOfFunctions; // export table rva + Kernel::UInt32 AddressOfNames; + Kernel::UInt32 AddressOfNameOrdinal; // ordinal table rva } LDR_EXPORT_DIRECTORY, *LDR_EXPORT_DIRECTORY_PTR; -typedef struct LDR_IMPORT_DIRECTORY -{ - union { - Kernel::UInt32 Characteristics; - Kernel::UInt32 OriginalFirstThunk; - }; - Kernel::UInt32 TimeDateStamp; - Kernel::UInt32 ForwarderChain; - Kernel::UInt32 NameRva; - Kernel::UInt32 ThunkTableRva; +typedef struct LDR_IMPORT_DIRECTORY { + union { + Kernel::UInt32 Characteristics; + Kernel::UInt32 OriginalFirstThunk; + }; + Kernel::UInt32 TimeDateStamp; + Kernel::UInt32 ForwarderChain; + Kernel::UInt32 NameRva; + Kernel::UInt32 ThunkTableRva; } LDR_IMPORT_DIRECTORY, *LDR_IMPORT_DIRECTORY_PTR; -typedef struct LDR_DATA_DIRECTORY -{ - Kernel::UInt32 VirtualAddress; - Kernel::UInt32 Size; +typedef struct LDR_DATA_DIRECTORY { + Kernel::UInt32 VirtualAddress; + Kernel::UInt32 Size; } LDR_DATA_DIRECTORY, *LDR_DATA_DIRECTORY_PTR; -typedef struct LDR_IMAGE_HEADER -{ - LDR_EXEC_HEADER Header; - LDR_OPTIONAL_HEADER OptHdr; +typedef struct LDR_IMAGE_HEADER { + LDR_EXEC_HEADER Header; + LDR_OPTIONAL_HEADER OptHdr; } LDR_IMAGE_HEADER, *LDR_IMAGE_HEADER_PTR; -enum -{ - kUserSection = 0x00000020, - kPEResourceId = 0xFFaadd00, +enum { + kUserSection = 0x00000020, + kPEResourceId = 0xFFaadd00, }; #endif /* ifndef __KERNELKIT_INC_PE_H__ */ diff --git a/dev/kernel/KernelKit/PECodeMgr.h b/dev/kernel/KernelKit/PECodeMgr.h index fdbd1032..860f3426 100644 --- a/dev/kernel/KernelKit/PECodeMgr.h +++ b/dev/kernel/KernelKit/PECodeMgr.h @@ -1,13 +1,13 @@ /* ------------------------------------------- - Copyright (C) 2024-2025, Amlal El Mahrouss, all rights reserved. + Copyright (C) 2024-2025, Amlal El Mahrouss, all rights reserved. - File: PECodeMgr.h - Purpose: PE32+ Code Mgr and Dylib mgr. + File: PECodeMgr.h + Purpose: PE32+ Code Mgr and Dylib mgr. - Revision History: + Revision History: - 12/02/24: Added file (amlel) + 12/02/24: Added file (amlel) ------------------------------------------- */ @@ -19,11 +19,11 @@ //////////////////////////////////////////////////// +#include +#include #include #include #include -#include -#include #ifndef INC_PROCESS_SCHEDULER_H #include @@ -31,49 +31,47 @@ #define kPeApplicationMime "application/vnd-portable-executable" -namespace Kernel -{ - /// - /// \name PE32Loader - /// \brief PE32+ loader class. - /// - class PE32Loader : public LoaderInterface - { - private: - explicit PE32Loader() = delete; - - public: - explicit PE32Loader(const VoidPtr blob); - explicit PE32Loader(const Char* path); - ~PE32Loader() override; - - public: - NE_COPY_DEFAULT(PE32Loader) - - public: - const Char* Path() override; - const Char* AsString() override; - const Char* MIME() override; - - public: - ErrorOr FindStart() override; - VoidPtr FindSymbol(const Char* name, Int32 kind) override; - ErrorOr GetBlob() override; - - public: - bool IsLoaded() noexcept; - - private: +namespace Kernel { +/// +/// \name PE32Loader +/// \brief PE32+ loader class. +/// +class PE32Loader : public LoaderInterface { + private: + explicit PE32Loader() = delete; + + public: + explicit PE32Loader(const VoidPtr blob); + explicit PE32Loader(const Char* path); + ~PE32Loader() override; + + public: + NE_COPY_DEFAULT(PE32Loader) + + public: + const Char* Path() override; + const Char* AsString() override; + const Char* MIME() override; + + public: + ErrorOr FindStart() override; + VoidPtr FindSymbol(const Char* name, Int32 kind) override; + ErrorOr GetBlob() override; + + public: + bool IsLoaded() noexcept; + + private: #ifdef __FSKIT_INCLUDES_NEFS__ - OwnPtr> fFile; + OwnPtr> fFile; #elif defined(__FSKIT_INCLUDES_HEFS__) - OwnPtr> fFile; + OwnPtr> fFile; #else - OwnPtr> fFile; -#endif // __FSKIT_INCLUDES_NEFS__ - - Ref fPath; - VoidPtr fCachedBlob; - bool fBad; - }; -} // namespace Kernel \ No newline at end of file + OwnPtr> fFile; +#endif // __FSKIT_INCLUDES_NEFS__ + + Ref fPath; + VoidPtr fCachedBlob; + bool fBad; +}; +} // namespace Kernel \ No newline at end of file diff --git a/dev/kernel/KernelKit/PEF.h b/dev/kernel/KernelKit/PEF.h index 0b2f5cb7..4c6ee5ae 100644 --- a/dev/kernel/KernelKit/PEF.h +++ b/dev/kernel/KernelKit/PEF.h @@ -1,13 +1,13 @@ /* ------------------------------------------- - Copyright (C) 2024-2025, Amlal El Mahrouss, all rights reserved. + Copyright (C) 2024-2025, Amlal El Mahrouss, all rights reserved. - File: PEF.h - Purpose: Preferred Executable Format for Kernel. + File: PEF.h + Purpose: Preferred Executable Format for Kernel. - Revision History: + Revision History: - ?/?/23: Added file (amlel) + ?/?/23: Added file (amlel) ------------------------------------------- */ @@ -18,7 +18,7 @@ #include #include -#define kPefMagic "Joy!" +#define kPefMagic "Joy!" #define kPefMagicFat "yoJ!" #define kPefMagicLen (5) @@ -27,11 +27,11 @@ #define kPefNameLen (256U) /* not mandatory, only for non fork based filesystems. */ -#define kPefExt ".exec" -#define kPefDylibExt ".dylib" -#define kPefLibExt ".lib" +#define kPefExt ".exec" +#define kPefDylibExt ".dylib" +#define kPefLibExt ".lib" #define kPefObjectExt ".obj" -#define kPefDebugExt ".dbg" +#define kPefDebugExt ".dbg" #define kPefDriverExt ".sys" // Kernel System Binary Interface. @@ -42,77 +42,70 @@ #define kPefStart "__ImageStart" #define kPefMainSymbol "_NeMain" -#define kPefForkKind kPefMagic +#define kPefForkKind kPefMagic #define kPefForkKindFAT kPefMagicFat -namespace Kernel -{ - enum - { - kPefArchIntel86S, - kPefArchAMD64, - kPefArchRISCV, - kPefArch64x0, /* 64x0. ISA */ - kPefArch32x0, /* 32x0. ISA */ - kPefArchPowerPC, - kPefArchARM64, - kPefArchCount = (kPefArchPowerPC - kPefArchIntel86S) + 1, - kPefArchInvalid = 0xFF, - }; - - enum - { - kPefSubArchAMD, - kPefSubArchIntel, - kPefSubArchARM, - kPefSubArchGeneric, - kPefSubArchIBM, - }; - - enum - { - kPefKindExec = 1, /* .o */ - kPefKindDylib = 2, /* .dylib */ - kPefKindObject = 4, /* .obj */ - kPefKindDebug = 5, /* .dbg */ - kPefKindDriver = 6, - kPefKindCount, - }; - - typedef struct PEFContainer final - { - Char Magic[kPefMagicLen]; - UInt32 Linker; - UInt32 Version; - UInt32 Kind; - UInt32 Abi; - UInt32 Cpu; - UInt32 SubCpu; /* Cpu specific information */ - UIntPtr Start; - SizeT HdrSz; /* Size of header */ - SizeT Count; /* container header count */ - } PACKED PEFContainer; - - /* First PEFCommandHeader starts after PEFContainer */ - - typedef struct PEFCommandHeader final - { - Char Name[kPefNameLen]; /* container name */ - UInt32 Cpu; /* container cpu */ - UInt32 SubCpu; /* container sub-cpu */ - UInt32 Flags; /* container flags */ - UInt16 Kind; /* container kind */ - UIntPtr Offset; /* content offset */ - SizeT Size; /* content Size */ - } PACKED PEFCommandHeader; - - enum - { - kPefCode = 0xC, - kPefData = 0xD, - kPefZero = 0xE, - kPefLinkerID = 0x1, - }; -} // namespace Kernel +namespace Kernel { +enum { + kPefArchIntel86S, + kPefArchAMD64, + kPefArchRISCV, + kPefArch64x0, /* 64x0. ISA */ + kPefArch32x0, /* 32x0. ISA */ + kPefArchPowerPC, + kPefArchARM64, + kPefArchCount = (kPefArchPowerPC - kPefArchIntel86S) + 1, + kPefArchInvalid = 0xFF, +}; + +enum { + kPefSubArchAMD, + kPefSubArchIntel, + kPefSubArchARM, + kPefSubArchGeneric, + kPefSubArchIBM, +}; + +enum { + kPefKindExec = 1, /* .o */ + kPefKindDylib = 2, /* .dylib */ + kPefKindObject = 4, /* .obj */ + kPefKindDebug = 5, /* .dbg */ + kPefKindDriver = 6, + kPefKindCount, +}; + +typedef struct PEFContainer final { + Char Magic[kPefMagicLen]; + UInt32 Linker; + UInt32 Version; + UInt32 Kind; + UInt32 Abi; + UInt32 Cpu; + UInt32 SubCpu; /* Cpu specific information */ + UIntPtr Start; + SizeT HdrSz; /* Size of header */ + SizeT Count; /* container header count */ +} PACKED PEFContainer; + +/* First PEFCommandHeader starts after PEFContainer */ + +typedef struct PEFCommandHeader final { + Char Name[kPefNameLen]; /* container name */ + UInt32 Cpu; /* container cpu */ + UInt32 SubCpu; /* container sub-cpu */ + UInt32 Flags; /* container flags */ + UInt16 Kind; /* container kind */ + UIntPtr Offset; /* content offset */ + SizeT Size; /* content Size */ +} PACKED PEFCommandHeader; + +enum { + kPefCode = 0xC, + kPefData = 0xD, + kPefZero = 0xE, + kPefLinkerID = 0x1, +}; +} // namespace Kernel #endif /* ifndef KERNELKIT_PEF_H */ diff --git a/dev/kernel/KernelKit/PEFCodeMgr.h b/dev/kernel/KernelKit/PEFCodeMgr.h index 389774fd..b3ca43d0 100644 --- a/dev/kernel/KernelKit/PEFCodeMgr.h +++ b/dev/kernel/KernelKit/PEFCodeMgr.h @@ -1,16 +1,16 @@ /* ------------------------------------------- - Copyright (C) 2024-2025, Amlal El Mahrouss, all rights reserved. + Copyright (C) 2024-2025, Amlal El Mahrouss, all rights reserved. ------------------------------------------- */ #ifndef _INC_CODE_MANAGER_PEF_H_ #define _INC_CODE_MANAGER_PEF_H_ +#include #include #include #include -#include #ifndef INC_PROCESS_SCHEDULER_H #include @@ -18,57 +18,54 @@ #define kPefApplicationMime "application/vnd-nekernel-executable" -namespace Kernel -{ - /// - /// \name PEFLoader - /// \brief PEF loader class. - /// - class PEFLoader : public LoaderInterface - { - private: - explicit PEFLoader() = delete; - - public: - explicit PEFLoader(const VoidPtr blob); - explicit PEFLoader(const Char* path); - ~PEFLoader() override; - - public: - NE_COPY_DEFAULT(PEFLoader) - - public: - const Char* Path() override; - const Char* AsString() override; - const Char* MIME() override; - - public: - ErrorOr FindStart() override; - VoidPtr FindSymbol(const Char* name, Int32 kind) override; - ErrorOr GetBlob() override; - - public: - bool IsLoaded() noexcept; - - private: +namespace Kernel { +/// +/// \name PEFLoader +/// \brief PEF loader class. +/// +class PEFLoader : public LoaderInterface { + private: + explicit PEFLoader() = delete; + + public: + explicit PEFLoader(const VoidPtr blob); + explicit PEFLoader(const Char* path); + ~PEFLoader() override; + + public: + NE_COPY_DEFAULT(PEFLoader) + + public: + const Char* Path() override; + const Char* AsString() override; + const Char* MIME() override; + + public: + ErrorOr FindStart() override; + VoidPtr FindSymbol(const Char* name, Int32 kind) override; + ErrorOr GetBlob() override; + + public: + bool IsLoaded() noexcept; + + private: #ifdef __FSKIT_INCLUDES_NEFS__ - OwnPtr> fFile; + OwnPtr> fFile; #elif defined(__FSKIT_INCLUDES_HEFS__) - OwnPtr> fFile; + OwnPtr> fFile; #else - OwnPtr> fFile; -#endif // __FSKIT_INCLUDES_NEFS__ - - Ref fPath; - VoidPtr fCachedBlob; - bool fFatBinary; - bool fBad; - }; - - namespace Utils - { - ProcessID rtl_create_user_process(PEFLoader& exec, const Int32& procKind) noexcept; - } // namespace Utils -} // namespace Kernel - -#endif // ifndef _INC_CODE_MANAGER_PEF_H_ + OwnPtr> fFile; +#endif // __FSKIT_INCLUDES_NEFS__ + + Ref fPath; + VoidPtr fCachedBlob; + bool fFatBinary; + bool fBad; +}; + +namespace Utils { + ProcessID rtl_create_user_process(PEFLoader& exec, const Int32& procKind) noexcept; +} // namespace Utils +} // namespace Kernel + +#endif // ifndef _INC_CODE_MANAGER_PEF_H_ diff --git a/dev/kernel/KernelKit/ProcessScheduler.h b/dev/kernel/KernelKit/ProcessScheduler.h index 038f46db..6da176b3 100644 --- a/dev/kernel/KernelKit/ProcessScheduler.h +++ b/dev/kernel/KernelKit/ProcessScheduler.h @@ -1,10 +1,10 @@ /* ------------------------------------------- - Copyright (C) 2025, Amlal El Mahrouss, all rights reserved. + Copyright (C) 2025, Amlal El Mahrouss, all rights reserved. ------------------------------------------- */ #pragma once -#include -#include \ No newline at end of file +#include +#include \ No newline at end of file diff --git a/dev/kernel/KernelKit/Semaphore.h b/dev/kernel/KernelKit/Semaphore.h index f11bbbd9..9a66b9fe 100644 --- a/dev/kernel/KernelKit/Semaphore.h +++ b/dev/kernel/KernelKit/Semaphore.h @@ -1,16 +1,15 @@ /* ------------------------------------------- - Copyright (C) 2024-2025, Amlal El Mahrouss, all rights reserved. + Copyright (C) 2024-2025, Amlal El Mahrouss, all rights reserved. ------------------------------------------- */ #pragma once -#include -#include #include +#include +#include -namespace Kernel -{ - typedef Int64 Semaphore; -} // namespace Kernel \ No newline at end of file +namespace Kernel { +typedef Int64 Semaphore; +} // namespace Kernel \ No newline at end of file diff --git a/dev/kernel/KernelKit/ThreadLocalStorage.h b/dev/kernel/KernelKit/ThreadLocalStorage.h index 00203ab1..bf34f39a 100644 --- a/dev/kernel/KernelKit/ThreadLocalStorage.h +++ b/dev/kernel/KernelKit/ThreadLocalStorage.h @@ -1,6 +1,6 @@ /* ------------------------------------------- - Copyright (C) 2024-2025, Amlal El Mahrouss, all rights reserved. + Copyright (C) 2024-2025, Amlal El Mahrouss, all rights reserved. ------------------------------------------- */ @@ -26,10 +26,9 @@ struct THREAD_INFORMATION_BLOCK; /// @brief Thread Information Block. /// Located in GS on AMD64, other architectures have their own stuff. (64x0, 32x0, ARM64) -struct PACKED THREAD_INFORMATION_BLOCK final -{ - Kernel::Char Cookie[kTLSCookieLen]{0}; //! Thread magic number. - Kernel::VoidPtr Record{nullptr}; //! Thread information record. +struct PACKED THREAD_INFORMATION_BLOCK final { + Kernel::Char Cookie[kTLSCookieLen]{0}; //! Thread magic number. + Kernel::VoidPtr Record{nullptr}; //! Thread information record. }; ///! @brief Cookie Sanity check. diff --git a/dev/kernel/KernelKit/ThreadLocalStorage.inl b/dev/kernel/KernelKit/ThreadLocalStorage.inl index 9161b5d0..553f8d42 100644 --- a/dev/kernel/KernelKit/ThreadLocalStorage.inl +++ b/dev/kernel/KernelKit/ThreadLocalStorage.inl @@ -1,6 +1,6 @@ /* ------------------------------------------- - Copyright (C) 2024-2025, Amlal El Mahrouss, all rights reserved. + Copyright (C) 2024-2025, Amlal El Mahrouss, all rights reserved. ------------------------------------------- */ @@ -12,53 +12,47 @@ #endif template -inline T* tls_new_ptr(void) noexcept -{ - using namespace Kernel; +inline T* tls_new_ptr(void) noexcept { + using namespace Kernel; - auto ref_process = UserProcessScheduler::The().CurrentProcess(); - MUST_PASS(ref_process); + auto ref_process = UserProcessScheduler::The().CurrentProcess(); + MUST_PASS(ref_process); - auto pointer = ref_process.Leak().New(sizeof(T)); + auto pointer = ref_process.Leak().New(sizeof(T)); - if (pointer.Error()) - return nullptr; + if (pointer.Error()) return nullptr; - return reinterpret_cast(pointer.Leak().Leak()); + return reinterpret_cast(pointer.Leak().Leak()); } //! @brief Delete process pointer. //! @param obj The pointer to delete. template -inline Kernel::Bool tls_delete_ptr(T* obj) noexcept -{ - using namespace Kernel; +inline Kernel::Bool tls_delete_ptr(T* obj) noexcept { + using namespace Kernel; - if (!obj) - return No; + if (!obj) return No; - auto ref_process = UserProcessScheduler::The().CurrentProcess(); - MUST_PASS(ref_process); + auto ref_process = UserProcessScheduler::The().CurrentProcess(); + MUST_PASS(ref_process); - ErrorOr obj_wrapped{obj}; + ErrorOr obj_wrapped{obj}; - return ref_process.Leak().Delete(obj_wrapped); + return ref_process.Leak().Delete(obj_wrapped); } //! @brief Delete process pointer. //! @param obj The pointer to delete. template -inline Kernel::Bool tls_delete_ptr(Kernel::ErrorOr obj) noexcept -{ - return tls_delete_ptr(obj.Leak()); +inline Kernel::Bool tls_delete_ptr(Kernel::ErrorOr obj) noexcept { + return tls_delete_ptr(obj.Leak()); } //! @brief Delete process pointer. //! @param obj The pointer to delete. template -inline Kernel::Bool tls_delete_ptr(Kernel::ErrorOr obj) noexcept -{ - return tls_delete_ptr(obj->Leak()); +inline Kernel::Bool tls_delete_ptr(Kernel::ErrorOr obj) noexcept { + return tls_delete_ptr(obj->Leak()); } /// @brief Allocate a C++ class, and then call the constructor of it. @@ -67,19 +61,17 @@ inline Kernel::Bool tls_delete_ptr(Kernel::ErrorOr obj) noexcept /// @param args arguments list. /// @return Class instance. template -T* tls_new_class(Args&&... args) -{ - using namespace Kernel; +T* tls_new_class(Args&&... args) { + using namespace Kernel; - T* obj = tls_new_ptr(); + T* obj = tls_new_ptr(); - if (obj) - { - *obj = T(forward(args)...); - return obj; - } + if (obj) { + *obj = T(forward(args)...); + return obj; + } - return nullptr; + return nullptr; } /// @brief Delete a C++ class (call constructor first.) @@ -87,13 +79,11 @@ T* tls_new_class(Args&&... args) /// @param obj /// @return template -inline Kernel::Bool tls_delete_class(T* obj) -{ - using namespace Kernel; +inline Kernel::Bool tls_delete_class(T* obj) { + using namespace Kernel; - if (!obj) - return No; + if (!obj) return No; - obj->~T(); - return tls_delete_ptr(obj); + obj->~T(); + return tls_delete_ptr(obj); } diff --git a/dev/kernel/KernelKit/Timer.h b/dev/kernel/KernelKit/Timer.h index 1d12876b..d6cfee39 100644 --- a/dev/kernel/KernelKit/Timer.h +++ b/dev/kernel/KernelKit/Timer.h @@ -1,6 +1,6 @@ /* ------------------------------------------- - Copyright (C) 2024-2025, Amlal El Mahrouss, all rights reserved. + Copyright (C) 2024-2025, Amlal El Mahrouss, all rights reserved. ------------------------------------------- */ @@ -9,75 +9,67 @@ #include #include -namespace Kernel -{ - class SoftwareTimer; - class TimerInterface; - - inline constexpr Int16 kTimeUnit = 1000; - - class TimerInterface - { - public: - /// @brief Default constructor - explicit TimerInterface() = default; - virtual ~TimerInterface() = default; - - public: - NE_COPY_DEFAULT(TimerInterface) - - public: - virtual BOOL Wait() noexcept; - }; - - class SoftwareTimer final : public TimerInterface - { - public: - explicit SoftwareTimer(Int64 seconds); - ~SoftwareTimer() override; - - public: - NE_COPY_DEFAULT(SoftwareTimer) - - public: - BOOL Wait() noexcept override; - - private: - UIntPtr* fDigitalTimer{nullptr}; - Int64 fWaitFor{0}; - }; - - class HardwareTimer final : public TimerInterface - { - public: - explicit HardwareTimer(UInt64 seconds); - ~HardwareTimer() override; - - public: - NE_COPY_DEFAULT(HardwareTimer) - - public: - BOOL Wait() noexcept override; - - private: - volatile UInt8* fDigitalTimer{nullptr}; - Int64 fWaitFor{0}; - }; - - inline Int64 rtl_microseconds(Int64 time) - { - if (time < 0) - return 0; - - // TODO: nanoseconds maybe? - return kTimeUnit * time; - } - - inline Int64 rtl_milliseconds(Int64 time) - { - if (time < 0) - return 0; - - return kTimeUnit * kTimeUnit * time; - } -} // namespace Kernel +namespace Kernel { +class SoftwareTimer; +class TimerInterface; + +inline constexpr Int16 kTimeUnit = 1000; + +class TimerInterface { + public: + /// @brief Default constructor + explicit TimerInterface() = default; + virtual ~TimerInterface() = default; + + public: + NE_COPY_DEFAULT(TimerInterface) + + public: + virtual BOOL Wait() noexcept; +}; + +class SoftwareTimer final : public TimerInterface { + public: + explicit SoftwareTimer(Int64 seconds); + ~SoftwareTimer() override; + + public: + NE_COPY_DEFAULT(SoftwareTimer) + + public: + BOOL Wait() noexcept override; + + private: + UIntPtr* fDigitalTimer{nullptr}; + Int64 fWaitFor{0}; +}; + +class HardwareTimer final : public TimerInterface { + public: + explicit HardwareTimer(UInt64 seconds); + ~HardwareTimer() override; + + public: + NE_COPY_DEFAULT(HardwareTimer) + + public: + BOOL Wait() noexcept override; + + private: + volatile UInt8* fDigitalTimer{nullptr}; + Int64 fWaitFor{0}; +}; + +inline Int64 rtl_microseconds(Int64 time) { + if (time < 0) return 0; + + // TODO: nanoseconds maybe? + return kTimeUnit * time; +} + +inline Int64 rtl_milliseconds(Int64 time) { + if (time < 0) return 0; + + return kTimeUnit * kTimeUnit * time; +} +} // namespace Kernel diff --git a/dev/kernel/KernelKit/User.h b/dev/kernel/KernelKit/User.h index a228c9f0..250b1dfc 100644 --- a/dev/kernel/KernelKit/User.h +++ b/dev/kernel/KernelKit/User.h @@ -17,79 +17,76 @@ #include #include -#include #include +#include ///! We got the Super, Standard (%s format) and Guest user, ///! all are used to make authorization operations on the OS. #define kSuperUser "OS AUTHORITY/SUPER/%s" #define kGuestUser "OS AUTHORITY/GUEST/%s" -#define kStdUser "OS AUTHORITY/STD/%s" +#define kStdUser "OS AUTHORITY/STD/%s" #define kUsersDir "/user/" -#define kMaxUserNameLen (256U) +#define kMaxUserNameLen (256U) #define kMaxUserTokenLen (256U) -namespace Kernel -{ - class User; +namespace Kernel { +class User; - enum class UserRingKind - { - kRingInvalid = 0, - kRingStdUser = 1, - kRingSuperUser = 2, - kRingGuestUser = 5, - kRingCount = 3, - }; +enum class UserRingKind { + kRingInvalid = 0, + kRingStdUser = 1, + kRingSuperUser = 2, + kRingGuestUser = 5, + kRingCount = 3, +}; - typedef Char* UserPublicKey; - typedef Char UserPublicKeyType; +typedef Char* UserPublicKey; +typedef Char UserPublicKeyType; - /// @brief User class. - class User final - { - public: - User() = delete; +/// @brief User class. +class User final { + public: + User() = delete; - User(const Int32& sel, const Char* username); - User(const UserRingKind& kind, const Char* username); + User(const Int32& sel, const Char* username); + User(const UserRingKind& kind, const Char* username); - ~User(); + ~User(); - public: - NE_COPY_DEFAULT(User) + public: + NE_COPY_DEFAULT(User) - public: - bool operator==(const User& lhs); - bool operator!=(const User& lhs); + public: + bool operator==(const User& lhs); + bool operator!=(const User& lhs); - public: - /// @brief Get software ring - const UserRingKind& Ring() noexcept; + public: + /// @brief Get software ring + const UserRingKind& Ring() noexcept; - /// @brief Get user name - Char* Name() noexcept; + /// @brief Get user name + Char* Name() noexcept; - /// @brief Is he a standard user? - Bool IsStdUser() noexcept; + /// @brief Is he a standard user? + Bool IsStdUser() noexcept; - /// @brief Is she a super user? - Bool IsSuperUser() noexcept; + /// @brief Is she a super user? + Bool IsSuperUser() noexcept; - /// @brief Saves a password from the public key. - Bool Save(const UserPublicKey password) noexcept; + /// @brief Saves a password from the public key. + Bool Save(const UserPublicKey password) noexcept; - /// @brief Checks if a password matches the **password**. - /// @param password the password to check. - Bool Matches(const UserPublicKey password) noexcept; + /// @brief Checks if a password matches the **password**. + /// @param password the password to check. + Bool Matches(const UserPublicKey password) noexcept; - private: - UserRingKind mUserRing{UserRingKind::kRingStdUser}; - Char mUserName[kMaxUserNameLen] = {0}; - Char mUserKey[kMaxUserTokenLen] = {0}; - }; -} // namespace Kernel + private: + UserRingKind mUserRing{UserRingKind::kRingStdUser}; + Char mUserName[kMaxUserNameLen] = {0}; + Char mUserKey[kMaxUserTokenLen] = {0}; +}; +} // namespace Kernel #endif /* ifndef INC_USER_H */ diff --git a/dev/kernel/KernelKit/UserProcessScheduler.h b/dev/kernel/KernelKit/UserProcessScheduler.h index aeefe1d2..d6cd7ad4 100644 --- a/dev/kernel/KernelKit/UserProcessScheduler.h +++ b/dev/kernel/KernelKit/UserProcessScheduler.h @@ -1,6 +1,6 @@ /* ------------------------------------------- - Copyright (C) 2024-2025, Amlal El Mahrouss, all rights reserved. + Copyright (C) 2024-2025, Amlal El Mahrouss, all rights reserved. ------------------------------------------- */ @@ -12,18 +12,18 @@ /// @author Amlal El Mahrouss (amlal@nekernel.org) #include +#include #include #include #include -#include -#define kSchedMinMicroTime (AffinityKind::kStandard) -#define kSchedInvalidPID (-1) +#define kSchedMinMicroTime (AffinityKind::kStandard) +#define kSchedInvalidPID (-1) #define kSchedProcessLimitPerTeam (32U) -#define kSchedTeamCount (256U) +#define kSchedTeamCount (256U) #define kSchedMaxMemoryLimit gib_cast(128) /* max physical memory limit */ -#define kSchedMaxStackSz mib_cast(8) /* maximum stack size */ +#define kSchedMaxStackSz mib_cast(8) /* maximum stack size */ #define kSchedNameLen (128U) @@ -31,240 +31,232 @@ // Last revision date is: Fri Mar 28 2025 // //////////////////////////////////////////////////// -namespace Kernel -{ - //! @brief Forward declarations. - - class IDylibObject; - class UserProcessScheduler; - class UserProcessHelper; - - /***********************************************************************************/ - /// @name USER_PROCESS - /// @brief USER_PROCESS class, holds information about the running process/thread. - /***********************************************************************************/ - class USER_PROCESS final - { - public: - explicit USER_PROCESS(); - ~USER_PROCESS(); - - public: - NE_COPY_DEFAULT(USER_PROCESS) - - public: - Char Name[kSchedNameLen] = {"USER_PROCESS"}; - ProcessSubsystem SubSystem{ProcessSubsystem::kProcessSubsystemInvalid}; - User* Owner{nullptr}; - HAL::StackFramePtr StackFrame{nullptr}; - AffinityKind Affinity{AffinityKind::kStandard}; - ProcessStatusKind Status{ProcessStatusKind::kKilled}; - UInt8* StackReserve{nullptr}; - PROCESS_IMAGE Image{}; - SizeT StackSize{kSchedMaxStackSz}; - IDylibObject* DylibDelegate{nullptr}; - SizeT MemoryCursor{0UL}; - SizeT MemoryLimit{kSchedMaxMemoryLimit}; - SizeT UsedMemory{0UL}; - - /// @brief Allocation tracker structure. - struct USER_HEAP_TREE final - { - VoidPtr MemoryEntry{nullptr}; - SizeT MemoryEntrySize{0UL}; - SizeT MemoryEntryPad{0UL}; - - enum - { - kInvalidMemory = 0, - kRedMemory = 100, - kBlackMemory = 101, - kCountMemory = 2, - }; - - Int32 MemoryColor{kBlackMemory}; - - struct USER_HEAP_TREE* MemoryParent{nullptr}; - struct USER_HEAP_TREE* MemoryChild{nullptr}; - - struct USER_HEAP_TREE* MemoryPrev{nullptr}; - struct USER_HEAP_TREE* MemoryNext{nullptr}; - }; - - struct USER_PROCESS_SIGNAL final - { - UIntPtr SignalArg; - ProcessStatusKind Status; - UIntPtr SignalID; - }; - - USER_PROCESS_SIGNAL Signal; - USER_HEAP_TREE* HeapTree{nullptr}; - UserProcessTeam* ParentTeam; - - VoidPtr VMRegister{0UL}; - - enum - { - kInvalidExecutableKind, - kExecutableKind, - kExecutableDylibKind, - kExecutableKindCount, - }; - - ProcessTime PTime{0}; //! @brief USER_PROCESS allocated tine. - - PID ProcessId{kSchedInvalidPID}; - Int32 Kind{kExecutableKind}; - - public: - /***********************************************************************************/ - //! @brief boolean operator, check status. - /***********************************************************************************/ - operator bool(); - - /***********************************************************************************/ - ///! @brief Crashes the app, exits with code ~0. - /***********************************************************************************/ - Void Crash(); - - /***********************************************************************************/ - ///! @brief Exits the app. - /***********************************************************************************/ - Void Exit(const Int32& exit_code = 0); - - /***********************************************************************************/ - ///! @brief TLS allocate. - ///! @param sz size of data structure. - ///! @param pad_amount amount to add after pointer. - ///! @return A wrapped pointer, or error code. - /***********************************************************************************/ - ErrorOr New(SizeT sz, SizeT pad_amount = 0); - - /***********************************************************************************/ - ///! @brief TLS free. - ///! @param ptr the pointer to free. - ///! @param sz the size of it. - /***********************************************************************************/ - template - Boolean Delete(ErrorOr ptr); - - /***********************************************************************************/ - ///! @brief Wakes up thread. - /***********************************************************************************/ - Void Wake(Bool wakeup = false); - - public: - /***********************************************************************************/ - //! @brief Gets the local exit code. - /***********************************************************************************/ - const UInt32& GetExitCode() noexcept; - - /***********************************************************************************/ - ///! @brief Get the process's name - ///! @example 'C Runtime Library' - /***********************************************************************************/ - const Char* GetName() noexcept; - - /***********************************************************************************/ - //! @brief return local error code of process. - //! @return Int32 local error code. - /***********************************************************************************/ - Int32& GetLocalCode() noexcept; - - const User* GetOwner() noexcept; - const ProcessStatusKind& GetStatus() noexcept; - const AffinityKind& GetAffinity() noexcept; - - private: - UInt32 fLastExitCode{0}; - Int32 fLocalCode{0}; - - friend UserProcessScheduler; - friend UserProcessHelper; - }; - - typedef Array USER_PROCESS_ARRAY; - - /// \brief Processs Team (contains multiple processes inside it.) - /// Equivalent to a process batch - class UserProcessTeam final - { - public: - explicit UserProcessTeam(); - ~UserProcessTeam() = default; - - NE_COPY_DEFAULT(UserProcessTeam) - - Array& AsArray(); - Ref& AsRef(); - ProcessID& Id() noexcept; - - public: - USER_PROCESS_ARRAY mProcessList; - Ref mCurrentProcess; - ProcessID mTeamId{0}; - ProcessID mProcessCount{0}; - }; - - /***********************************************************************************/ - /// @brief USER_PROCESS scheduler class. - /// The main class which you call to schedule user processes. - /***********************************************************************************/ - class UserProcessScheduler final : public ISchedulable - { - friend class UserProcessHelper; - - public: - explicit UserProcessScheduler() = default; - ~UserProcessScheduler() override = default; - - NE_COPY_DELETE(UserProcessScheduler) - NE_MOVE_DELETE(UserProcessScheduler) - - operator bool(); - bool operator!(); - - public: - UserProcessTeam& CurrentTeam(); - BOOL SwitchTeam(UserProcessTeam& team); - - public: - ProcessID Spawn(const Char* name, VoidPtr code, VoidPtr image); - Void Remove(ProcessID process_id); - - Bool IsUser() override; - Bool IsKernel() override; - Bool HasMP() override; - - public: - Ref& CurrentProcess(); - SizeT Run() noexcept; - - public: - STATIC UserProcessScheduler& The(); - - private: - UserProcessTeam mTeam{}; - }; - - /***********************************************************************************/ - /** - * \brief USER_PROCESS helper class, which contains needed utilities for the scheduler. - */ - /***********************************************************************************/ - - class UserProcessHelper final - { - public: - STATIC Bool Switch(VoidPtr image_ptr, UInt8* stack_ptr, HAL::StackFramePtr frame_ptr, PID new_pid); - STATIC Bool CanBeScheduled(const USER_PROCESS& process); - STATIC ErrorOr TheCurrentPID(); - STATIC SizeT StartScheduling(); - }; - - const UInt32& sched_get_exit_code(void) noexcept; -} // namespace Kernel +namespace Kernel { +//! @brief Forward declarations. + +class IDylibObject; +class UserProcessScheduler; +class UserProcessHelper; + +/***********************************************************************************/ +/// @name USER_PROCESS +/// @brief USER_PROCESS class, holds information about the running process/thread. +/***********************************************************************************/ +class USER_PROCESS final { + public: + explicit USER_PROCESS(); + ~USER_PROCESS(); + + public: + NE_COPY_DEFAULT(USER_PROCESS) + + public: + Char Name[kSchedNameLen] = {"USER_PROCESS"}; + ProcessSubsystem SubSystem{ProcessSubsystem::kProcessSubsystemInvalid}; + User* Owner{nullptr}; + HAL::StackFramePtr StackFrame{nullptr}; + AffinityKind Affinity{AffinityKind::kStandard}; + ProcessStatusKind Status{ProcessStatusKind::kKilled}; + UInt8* StackReserve{nullptr}; + PROCESS_IMAGE Image{}; + SizeT StackSize{kSchedMaxStackSz}; + IDylibObject* DylibDelegate{nullptr}; + SizeT MemoryCursor{0UL}; + SizeT MemoryLimit{kSchedMaxMemoryLimit}; + SizeT UsedMemory{0UL}; + + /// @brief Allocation tracker structure. + struct USER_HEAP_TREE final { + VoidPtr MemoryEntry{nullptr}; + SizeT MemoryEntrySize{0UL}; + SizeT MemoryEntryPad{0UL}; + + enum { + kInvalidMemory = 0, + kRedMemory = 100, + kBlackMemory = 101, + kCountMemory = 2, + }; + + Int32 MemoryColor{kBlackMemory}; + + struct USER_HEAP_TREE* MemoryParent{nullptr}; + struct USER_HEAP_TREE* MemoryChild{nullptr}; + + struct USER_HEAP_TREE* MemoryPrev{nullptr}; + struct USER_HEAP_TREE* MemoryNext{nullptr}; + }; + + struct USER_PROCESS_SIGNAL final { + UIntPtr SignalArg; + ProcessStatusKind Status; + UIntPtr SignalID; + }; + + USER_PROCESS_SIGNAL Signal; + USER_HEAP_TREE* HeapTree{nullptr}; + UserProcessTeam* ParentTeam; + + VoidPtr VMRegister{0UL}; + + enum { + kInvalidExecutableKind, + kExecutableKind, + kExecutableDylibKind, + kExecutableKindCount, + }; + + ProcessTime PTime{0}; //! @brief USER_PROCESS allocated tine. + + PID ProcessId{kSchedInvalidPID}; + Int32 Kind{kExecutableKind}; + + public: + /***********************************************************************************/ + //! @brief boolean operator, check status. + /***********************************************************************************/ + operator bool(); + + /***********************************************************************************/ + ///! @brief Crashes the app, exits with code ~0. + /***********************************************************************************/ + Void Crash(); + + /***********************************************************************************/ + ///! @brief Exits the app. + /***********************************************************************************/ + Void Exit(const Int32& exit_code = 0); + + /***********************************************************************************/ + ///! @brief TLS allocate. + ///! @param sz size of data structure. + ///! @param pad_amount amount to add after pointer. + ///! @return A wrapped pointer, or error code. + /***********************************************************************************/ + ErrorOr New(SizeT sz, SizeT pad_amount = 0); + + /***********************************************************************************/ + ///! @brief TLS free. + ///! @param ptr the pointer to free. + ///! @param sz the size of it. + /***********************************************************************************/ + template + Boolean Delete(ErrorOr ptr); + + /***********************************************************************************/ + ///! @brief Wakes up thread. + /***********************************************************************************/ + Void Wake(Bool wakeup = false); + + public: + /***********************************************************************************/ + //! @brief Gets the local exit code. + /***********************************************************************************/ + const UInt32& GetExitCode() noexcept; + + /***********************************************************************************/ + ///! @brief Get the process's name + ///! @example 'C Runtime Library' + /***********************************************************************************/ + const Char* GetName() noexcept; + + /***********************************************************************************/ + //! @brief return local error code of process. + //! @return Int32 local error code. + /***********************************************************************************/ + Int32& GetLocalCode() noexcept; + + const User* GetOwner() noexcept; + const ProcessStatusKind& GetStatus() noexcept; + const AffinityKind& GetAffinity() noexcept; + + private: + UInt32 fLastExitCode{0}; + Int32 fLocalCode{0}; + + friend UserProcessScheduler; + friend UserProcessHelper; +}; + +typedef Array USER_PROCESS_ARRAY; + +/// \brief Processs Team (contains multiple processes inside it.) +/// Equivalent to a process batch +class UserProcessTeam final { + public: + explicit UserProcessTeam(); + ~UserProcessTeam() = default; + + NE_COPY_DEFAULT(UserProcessTeam) + + Array& AsArray(); + Ref& AsRef(); + ProcessID& Id() noexcept; + + public: + USER_PROCESS_ARRAY mProcessList; + Ref mCurrentProcess; + ProcessID mTeamId{0}; + ProcessID mProcessCount{0}; +}; + +/***********************************************************************************/ +/// @brief USER_PROCESS scheduler class. +/// The main class which you call to schedule user processes. +/***********************************************************************************/ +class UserProcessScheduler final : public ISchedulable { + friend class UserProcessHelper; + + public: + explicit UserProcessScheduler() = default; + ~UserProcessScheduler() override = default; + + NE_COPY_DELETE(UserProcessScheduler) + NE_MOVE_DELETE(UserProcessScheduler) + + operator bool(); + bool operator!(); + + public: + UserProcessTeam& CurrentTeam(); + BOOL SwitchTeam(UserProcessTeam& team); + + public: + ProcessID Spawn(const Char* name, VoidPtr code, VoidPtr image); + Void Remove(ProcessID process_id); + + Bool IsUser() override; + Bool IsKernel() override; + Bool HasMP() override; + + public: + Ref& CurrentProcess(); + SizeT Run() noexcept; + + public: + STATIC UserProcessScheduler& The(); + + private: + UserProcessTeam mTeam{}; +}; + +/***********************************************************************************/ +/** + * \brief USER_PROCESS helper class, which contains needed utilities for the scheduler. + */ +/***********************************************************************************/ + +class UserProcessHelper final { + public: + STATIC Bool Switch(VoidPtr image_ptr, UInt8* stack_ptr, HAL::StackFramePtr frame_ptr, + PID new_pid); + STATIC Bool CanBeScheduled(const USER_PROCESS& process); + STATIC ErrorOr TheCurrentPID(); + STATIC SizeT StartScheduling(); +}; + +const UInt32& sched_get_exit_code(void) noexcept; +} // namespace Kernel #include #include diff --git a/dev/kernel/KernelKit/UserProcessScheduler.inl b/dev/kernel/KernelKit/UserProcessScheduler.inl index 63cdc795..2333b898 100644 --- a/dev/kernel/KernelKit/UserProcessScheduler.inl +++ b/dev/kernel/KernelKit/UserProcessScheduler.inl @@ -1,9 +1,9 @@ /* ------------------------------------------- - Copyright (C) 2024-2025, Amlal El Mahrouss, all rights reserved. + Copyright (C) 2024-2025, Amlal El Mahrouss, all rights reserved. - FILE: UserProcessScheduler.inl - PURPOSE: Low level/Ring-3 process scheduler. + FILE: UserProcessScheduler.inl + PURPOSE: Low level/Ring-3 process scheduler. ------------------------------------------- */ @@ -11,56 +11,50 @@ /// @author Amlal El Mahrouss (amlal@nekernel.org) /// @date Tue Apr 22 22:01:07 CEST 2025 -namespace Kernel -{ - /***********************************************************************************/ - /** @brief Free pointer from usage. */ - /***********************************************************************************/ +namespace Kernel { +/***********************************************************************************/ +/** @brief Free pointer from usage. */ +/***********************************************************************************/ - template - Boolean USER_PROCESS::Delete(ErrorOr ptr) - { - if (!ptr) - return No; +template +Boolean USER_PROCESS::Delete(ErrorOr ptr) { + if (!ptr) return No; - if (!this->HeapTree) - { - kout << "USER_PROCESS's heap is empty.\r"; - return No; - } + if (!this->HeapTree) { + kout << "USER_PROCESS's heap is empty.\r"; + return No; + } - USER_HEAP_TREE* entry = this->HeapTree; + USER_HEAP_TREE* entry = this->HeapTree; - while (entry != nullptr) - { - if (entry->MemoryEntry == ptr.Leak().Leak()) - { - this->UsedMemory -= entry->MemoryEntrySize; + while (entry != nullptr) { + if (entry->MemoryEntry == ptr.Leak().Leak()) { + this->UsedMemory -= entry->MemoryEntrySize; #ifdef __NE_AMD64__ - auto pd = hal_read_cr3(); + auto pd = hal_read_cr3(); - hal_write_cr3(this->VMRegister); + hal_write_cr3(this->VMRegister); - auto ret = mm_delete_heap(entry->MemoryEntry); + auto ret = mm_delete_heap(entry->MemoryEntry); - hal_write_cr3(pd); + hal_write_cr3(pd); - return ret == kErrorSuccess; + return ret == kErrorSuccess; #else - Bool ret = mm_delete_heap(ptr.Leak().Leak()); + Bool ret = mm_delete_heap(ptr.Leak().Leak()); - return ret == kErrorSuccess; + return ret == kErrorSuccess; #endif - } + } - entry = entry->MemoryNext; - } + entry = entry->MemoryNext; + } - kout << "USER_PROCESS: Trying to free a pointer which doesn't exist.\r"; + kout << "USER_PROCESS: Trying to free a pointer which doesn't exist.\r"; - this->Crash(); + this->Crash(); - return No; - } -} // namespace Kernel + return No; +} +} // namespace Kernel diff --git a/dev/kernel/KernelKit/XCOFF.h b/dev/kernel/KernelKit/XCOFF.h index 69cb0c53..7b15782b 100644 --- a/dev/kernel/KernelKit/XCOFF.h +++ b/dev/kernel/KernelKit/XCOFF.h @@ -1,13 +1,13 @@ /* ------------------------------------------- - Copyright (C) 2024-2025, Amlal El Mahrouss, all rights reserved. + Copyright (C) 2024-2025, Amlal El Mahrouss, all rights reserved. - File: XCOFF.h - Purpose: XCOFF for Kernel. + File: XCOFF.h + Purpose: XCOFF for Kernel. - Revision History: + Revision History: - 04/07/24: Added file (amlel) + 04/07/24: Added file (amlel) ------------------------------------------- */ @@ -16,38 +16,36 @@ #include -#define kXCOFF64Magic (0x01F7) +#define kXCOFF64Magic (0x01F7) #define kXCOFF64ForkNameLen (256U) -#define kXCOFFRelFlg (0x0001) +#define kXCOFFRelFlg (0x0001) #define kXCOFFExecutable (0x0002) -#define kXCOFFLnno (0x0004) -#define kXCOFFLSyms (0x0008) +#define kXCOFFLnno (0x0004) +#define kXCOFFLSyms (0x0008) struct XCOFF_FILE_HEADER; struct XCOFF_FORK_HEADER; /// @brief XCoff file header, meant for POWER apps. -typedef struct XCOFF_FILE_HEADER -{ - Kernel::UInt16 fMagic; - Kernel::UInt16 fTarget; - Kernel::UInt16 fNumSecs; - Kernel::UInt32 fTimeDat; - Kernel::UIntPtr fSymPtr; - Kernel::UInt32 fNumSyms; - Kernel::UInt16 fOptHdr; // ?: Number of bytes in optional header +typedef struct XCOFF_FILE_HEADER { + Kernel::UInt16 fMagic; + Kernel::UInt16 fTarget; + Kernel::UInt16 fNumSecs; + Kernel::UInt32 fTimeDat; + Kernel::UIntPtr fSymPtr; + Kernel::UInt32 fNumSyms; + Kernel::UInt16 fOptHdr; // ?: Number of bytes in optional header } XCOFF_FILE_HEADER, XCOFF_FILE_HEADER32, XCOFF_FILE_HEADER64; /// @brief This the executable's manifest fork, designed for NeFS. /// @param fPropertiesXMLFork The XML fork of the executable. /// @param fDynamicLoaderFork The DYLD fork metadata. /// @param fCodeSignFork Executable's certificate contained in a fork. -typedef struct XCOFF_FORK_HEADER -{ - Kernel::Char fPropertiesXMLFork[kXCOFF64ForkNameLen]; - Kernel::Char fDynamicLoaderFork[kXCOFF64ForkNameLen]; - Kernel::Char fCodeSignFork[kXCOFF64ForkNameLen]; +typedef struct XCOFF_FORK_HEADER { + Kernel::Char fPropertiesXMLFork[kXCOFF64ForkNameLen]; + Kernel::Char fDynamicLoaderFork[kXCOFF64ForkNameLen]; + Kernel::Char fCodeSignFork[kXCOFF64ForkNameLen]; } XCOFF_FORK_HEADER; -#endif // ifndef INC_XOCFF_H +#endif // ifndef INC_XOCFF_H -- cgit v1.2.3