From 8153dc983802115951836f2b164af371ee6e3d73 Mon Sep 17 00:00:00 2001 From: Amlal El Mahrouss Date: Wed, 24 Apr 2024 19:57:10 +0200 Subject: MHR-16: Add QR-code when bootloader crashes alongside other welcomed changes. Signed-off-by: Amlal El Mahrouss --- Private/Builtins/Toolbox/Toolbox.hxx | 12 +- Private/FirmwareKit/EFI/API.hxx | 40 +- Private/FirmwareKit/Handover.hxx | 9 +- Private/KernelKit/SMPManager.hpp | 3 + Private/NewBoot/BootKit/BitManip.hxx | 20 + Private/NewBoot/BootKit/BootKit.hxx | 13 +- Private/NewBoot/BootKit/Vendor/Qr.hxx | 837 +++++++++++++++++++++ Private/NewBoot/BootKit/Vendor/QrPrelude.hxx | 1 + Private/NewBoot/BootKit/Vendor/Support.hxx | 90 +++ Private/NewBoot/Source/CDROM/SplashScreen.fmt | 2 +- Private/NewBoot/Source/HEL/AMD64/BootAHCI.cxx | 3 + Private/NewBoot/Source/HEL/AMD64/BootATA.cxx | 3 +- .../NewBoot/Source/HEL/AMD64/BootFileReader.cxx | 2 + Private/NewBoot/Source/HEL/AMD64/BootMain.cxx | 6 +- Private/NewBoot/Source/HEL/AMD64/BootPlatform.cxx | 2 + Private/NewBoot/Source/HEL/AMD64/BootString.cxx | 2 + .../NewBoot/Source/HEL/AMD64/BootTextWriter.cxx | 2 + Private/NewBoot/Source/HEL/AMD64/New+Delete.cxx | 2 + Private/NewBoot/Source/HEL/AMD64/Support.cxx | 32 + Private/NewBoot/Source/makefile | 2 +- Private/Source/ProcessScheduler.cxx | 11 +- 21 files changed, 1054 insertions(+), 40 deletions(-) create mode 100644 Private/NewBoot/BootKit/BitManip.hxx create mode 100644 Private/NewBoot/BootKit/Vendor/Qr.hxx create mode 100644 Private/NewBoot/BootKit/Vendor/QrPrelude.hxx create mode 100644 Private/NewBoot/BootKit/Vendor/Support.hxx create mode 100644 Private/NewBoot/Source/HEL/AMD64/Support.cxx diff --git a/Private/Builtins/Toolbox/Toolbox.hxx b/Private/Builtins/Toolbox/Toolbox.hxx index b3dad30b..0c5b31c5 100644 --- a/Private/Builtins/Toolbox/Toolbox.hxx +++ b/Private/Builtins/Toolbox/Toolbox.hxx @@ -25,8 +25,8 @@ EXTERN_C NewOS::Boolean _hal_right_button_pressed(); #define ToolboxDrawOrRsrc(ImgPtr, _Height, _Width, BaseX, BaseY) \ __ToolboxCursor = 0; \ \ - for (NewOS::SizeT i = BaseX; i < _Height + BaseX; ++i) { \ - for (NewOS::SizeT u = BaseY; u < _Width + BaseY; ++u) { \ + for (NewOS::SizeT i = BaseX; i < (_Height + BaseX); ++i) { \ + for (NewOS::SizeT u = BaseY; u < (_Width + BaseY); ++u) { \ *(((volatile NewOS::UInt32*)(kHandoverHeader->f_GOP.f_The + \ 4 * kHandoverHeader->f_GOP.f_PixelPerLine * \ i + \ @@ -40,8 +40,8 @@ EXTERN_C NewOS::Boolean _hal_right_button_pressed(); #define ToolboxDrawRsrc(ImgPtr, _Height, _Width, BaseX, BaseY) \ __ToolboxCursor = 0; \ \ - for (NewOS::SizeT i = BaseX; i < _Height + BaseX; ++i) { \ - for (NewOS::SizeT u = BaseY; u < _Width + BaseY; ++u) { \ + for (NewOS::SizeT i = BaseX; i < (_Height + BaseX); ++i) { \ + for (NewOS::SizeT u = BaseY; u < (_Width + BaseY); ++u) { \ *(((volatile NewOS::UInt32*)(kHandoverHeader->f_GOP.f_The + \ 4 * kHandoverHeader->f_GOP.f_PixelPerLine * \ i + \ @@ -66,8 +66,8 @@ EXTERN_C NewOS::Boolean _hal_right_button_pressed(); /// @brief Draws inside a zone. #define ToolboxDrawZone(_Clr, _Height, _Width, BaseX, BaseY) \ \ - for (NewOS::SizeT i = BaseX; i < _Width + BaseX; ++i) { \ - for (NewOS::SizeT u = BaseY; u < _Height + BaseY; ++u) { \ + for (NewOS::SizeT i = BaseX; i < (_Width + BaseX); ++i) { \ + for (NewOS::SizeT u = BaseY; u < (_Height + BaseY); ++u) { \ *(((volatile NewOS::UInt32*)(kHandoverHeader->f_GOP.f_The + \ 4 * kHandoverHeader->f_GOP.f_PixelPerLine * \ i + \ diff --git a/Private/FirmwareKit/EFI/API.hxx b/Private/FirmwareKit/EFI/API.hxx index 536d12c8..212f3686 100644 --- a/Private/FirmwareKit/EFI/API.hxx +++ b/Private/FirmwareKit/EFI/API.hxx @@ -7,16 +7,23 @@ #ifndef __EFI_API__ #define __EFI_API__ -#ifdef __NEWBOOT__ -#include -#include -#endif // ifdef __NEWBOOT__ - #include #include #include #include +#ifdef __NEWBOOT__ +// forward decl. +class BTextWriter; + +#define __BOOTKIT_NO_INCLUDE__ 1 + +#include +#include +#include +#include +#endif // ifdef __NEWBOOT__ + inline EfiSystemTable *ST = nullptr; inline EfiBootServices *BS = nullptr; @@ -58,17 +65,17 @@ inline UInt32 Platform() noexcept { return kPEMachineAMD64; } */ inline void RaiseHardError(const EfiCharType *ErrorCode, const EfiCharType *Reason) noexcept { +#ifdef __DEBUG__ ST->ConOut->OutputString(ST->ConOut, L"\r\n*** STOP ***\r\n"); ST->ConOut->OutputString(ST->ConOut, L"*** Error: "); ST->ConOut->OutputString(ST->ConOut, ErrorCode); -#ifdef __DEBUG__ ST->ConOut->OutputString(ST->ConOut, L", Reason: "); ST->ConOut->OutputString(ST->ConOut, Reason); -#endif // ifdef __DEBUG__ ST->ConOut->OutputString(ST->ConOut, L" ***\r\n"); +#endif // ifdef __DEBUG__ #ifdef __NEWBOOT__ ToolboxInitRsrc(); @@ -78,7 +85,24 @@ inline void RaiseHardError(const EfiCharType *ErrorCode, (kHandoverHeader->f_GOP.f_Height - NEWBOOTFATAL_HEIGHT) / 2); ToolboxClearRsrc(); -#endif // ifdef __NEWBOOT__ + + /// Show the QR code now. + + constexpr auto ver = 7; + auto ecc = qr::Ecc::H; + auto str = "https://www.mahrouss-logic.com/help"; + auto len = BStrLen(L"https://www.mahrouss-logic.com/help"); + + qr::Qr encoder; + qr::QrDelegate encoderDelegate; + + encoder.encode(str, len, ecc, -1); // Automatic mask. + + /// tell delegate to draw encoded QR. + encoderDelegate.draw(encoder, (kHandoverHeader->f_GOP.f_Width - encoder.side_size()) / 2, + (kHandoverHeader->f_GOP.f_Height - encoder.side_size()) - 20); + +#endif // ifdef __NEWBOOT__ EFI::Stop(); } diff --git a/Private/FirmwareKit/Handover.hxx b/Private/FirmwareKit/Handover.hxx index 5ab19fdf..4131467d 100644 --- a/Private/FirmwareKit/Handover.hxx +++ b/Private/FirmwareKit/Handover.hxx @@ -81,10 +81,11 @@ struct HandoverInformationHeader { } f_GOP; }; -/** - @brief Handover Jump Proc -*/ -typedef void (*HandoverProc)(HandoverInformationHeader* pHandover); +/// @brief Bootloader main type. +typedef void (*BootMainKind)(NewOS::HEL::HandoverInformationHeader* handoverInfo); + +/// @brief Alias of bootloader main type. +typedef void (*HandoverProc)(HandoverInformationHeader* handoverInfo); } // namespace NewOS::HEL diff --git a/Private/KernelKit/SMPManager.hpp b/Private/KernelKit/SMPManager.hpp index 17ea9d38..b7f78ebd 100644 --- a/Private/KernelKit/SMPManager.hpp +++ b/Private/KernelKit/SMPManager.hpp @@ -29,6 +29,9 @@ enum ThreadKind { kHartCount, }; +typedef enum ThreadKind SmThreadKind; +typedef ThreadID SmThreadID; + /// /// \name HardwareThread /// @brief CPU Hardware Thread (POWER, x64, or 64x0) diff --git a/Private/NewBoot/BootKit/BitManip.hxx b/Private/NewBoot/BootKit/BitManip.hxx new file mode 100644 index 00000000..dcb786cf --- /dev/null +++ b/Private/NewBoot/BootKit/BitManip.hxx @@ -0,0 +1,20 @@ +/* ------------------------------------------- + + Copyright Mahrouss Logic + +------------------------------------------- */ + +#ifndef __BITMANIP_H__ +#define __BITMANIP_H__ + +/// Name: Bits API. +/// Purpose: Bit manip helpers, based on CoreBoot header. + +#define bk_set_bit(X, O) X = (1 << O) | X +#define bk_clear_bit(X, O) X = ~(1 << O) & X +#define bk_toogle(X, O) X = (1 << O) ^ X +#define bk_lsb(X) X = X & -X +#define bk_msb(X) X = -(mp_lsb(X)) & X +#define bk_look_for_bit(X, O) (1 << O) | X + +#endif // ifndef __BITMANIP_H__ diff --git a/Private/NewBoot/BootKit/BootKit.hxx b/Private/NewBoot/BootKit/BootKit.hxx index 1a992166..5c3a531d 100644 --- a/Private/NewBoot/BootKit/BootKit.hxx +++ b/Private/NewBoot/BootKit/BootKit.hxx @@ -29,19 +29,11 @@ class BVersionString; /// Include other APIs. /***********************************************************************************/ -#include -#include +#include ///! @note This address is reserved to NewKernel. #define kBootVirtualAddress (0xfffffff80000000) -#ifdef __EFI_x86_64__ -#include -#endif // ifdef __EFI_x86_64__ - -#include -#include - using namespace NewOS; typedef Char *PEFImagePtr; @@ -147,9 +139,6 @@ class BVersionString final { static const CharacterTypeUTF16 *Shared() { return BOOTLOADER_VERSION; } }; -/// @brief Bootloader main type. -typedef void (*BootMainKind)(HEL::HandoverInformationHeader *handoverInfo); - /***********************************************************************************/ /// Provide some useful processor features. /***********************************************************************************/ diff --git a/Private/NewBoot/BootKit/Vendor/Qr.hxx b/Private/NewBoot/BootKit/Vendor/Qr.hxx new file mode 100644 index 00000000..7fec429e --- /dev/null +++ b/Private/NewBoot/BootKit/Vendor/Qr.hxx @@ -0,0 +1,837 @@ +#ifndef QR_H +#define QR_H + +#include +#include +#include + +#include +#include +#include +#include + +namespace qr { +inline uint8_t min_poly = + 0b11101, /* Minimal polynomial x^8 + x^4 + x^3 + x^2 + 1 */ + generator = 0b10; /* Generator of Galois field */ + +/// @brief galois finite field multiplication. +inline uint8_t gf_mul(uint8_t a, uint8_t b) { + uint8_t res = 0; + + for (; b; b >>= 1) { + if (b & 1) res ^= a; + if (a & 0x80) + a = (a << 1) ^ min_poly; + else + a <<= 1; + } + + return res; +} + +// Size of Ecc block with respect to level and version. 0 version is for +// padding. +constexpr int ECC_CODEWORDS_PER_BLOCK[4][41] = { + {0, 7, 10, 15, 20, 26, 18, 20, 24, 30, 18, 20, 24, 26, + 30, 22, 24, 28, 30, 28, 28, 28, 28, 30, 30, 26, 28, 30, + 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30}, + {0, 10, 16, 26, 18, 24, 16, 18, 22, 22, 26, 30, 22, 22, + 24, 24, 28, 28, 26, 26, 26, 26, 28, 28, 28, 28, 28, 28, + 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28}, + {0, 13, 22, 18, 26, 18, 24, 18, 22, 20, 24, 28, 26, 24, + 20, 30, 24, 28, 28, 26, 30, 28, 30, 30, 30, 30, 28, 30, + 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30}, + {0, 17, 28, 22, 16, 22, 28, 26, 26, 24, 28, 24, 28, 22, + 24, 24, 30, 28, 28, 26, 28, 30, 24, 30, 30, 30, 30, 30, + 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30}, +}; + +// Number of Ecc blocks with respect to level and version. 0 version is for +// padding. +constexpr int N_ECC_BLOCKS[4][41] = { + {0, 1, 1, 1, 1, 1, 2, 2, 2, 2, 4, 4, 4, 4, + 4, 6, 6, 6, 6, 7, 8, 8, 9, 9, 10, 12, 12, 12, + 13, 14, 15, 16, 17, 18, 19, 19, 20, 21, 22, 24, 25}, + {0, 1, 1, 1, 2, 2, 4, 4, 4, 5, 5, 5, 8, 9, + 9, 10, 10, 11, 13, 14, 16, 17, 17, 18, 20, 21, 23, 25, + 26, 28, 29, 31, 33, 35, 37, 38, 40, 43, 45, 47, 49}, + {0, 1, 1, 2, 2, 4, 4, 6, 6, 8, 8, 8, 10, 12, + 16, 12, 17, 16, 18, 21, 20, 23, 23, 25, 27, 29, 34, 34, + 35, 38, 40, 43, 45, 48, 51, 53, 56, 59, 62, 65, 68}, + {0, 1, 1, 2, 4, 4, 4, 5, 6, 8, 8, 11, 11, 16, + 16, 18, 16, 19, 21, 25, 25, 25, 34, 30, 32, 35, 37, 40, + 42, 45, 48, 51, 54, 57, 60, 63, 66, 70, 74, 77, 81}, +}; + +// Positions of central modules of alignment patterns according to version. 0 +// version is for padding. +constexpr int ALIGN_POS[41][7] = { + {}, + {0}, + {6, 18}, + {6, 22}, + {6, 26}, + {6, 30}, + {6, 34}, + {6, 22, 38}, + {6, 24, 42}, + {6, 26, 46}, + {6, 28, 50}, + {6, 30, 54}, + {6, 32, 58}, + {6, 34, 62}, + {6, 26, 46, 66}, + {6, 26, 48, 70}, + {6, 26, 50, 74}, + {6, 30, 54, 78}, + {6, 30, 56, 82}, + {6, 30, 58, 86}, + {6, 34, 62, 90}, + {6, 28, 50, 72, 94}, + {6, 26, 50, 74, 98}, + {6, 30, 54, 78, 102}, + {6, 28, 54, 80, 106}, + {6, 32, 58, 84, 110}, + {6, 30, 58, 86, 114}, + {6, 34, 62, 90, 118}, + {6, 26, 50, 74, 98, 122}, + {6, 30, 54, 78, 102, 126}, + {6, 26, 52, 78, 104, 130}, + {6, 30, 56, 82, 108, 134}, + {6, 34, 60, 86, 112, 138}, + {6, 30, 58, 86, 114, 142}, + {6, 34, 62, 90, 118, 146}, + {6, 30, 54, 78, 102, 126, 150}, + {6, 24, 50, 76, 102, 128, 154}, + {6, 28, 54, 80, 106, 132, 158}, + {6, 32, 58, 84, 110, 136, 162}, + {6, 26, 54, 82, 110, 138, 166}, + {6, 30, 58, 86, 114, 142, 170}, +}; + +// Return n-th bit of arr starting from MSB. +constexpr uint8_t get_bit_r(uint8_t *arr, int n) { + return (arr[n >> 3] >> (7 - (n & 7))) & 1; +} + +// Add up to 16 bits to arr. Data starts from MSB as well as each byte of an +// array. +constexpr void add_bits(uint16_t data, int n, uint8_t *arr, size_t &pos) { + while (n--) { + arr[pos >> 3] |= ((data >> n) & 1) << (7 - (pos & 7)); + ++pos; + } +} + +// Translate char to alphanumeric encoding value, +constexpr int alphanumeric(char c) { + if (c >= '0' && c <= '9') return c - '0'; + + if (c >= 'A' && c <= 'Z') return c - 'A' + 10; + + switch (c) { + case ' ': + return 36; + case '$': + return 37; + case '%': + return 38; + case '*': + return 39; + case '+': + return 40; + case '-': + return 41; + case '.': + return 42; + case '/': + return 43; + case ':': + return 44; + } + return -1; +} + +// Check if string can be encoded in alphanumeric mode. +constexpr bool is_alphanumeric(const char *str, size_t len) { + for (size_t i = 0; i < len; ++i) + if (alphanumeric(str[i]) == -1) return false; + return true; +} + +// Check if string can be encoded in numeric mode. +constexpr bool is_numeric(const char *str, size_t len) { + for (size_t i = 0; i < len; ++i) + if (str[i] < '0' || str[i] > '9') return false; + return true; +} + +// Check if string can be encoded in kanji mode. +constexpr bool is_kanji(const char *str, size_t len) { + for (size_t i = 0; i < len; i += 2) { + uint16_t val = uint16_t(str[i]) | (uint16_t(str[i + 1]) << 8); + if (val < 0x8140 || val > 0xebbf || (val > 0x9ffc && val < 0xe040)) + return false; + } + return true; +} + +// Reed-Solomon Ecc generator polynomial for the given degree. +constexpr void gf_gen_poly(int degree, uint8_t *poly) { + SetMem(poly, 0, degree); + + uint8_t root = poly[degree - 1] = 1; + + for (int i = 0; i < degree; ++i) { + for (int j = 0; j < degree - 1; ++j) + poly[j] = gf_mul(poly[j], root) ^ poly[j + 1]; + poly[degree - 1] = gf_mul(poly[degree - 1], root); + root = (root << 1) ^ ((root >> 7) * 0x11d); + } +} + +// Polynomial division if Galois Field. +constexpr void gf_poly_div(uint8_t *dividend, size_t len, uint8_t *divisor, + int degree, uint8_t *result) { + SetMem(result, 0, degree); + + for (size_t i = 0; i < len; ++i) { + uint8_t factor = dividend[i] ^ result[0]; + MoveMem(&result[0], &result[1], degree - 1); + result[degree - 1] = 0; + for (int j = 0; j < degree; ++j) result[j] ^= gf_mul(divisor[j], factor); + } +} + +enum Ecc { + L, + M, + Q, + H, +}; + +enum Mode { + M_NUMERIC, + M_ALPHANUMERIC, + M_BYTE, + M_KANJI, +}; + +// Select appropriate encoding mode for string. +constexpr Mode select_mode(const char *str, size_t len) { + if (is_numeric(str, len)) return M_NUMERIC; + if (is_alphanumeric(str, len)) return M_ALPHANUMERIC; + if (is_kanji(str, len)) return M_KANJI; + return M_BYTE; +} + +// Return size of Character Control Indicator in bits for given version and +// mode. +constexpr int cci(int ver, Mode mode) { + constexpr int cnt[4][3] = { + {10, 12, 14}, + {9, 11, 13}, + {8, 16, 16}, + {8, 10, 12}, + }; + if (ver < 10) return cnt[mode][0]; + if (ver < 27) return cnt[mode][1]; + return cnt[mode][2]; +} + +template +struct Qr { +private: + friend class QrDelegate; + bool draw(int x, int y) noexcept; + +public: + constexpr auto side_size() const { return SIDE; } + constexpr auto data_size() const { return N_BITS; } + constexpr auto data_ptr() const { return code; } + + bool module(int x, int y); + bool encode(const char *str, size_t len, Ecc ecc, int mask = -1); + + private: + bool encode_data(const char *data, size_t len, Ecc ecc, uint8_t *out); + void encode_ecc(uint8_t *data, Ecc ecc, uint8_t *out); + + void add_data(uint8_t *data, uint8_t *patterns); + void add_patterns(); + void add_version(); + void add_format(Ecc ecc, int mask); + void reserve_patterns(uint8_t *out); + + template + void draw_rect(int y, int x, int height, int width, uint8_t *out); + template + void draw_bound(int y, int x, int height, int width, uint8_t *out); + + template + int rule_1_3_score(); + int penalty_score(); + int select_mask(Ecc ecc, uint8_t *patterns); + void apply_mask(int mask, uint8_t *patterns); + + private: + static_assert(V <= 40, "invalid version"); + static constexpr int SIDE = 17 + V * 4; + static constexpr int N_BITS = SIDE * SIDE; + static constexpr int N_ALIGN = V == 1 ? 0 : V / 7 + 2; + static constexpr int N_ALIGN_BITS = V > 1 ? (N_ALIGN *N_ALIGN - 3) * 25 : 0; + static constexpr int N_TIMING_BITS = + (SIDE - 16) * 2 - (10 * (V > 1 ? N_ALIGN - 2 : 0)); + static constexpr int N_VER_BITS = V > 6 ? 36 : 0; + static constexpr int N_DAT_BITS = + N_BITS - (192 + N_ALIGN_BITS + N_TIMING_BITS + 31 + N_VER_BITS); + static constexpr int N_BYTES = N_BITS; // Actual number of bytes_in_bits + // required to store whole Qr code + static constexpr int N_DAT_BYTES = + N_DAT_BITS; // Actual number of bytes_in_bits required to store + // [data + ecc] + static constexpr int N_DAT_CAPACITY = + N_DAT_BITS >> 3; // Capacity of [data + ecc] without remainder bits + private: + /// @brief internal function to retrieve bit from a bitset. + uint8_t get_arr_bit(uint8_t *arr, uint64_t bit) const { + return ((volatile uint8_t *)arr)[bit]; + } + + /// @brief internal function to set bit from a bitset. + bool set_arr_bit(uint8_t *arr, uint64_t bit) { + if (((volatile uint8_t *)arr)[bit] == 0) { + ((volatile uint8_t *)arr)[bit] = 1; + + return true; + } + + return false; + } + + /// @brief internal function to clear bit from a bitset. + bool clr_arr_bit(uint8_t *arr, uint64_t bit) { + if (((volatile uint8_t *)arr)[bit] == 1) { + ((volatile uint8_t *)arr)[bit] = 0; + + return true; + } + + return false; + } + + uint8_t code[N_BITS] = {0}; + + bool status = false; +}; + +// Get color of a module from left-to-right and top-to-bottom. Black is true. +template +bool Qr::module(int x, int y) { + return get_arr_bit(code, y * SIDE + x); +} + +/// @brief draw a new QR code. +template +bool Qr::draw(int whereX, int whereY) noexcept { + if (!this->status) return false; // it may be invalid. + + for (int y = 0; y < (this->side_size()); ++y) { + for (int x = 0; x < (this->side_size()); ++x) { + ToolboxDrawZone( + (this->module(x, y) ? RGB(00, 00, 00) : RGB(FF, FF, FF)), + 1, 1, + x + whereX, y + whereY); + } + } + + return false; +} + +// Create Qr code with given error correction level. If mask == -1, +// then best mask selected automatically. NOTE: Automatic mask is the +// most expensive operation. Takes about 95 % of all computation time. +template +bool Qr::encode(const char *str, size_t len, Ecc ecc, int mask) { + uint8_t data[N_DAT_BYTES] = {}; + uint8_t data_with_ecc[N_DAT_BYTES] = {}; + uint8_t patterns[N_BYTES] = {}; + + if (!encode_data(str, len, ecc, data)) { + return status = false; + } + + encode_ecc(data, ecc, data_with_ecc); + + reserve_patterns(patterns); + CopyMem(code, patterns, N_BYTES); + + add_data(data_with_ecc, patterns); + add_patterns(); + add_version(); + + mask = mask != -1 ? mask & 7 : select_mask(ecc, patterns); + + add_format(ecc, mask); + apply_mask(mask, patterns); + + return status = true; +} + +template +bool Qr::encode_data(const char *data, size_t len, Ecc ecc, uint8_t *out) { + Mode mode = select_mode(data, len); + + size_t n_bits = + (N_DAT_CAPACITY - ECC_CODEWORDS_PER_BLOCK[ecc][V] * N_ECC_BLOCKS[ecc][V]) + << 3; + size_t pos = 0; + + add_bits(1 << mode, 4, out, pos); + add_bits(len, cci(V, mode), out, pos); + + if (mode == M_NUMERIC) { + const size_t triplets = len / 3; + const size_t triplets_size = triplets * 3; + const size_t rem = len % 3; + const size_t rem_bits = rem == 2 ? 7 : rem == 1 ? 4 : 0; + const size_t total_size = 10 * triplets + rem_bits; + + if (pos + total_size > n_bits) return false; + + char buf[4] = {}; + + for (size_t i = 0; i < triplets_size; i += 3) { + buf[0] = data[i]; + buf[1] = data[i + 1]; + buf[2] = data[i + 2]; + + uint16_t num = StringToLong(buf, NULL, 10); + add_bits(num, 10, out, pos); + } + + if (rem) { + buf[0] = data[triplets_size]; + buf[1] = data[triplets_size + 1]; + buf[rem] = 0; + + uint16_t num = StringToLong(buf, NULL, 10); + add_bits(num, rem_bits, out, pos); + } + } else if (mode == M_ALPHANUMERIC) { + if (pos + 11 * (int(len & ~1ul) / 2) > n_bits) return false; + + for (int i = 0; i < int(len & ~1ul); i += 2) { + uint16_t num = alphanumeric(data[i]) * 45 + alphanumeric(data[i + 1]); + add_bits(num, 11, out, pos); + } + if (len & 1) { + if (pos + 6 > n_bits) return false; + + add_bits(alphanumeric(data[len - 1]), 6, out, pos); + } + + } else if (mode == M_BYTE) { + if (pos + len * 8 > n_bits) return false; + + for (size_t i = 0; i < len; ++i) add_bits(data[i], 8, out, pos); + + } else { + if (pos + 13 * (len / 2) > n_bits) return false; + + for (size_t i = 0; i < len; i += 2) { + uint16_t val = ((uint8_t)data[i]) | (((uint8_t)data[i + 1]) << 8); + uint16_t res = 0; + val -= val < 0x9FFC ? 0x8140 : 0xC140; + res += val & 0xff; + res += (val >> 8) * 0xc0; + add_bits(res, 13, out, pos); + } + } + + size_t padding = n_bits - pos; + size_t i = 0; + + add_bits(0, padding > 4 ? 4 : padding, out, pos); + + if (pos & 7) add_bits(0, (8 - pos) & 7, out, pos); + + while (pos < n_bits) add_bits(++i & 1 ? 0xec : 0x11, 8, out, pos); + + return true; +} + +template +void Qr::encode_ecc(uint8_t *data, Ecc ecc, uint8_t *out) { + int n_blocks = N_ECC_BLOCKS[ecc][V]; + int ecc_len = ECC_CODEWORDS_PER_BLOCK[ecc][V]; + + int n_data_bytes = N_DAT_CAPACITY - ecc_len * n_blocks; + + int n_short_blocks = n_blocks - N_DAT_CAPACITY % n_blocks; + int short_len = N_DAT_CAPACITY / n_blocks - ecc_len; + + uint8_t gen_poly[30]; + uint8_t ecc_buf[30]; + + gf_gen_poly(ecc_len, gen_poly); + + uint8_t *data_ptr = data; + + for (int i = 0; i < n_blocks; ++i) { + int data_len = short_len; + + if (i >= n_short_blocks) ++data_len; + + gf_poly_div(data_ptr, data_len, gen_poly, ecc_len, ecc_buf); + + for (int j = 0, k = i; j < data_len; ++j, k += n_blocks) { + if (j == short_len) k -= n_short_blocks; + out[k] = data_ptr[j]; + } + for (int j = 0, k = n_data_bytes + i; j < ecc_len; ++j, k += n_blocks) + out[k] = ecc_buf[j]; + + data_ptr += data_len; + } +} + +template +void Qr::add_data(uint8_t *data, uint8_t *patterns) { + int data_pos = 0; + + for (int x = SIDE - 1; x >= 1; x -= 2) { + if (x == 6) x = 5; + + for (int i = 0; i < SIDE; ++i) { + int y = !((x + 1) & 2) ? SIDE - 1 - i : i; + int coord = y * SIDE + x; + + if (!get_arr_bit(patterns, coord)) { + if (get_bit_r(data, data_pos)) set_arr_bit(code, coord); + + ++data_pos; + } + + if (!get_arr_bit(patterns, coord - 1)) { + if (get_bit_r(data, data_pos)) set_arr_bit(code, coord - 1); + + ++data_pos; + } + } + } +} + +template +void Qr::add_patterns() { + // White bounds inside finders + draw_bound(1, 1, 5, 5, code); + draw_bound(1, SIDE - 6, 5, 5, code); + draw_bound(SIDE - 6, 1, 5, 5, code); + + // Finish alignment patterns + for (int i = 0; i < N_ALIGN; ++i) { + for (int j = 0; j < N_ALIGN; ++j) { + if ((!i && !j) || (!i && j == N_ALIGN - 1) || (!j && i == N_ALIGN - 1)) + continue; + draw_bound(ALIGN_POS[V][i] - 1, ALIGN_POS[V][j] - 1, 3, 3, code); + } + } + + // Draw white separators + draw_rect(7, 0, 1, 8, code); + draw_rect(0, 7, 8, 1, code); + draw_rect(SIDE - 8, 0, 1, 8, code); + draw_rect(SIDE - 8, 7, 8, 1, code); + draw_rect(7, SIDE - 8, 1, 8, code); + draw_rect(0, SIDE - 8, 8, 1, code); + + // Perforate timing patterns + for (int i = 7; i < SIDE - 7; i += 2) { + clr_arr_bit(code, 6 * SIDE + i); + clr_arr_bit(code, i * SIDE + 6); + } +} + +template +void Qr::add_version() { + if (V < 7) return; + + uint32_t rem = V; + + for (uint8_t i = 0; i < 12; ++i) rem = (rem << 1) ^ ((rem >> 11) * 0x1F25); + + uint32_t data = V << 12 | rem; + + for (int x = 0; x < 6; ++x) { + for (int j = 0; j < 3; ++j) { + int y = SIDE - 11 + j; + + bool black = (data >> (x * 3 + j)) & 1; + + if (!black) { + clr_arr_bit(code, y * SIDE + x); + clr_arr_bit(code, y + SIDE * x); + } + } + } +} + +template +void Qr::add_format(Ecc ecc, int mask) { + int data = (ecc ^ 1) << 3 | mask; + int rem = data; + + for (int i = 0; i < 10; i++) rem = (rem << 1) ^ ((rem >> 9) * 0b10100110111); + + int res = (data << 10 | rem) ^ 0b101010000010010; + + for (int i = 0; i < 6; ++i) { + if ((res >> i) & 1) { + set_arr_bit(code, SIDE * 8 + SIDE - 1 - i); + set_arr_bit(code, SIDE * i + 8); + } else { + clr_arr_bit(code, SIDE * 8 + SIDE - 1 - i); + clr_arr_bit(code, SIDE * i + 8); + } + } + + for (int i = 6; i < 8; ++i) { + if ((res >> i) & 1) { + set_arr_bit(code, SIDE * 8 + SIDE - 1 - i); + set_arr_bit(code, SIDE * (i + 1) + 8); + } else { + clr_arr_bit(code, SIDE * 8 + SIDE - 1 - i); + clr_arr_bit(code, SIDE * (i + 1) + 8); + } + } + + if ((res >> 8) & 1) { + set_arr_bit(code, SIDE * 8 + 7); + set_arr_bit(code, SIDE * (SIDE - 7) + 8); + } else { + clr_arr_bit(code, SIDE * 8 + 7); + clr_arr_bit(code, SIDE * (SIDE - 7) + 8); + } + + for (int i = 9, j = 5; i < 15; ++i, --j) { + if ((res >> i) & 1) { + set_arr_bit(code, SIDE * 8 + j); + set_arr_bit(code, SIDE * (SIDE - 1 - j) + 8); + } else { + clr_arr_bit(code, SIDE * 8 + j); + clr_arr_bit(code, SIDE * (SIDE - 1 - j) + 8); + } + } +} + +template +template +void Qr::draw_rect(int y, int x, int height, int width, uint8_t *out) { + if (B) { + for (int dy = y * SIDE; dy < (y + height) * SIDE; dy += SIDE) + for (int dx = x; dx < x + width; ++dx) set_arr_bit(out, dy + dx); + } else { + for (int dy = y * SIDE; dy < (y + height) * SIDE; dy += SIDE) + for (int dx = x; dx < x + width; ++dx) clr_arr_bit(out, dy + dx); + } +} + +template +template +void Qr::draw_bound(int y, int x, int height, int width, uint8_t *out) { + if (B) { + for (int i = y * SIDE + x; i < y * SIDE + x + width; ++i) + set_arr_bit(out, i); + for (int i = (y + height - 1) * SIDE + x; + i < (y + height - 1) * SIDE + x + width; ++i) + set_arr_bit(out, i); + for (int i = (y + 1) * SIDE + x; i < (y + height - 1) * SIDE + x; i += SIDE) + set_arr_bit(out, i); + for (int i = (y + 1) * SIDE + x + width - 1; + i < (y + height - 1) * SIDE + x + width - 1; i += SIDE) + set_arr_bit(out, i); + } else { + for (int i = y * SIDE + x; i < y * SIDE + x + width; ++i) + clr_arr_bit(out, i); + for (int i = (y + height - 1) * SIDE + x; + i < (y + height - 1) * SIDE + x + width; ++i) + clr_arr_bit(out, i); + for (int i = (y + 1) * SIDE + x; i < (y + height - 1) * SIDE + x; i += SIDE) + clr_arr_bit(out, i); + for (int i = (y + 1) * SIDE + x + width - 1; + i < (y + height - 1) * SIDE + x + width - 1; i += SIDE) + clr_arr_bit(out, i); + } +} + +template +void Qr::reserve_patterns(uint8_t *out) { + draw_rect(0, 6, SIDE, 1, out); + draw_rect(6, 0, 1, SIDE, out); + + draw_rect(0, 0, 9, 9, out); + draw_rect(SIDE - 8, 0, 8, 9, out); + draw_rect(0, SIDE - 8, 9, 8, out); + + for (int i = 0; i < N_ALIGN; ++i) { + for (int j = 0; j < N_ALIGN; ++j) { + if ((!i && !j) || (!i && j == N_ALIGN - 1) || (!j && i == N_ALIGN - 1)) + continue; + draw_rect(ALIGN_POS[V][i] - 2, ALIGN_POS[V][j] - 2, 5, 5, out); + } + } + + if (V >= 7) { + draw_rect(SIDE - 11, 0, 3, 6, out); + draw_rect(0, SIDE - 11, 6, 3, out); + } +} + +template +template +int Qr::rule_1_3_score() { + constexpr int y_max = H ? N_BITS : SIDE; + constexpr int x_max = H ? SIDE : N_BITS; + constexpr int y_step = H ? SIDE : 1; + constexpr int x_step = H ? 1 : SIDE; + + int res = 0; + + for (int y = 0; y < y_max; y += y_step) { + bool color = get_arr_bit(code, y); + int finder = color; + int cnt = 1; + for (int x = 1; x < x_max; x += x_step) { + if (get_arr_bit(code, y + x) == color) { + ++cnt; + if (cnt == 5) res += 3; + if (cnt > 5) ++res; + } else { + color = !color; + cnt = 1; + } + // Finder-like + finder = ((finder << 1) & 0x7ff) | color; + if (x >= x_step * 10) { + if (finder == 0x05d || finder == 0x5d0) res += 40; + } + } + } + return res; +} + +template +int Qr::penalty_score() { + int res = 0; + + res += rule_1_3_score(); + res += rule_1_3_score(); + + for (int y = 0; y < N_BITS - SIDE; y += SIDE) { + for (int x = 0; x < SIDE - 1; ++x) { + bool c = get_arr_bit(code, y + x); + + if (c == get_arr_bit(code, y + x + 1) && + c == get_arr_bit(code, y + x + SIDE) && + c == get_arr_bit(code, y + x + SIDE + 1)) + res += 3; + } + } + + int black = 0; + for (int y = 0; y < N_BITS; y += SIDE) { + for (int x = 0; x < SIDE; ++x) black += get_arr_bit(code, y + x); + } + res += abs((black * 100) / N_BITS - 50) / 5 * 10; + + return res; +} + +template +int Qr::select_mask(Ecc ecc, uint8_t *patterns) { + unsigned min_score = -1; + unsigned score = 0; + uint8_t mask = 0; + + for (int i = 0; i < 8; ++i) { + add_format(ecc, i); + apply_mask(i, patterns); + score = penalty_score(); + if (score < min_score) { + mask = i; + min_score = score; + } + apply_mask(i, patterns); + } + return mask; +} + +template +void Qr::apply_mask(int mask, uint8_t *patterns) { + for (int y = 0, dy = 0; y < SIDE; ++y, dy += SIDE) { + for (int x = 0; x < SIDE; ++x) { + int coord = dy + x; + + if (get_arr_bit(patterns, coord)) continue; + + bool keep = true; + + switch (mask) { + case 0: + keep = (x + y) & 1; + break; + case 1: + keep = y & 1; + break; + case 2: + keep = x % 3; + break; + case 3: + keep = (x + y) % 3; + break; + case 4: + keep = (y / 2 + x / 3) & 1; + break; + case 5: + keep = x * y % 2 + x * y % 3; + break; + case 6: + keep = (x * y % 2 + x * y % 3) & 1; + break; + case 7: + keep = ((x + y) % 2 + x * y % 3) & 1; + break; + } + + if (!keep) { + if (get_arr_bit(code, coord)) + clr_arr_bit(code, coord); + else + set_arr_bit(code, coord); + } + } + } +} + +/// @brief QR code encoder class. +class QrDelegate final { +public: + explicit QrDelegate() = default; + ~QrDelegate() = default; + + /// @brief Draw method delegate. + template + bool draw(Qr& subject, int x, int y) noexcept { + return subject.draw(x, y); + } + +}; +} // namespace qr + +namespace NewOS::Qr { + using namespace qr; +} // namespace NewOS + +#endif diff --git a/Private/NewBoot/BootKit/Vendor/QrPrelude.hxx b/Private/NewBoot/BootKit/Vendor/QrPrelude.hxx new file mode 100644 index 00000000..31bd93da --- /dev/null +++ b/Private/NewBoot/BootKit/Vendor/QrPrelude.hxx @@ -0,0 +1 @@ +#include diff --git a/Private/NewBoot/BootKit/Vendor/Support.hxx b/Private/NewBoot/BootKit/Vendor/Support.hxx new file mode 100644 index 00000000..4d35b4cb --- /dev/null +++ b/Private/NewBoot/BootKit/Vendor/Support.hxx @@ -0,0 +1,90 @@ +/* ------------------------------------------- + + Copyright Mahrouss Logic + +------------------------------------------- */ + +#pragma once + +/// @file Purpose of this file is to help port libs into the bootloader. + +#include + +#define LONG_MAX ((long)(~0UL>>1)) +#define LONG_MIN (~LONG_MAX) + +#define SetMem(dst, c, sz) BSetMem((CharacterTypeUTF16 *)dst, c, sz) +#define MoveMem(dst, src, sz) BCopyMem((CharacterTypeUTF16 *)dst, (CharacterTypeUTF16 *)src, sz) +#define CopyMem(dst, src, sz) BCopyMem((CharacterTypeUTF16 *)dst, (CharacterTypeUTF16 *)src, sz) + +inline int isspace(int c) { return c == ' '; } + +inline long StringToLong(const char * nptr, char ** endptr, int base) { + const char *p = nptr, *endp; + bool is_neg = 0, overflow = 0; + /* Need unsigned so (-LONG_MIN) can fit in these: */ + unsigned long n = 0UL, cutoff; + int cutlim; + if (base < 0 || base == 1 || base > 36) { + return 0L; + } + endp = nptr; + while (isspace(*p)) + p++; + if (*p == '+') { + p++; + } else if (*p == '-') { + is_neg = 1, p++; + } + if (*p == '0') { + p++; + /* For strtol(" 0xZ", &endptr, 16), endptr should point to 'x'; + * pointing to ' ' or '0' is non-compliant. + * (Many implementations do this wrong.) */ + endp = p; + if (base == 16 && (*p == 'X' || *p == 'x')) { + p++; + } else if (base == 2 && (*p == 'B' || *p == 'b')) { + /* C23 standard supports "0B" and "0b" prefixes. */ + p++; + } else if (base == 0) { + if (*p == 'X' || *p == 'x') { + base = 16, p++; + } else if (*p == 'B' || *p == 'b') { + base = 2, p++; + } else { + base = 8; + } + } + } else if (base == 0) { + base = 10; + } + cutoff = (is_neg) ? -(LONG_MIN / base) : LONG_MAX / base; + cutlim = (is_neg) ? -(LONG_MIN % base) : LONG_MAX % base; + while (1) { + int c; + if (*p >= 'A') + c = ((*p - 'A') & (~('a' ^ 'A'))) + 10; + else if (*p <= '9') + c = *p - '0'; + else + break; + if (c < 0 || c >= base) break; + endp = ++p; + if (overflow) { + /* endptr should go forward and point to the non-digit character + * (of the given base); required by ANSI standard. */ + if (endptr) continue; + break; + } + if (n > cutoff || (n == cutoff && c > cutlim)) { + overflow = 1; continue; + } + n = n * base + c; + } + if (endptr) *endptr = (char *)endp; + if (overflow) { + return ((is_neg) ? LONG_MIN : LONG_MAX); + } + return (long)((is_neg) ? -n : n); +} diff --git a/Private/NewBoot/Source/CDROM/SplashScreen.fmt b/Private/NewBoot/Source/CDROM/SplashScreen.fmt index a3dba676..339b94e7 100644 --- a/Private/NewBoot/Source/CDROM/SplashScreen.fmt +++ b/Private/NewBoot/Source/CDROM/SplashScreen.fmt @@ -1,4 +1,4 @@ -Welcome to the NeWS. +Welcome to NeWS. Brought to you by: * MicroKernel, Bootloader: Amlal EL Mahrouss. diff --git a/Private/NewBoot/Source/HEL/AMD64/BootAHCI.cxx b/Private/NewBoot/Source/HEL/AMD64/BootAHCI.cxx index d736ac59..d04a94d3 100644 --- a/Private/NewBoot/Source/HEL/AMD64/BootAHCI.cxx +++ b/Private/NewBoot/Source/HEL/AMD64/BootAHCI.cxx @@ -15,4 +15,7 @@ * */ + +#include +#include #include diff --git a/Private/NewBoot/Source/HEL/AMD64/BootATA.cxx b/Private/NewBoot/Source/HEL/AMD64/BootATA.cxx index 4e41ba2e..d3573064 100644 --- a/Private/NewBoot/Source/HEL/AMD64/BootATA.cxx +++ b/Private/NewBoot/Source/HEL/AMD64/BootATA.cxx @@ -15,8 +15,9 @@ * */ -#include +#include #include +#include /// bugs: 0 diff --git a/Private/NewBoot/Source/HEL/AMD64/BootFileReader.cxx b/Private/NewBoot/Source/HEL/AMD64/BootFileReader.cxx index 33067380..aab5db1f 100644 --- a/Private/NewBoot/Source/HEL/AMD64/BootFileReader.cxx +++ b/Private/NewBoot/Source/HEL/AMD64/BootFileReader.cxx @@ -8,6 +8,8 @@ ------------------------------------------- */ +#include +#include #include #include #include diff --git a/Private/NewBoot/Source/HEL/AMD64/BootMain.cxx b/Private/NewBoot/Source/HEL/AMD64/BootMain.cxx index 42852b5d..d314c949 100644 --- a/Private/NewBoot/Source/HEL/AMD64/BootMain.cxx +++ b/Private/NewBoot/Source/HEL/AMD64/BootMain.cxx @@ -4,6 +4,7 @@ ------------------------------------------- */ +#include #include #include #include @@ -58,9 +59,6 @@ EFI_EXTERN_C EFI_API Int Main(EfiHandlePtr ImageHandle, .Write(SystemTable->FirmwareVendor) .Write(L"\r\n"); - BootDeviceATA ataDev; - Boolean isGptFound = No; - UInt32 MapKey = 0; UInt32* SizePtr = nullptr; EfiMemoryDescriptor* Descriptor = nullptr; @@ -185,7 +183,7 @@ EFI_EXTERN_C EFI_API Int Main(EfiHandlePtr ImageHandle, L"New Boot can't run this architecture."); } - BootMainKind main = (BootMainKind) nullptr; + NewOS::HEL::BootMainKind main = (NewOS::HEL::BootMainKind) nullptr; if (!main) { EFI::RaiseHardError(L"Bad-Exec", diff --git a/Private/NewBoot/Source/HEL/AMD64/BootPlatform.cxx b/Private/NewBoot/Source/HEL/AMD64/BootPlatform.cxx index d0da09b7..f47e3532 100644 --- a/Private/NewBoot/Source/HEL/AMD64/BootPlatform.cxx +++ b/Private/NewBoot/Source/HEL/AMD64/BootPlatform.cxx @@ -4,6 +4,8 @@ ------------------------------------------- */ +#include +#include #include EXTERN_C void rt_hlt() { asm volatile("hlt"); } diff --git a/Private/NewBoot/Source/HEL/AMD64/BootString.cxx b/Private/NewBoot/Source/HEL/AMD64/BootString.cxx index 1c6b528e..ef0e4744 100644 --- a/Private/NewBoot/Source/HEL/AMD64/BootString.cxx +++ b/Private/NewBoot/Source/HEL/AMD64/BootString.cxx @@ -11,6 +11,8 @@ ------------------------------------------- */ +#include +#include #include /// bugs 0 diff --git a/Private/NewBoot/Source/HEL/AMD64/BootTextWriter.cxx b/Private/NewBoot/Source/HEL/AMD64/BootTextWriter.cxx index 2ebde023..81aa6c9d 100644 --- a/Private/NewBoot/Source/HEL/AMD64/BootTextWriter.cxx +++ b/Private/NewBoot/Source/HEL/AMD64/BootTextWriter.cxx @@ -11,6 +11,8 @@ ------------------------------------------- */ +#include +#include #include /// BUGS: 0 diff --git a/Private/NewBoot/Source/HEL/AMD64/New+Delete.cxx b/Private/NewBoot/Source/HEL/AMD64/New+Delete.cxx index 1bb2d9ca..77552ef8 100644 --- a/Private/NewBoot/Source/HEL/AMD64/New+Delete.cxx +++ b/Private/NewBoot/Source/HEL/AMD64/New+Delete.cxx @@ -4,6 +4,8 @@ ------------------------------------------- */ +#include +#include #include #include /* Since we're using GCC for this EFI program. */ diff --git a/Private/NewBoot/Source/HEL/AMD64/Support.cxx b/Private/NewBoot/Source/HEL/AMD64/Support.cxx new file mode 100644 index 00000000..c6b62630 --- /dev/null +++ b/Private/NewBoot/Source/HEL/AMD64/Support.cxx @@ -0,0 +1,32 @@ +/* ------------------------------------------- + + Copyright Mahrouss Logic + +------------------------------------------- */ + +#include +#include +#include + +/// @brief memset definition in C++. +/// @param dst destination pointer. +/// @param byte value to fill in. +/// @param len length of of src. +EXTERN_C VoidPtr memset(void *dst, int byte, + long long unsigned int len) { + SetMem(dst, byte, len); + return dst; +} + +/// @brief memcpy definition in C++. +/// @param dst destination pointer. +/// @param src source pointer. +/// @param len length of of src. +EXTERN_C VoidPtr memcpy(void *dst, const void *src, + long long unsigned int len) { + CopyMem(dst, src, len); + return dst; +} + +/// @brief somthing specific to the microsoft ABI, regarding checking the stack. +EXTERN_C void ___chkstk_ms(void) {} diff --git a/Private/NewBoot/Source/makefile b/Private/NewBoot/Source/makefile index 2f9e3756..11c1da75 100644 --- a/Private/NewBoot/Source/makefile +++ b/Private/NewBoot/Source/makefile @@ -36,7 +36,7 @@ FLAG_GNU=-fshort-wchar -D__EFI_x86_64__ -mno-red-zone -D__KERNEL__ -D__NEWBOOT__ invalid-recipe: @echo "invalid-recipe: Use make bootloader- instead." -KERNEL_OBJ=kernel.bin +KERNEL_OBJ=boot.bin DD=dd IMG_CREATE=qemu-img MAX_KERNEL_SIZE=1024K diff --git a/Private/Source/ProcessScheduler.cxx b/Private/Source/ProcessScheduler.cxx index 6d766d27..69236c18 100644 --- a/Private/Source/ProcessScheduler.cxx +++ b/Private/Source/ProcessScheduler.cxx @@ -25,8 +25,10 @@ namespace NewOS { /// Exit Code stuff /***********************************************************************************/ -static Int32 kExitCode = 0; +STATIC Int32 kExitCode = 0U; +/// @brief Gets the latest exit code. +/// @note Not thread-safe. const Int32 &rt_get_exit_code() noexcept { return kExitCode; } /***********************************************************************************/ @@ -65,8 +67,8 @@ VoidPtr ProcessHeader::New(const SizeT &sz) { /* @brief checks if runtime pointer is in region. */ bool rt_in_pool_region(VoidPtr pool_ptr, VoidPtr pool, const SizeT &sz) { - Char *_pool_ptr = (Char *)pool_ptr; - Char *_pool = (Char *)pool; + UIntPtr *_pool_ptr = (UIntPtr *)pool_ptr; + UIntPtr *_pool = (UIntPtr *)pool; for (SizeT index = sz; _pool[sz] != kUserHeapMag; --index) { if (&_pool[index] > &_pool_ptr[sz]) continue; @@ -97,10 +99,13 @@ Boolean ProcessHeader::Delete(VoidPtr ptr, const SizeT &sz) { return false; } +/// @brief process name getter. const Char *ProcessHeader::GetName() { return this->Name; } +/// @brief process selector getter. const ProcessSelector &ProcessHeader::GetSelector() { return this->Selector; } +/// @brief process status getter. const ProcessStatus &ProcessHeader::GetStatus() { return this->Status; } /***********************************************************************************/ -- cgit v1.2.3 From f6a38d6c14b314d7b85855f311527ede869db96f Mon Sep 17 00:00:00 2001 From: Amlal El Mahrouss Date: Thu, 25 Apr 2024 08:19:06 +0200 Subject: MHR-16: see below. - Use QR-code to redirect to support page inside bootloader. - Start working on NewLoader, since the PEF linker is done. Signed-off-by: Amlal El Mahrouss --- Doxyfile | 5 +- Private/Docs/SPECIFICATION.md | 62 ++++++ Private/Docs/TODO-LIST.md | 23 ++ Private/Documentation/.gitkeep | 0 Private/Documentation/Spec.md | 62 ------ Private/Documentation/Todo.md | 21 -- Private/Documentation/kernel-design.drawio | 70 ------ Private/FirmwareKit/EFI/API.hxx | 18 +- Private/NewBoot/BootKit/Vendor/Qr.hxx | 36 ++- Private/NewBoot/BootKit/Vendor/QrVendor/base.h | 25 +++ Private/NewBoot/BootKit/Vendor/QrVendor/bit.h | 245 +++++++++++++++++++++ .../NewBoot/Source/HEL/AMD64/BootFileReader.cxx | 6 +- Private/NewBoot/Source/HEL/AMD64/BootMain.cxx | 10 +- Private/NewLoader/Source/.gitkeep | 0 Private/makefile | 5 +- 15 files changed, 393 insertions(+), 195 deletions(-) create mode 100644 Private/Docs/SPECIFICATION.md create mode 100644 Private/Docs/TODO-LIST.md delete mode 100644 Private/Documentation/.gitkeep delete mode 100644 Private/Documentation/Spec.md delete mode 100644 Private/Documentation/Todo.md delete mode 100644 Private/Documentation/kernel-design.drawio create mode 100644 Private/NewBoot/BootKit/Vendor/QrVendor/base.h create mode 100644 Private/NewBoot/BootKit/Vendor/QrVendor/bit.h create mode 100644 Private/NewLoader/Source/.gitkeep diff --git a/Doxyfile b/Doxyfile index a52de5be..7fd58842 100644 --- a/Doxyfile +++ b/Doxyfile @@ -943,7 +943,8 @@ WARN_LOGFILE = # spaces. See also FILE_PATTERNS and EXTENSION_MAPPING # Note: If this tag is empty the current directory is searched. -INPUT = ./Private/ \ +INPUT = ./ \ + ./Private/ \ ./Public/ \ # This tag can be used to specify the character encoding of the source files @@ -1159,7 +1160,7 @@ FILTER_SOURCE_PATTERNS = # (index.html). This can be useful if you have a project on for instance GitHub # and want to reuse the introduction page also for the doxygen output. -USE_MDFILE_AS_MAINPAGE = +USE_MDFILE_AS_MAINPAGE = ./ReadMe.md # The Fortran standard specifies that for fixed formatted Fortran code all # characters from position 72 are to be considered as comment. A common diff --git a/Private/Docs/SPECIFICATION.md b/Private/Docs/SPECIFICATION.md new file mode 100644 index 00000000..e218947e --- /dev/null +++ b/Private/Docs/SPECIFICATION.md @@ -0,0 +1,62 @@ +=================================== + +# 0: General Information + +=================================== + +- ABI and Format: PEF/PE32+. +- Kernel architecture: Portable hybrid kernel. +- Language: C++/(Assembly (AMD64, X64000, X86S, ARM64, POWER, RISCV)) + +=================================== + +# 1: The NewKernel + +=================================== + +- Drive/Device Abstraction. +- SMP, Preemptive Multi Threading. +- Separation of Files/Devices. +- Networking. +- Hardware Abstraction Layer. +- Native Filesystem support (NewFS, FAT32 and ffs2). +- Program Loaders. +- Thread Local Storage. +- Semaphore, Locks, Timers. +- Canary mechanisms. +- Dynamic Libraries. +- Cross Platform. +- Permission Selectors. + +=================================== + +# 2: The Filesystem + +=================================== + +- Catalog object with associated forks. +- Large storage support. +- Long file names. +- UNIX path style. + +================================== + +# 3: Common naming conventions: + +================================== + +- Kernel -> ke_init_x +- RunTime -> rt_copy_mem +- Hal -> hal_foo_bar + +=================================== + +# 4: The NewBoot + +=================================== + +- Capable of booting from a network drive. +- Loads a PE file which is the kernel. +- Sanity checks, based on the number of sections. +- Handover compliant. +- Does check for a valid partition (useful in the case of recovering) diff --git a/Private/Docs/TODO-LIST.md b/Private/Docs/TODO-LIST.md new file mode 100644 index 00000000..c997ce10 --- /dev/null +++ b/Private/Docs/TODO-LIST.md @@ -0,0 +1,23 @@ +# TODO list. + +- We need preemptive multi-threading. [ X ] +- We then need sync primitives. [ X ] +- We also need a system library for the OS. [ X ] +- We need a bootloader for AMD64 [ X ] + - Implement Boot Services [ X ] + - Design Handover [ X ] + - Load kernel into memory [ X ] + - Fix bug in kernel loader, which causes a 06 #UD. [ X ] + - Load Kernel [ X ] + - Add IDT [ X ] + - AHCI driver [ WiP ] +- Context switch x87/SSE/AVX registers [ X ] +- Framebuffer [ X ] +- AHCI support [ ] +- Make installer [ ] + +Status: + +NewBoot: Need to boot from EPM partition. +
+NewKernel: New Filesystem in progress. diff --git a/Private/Documentation/.gitkeep b/Private/Documentation/.gitkeep deleted file mode 100644 index e69de29b..00000000 diff --git a/Private/Documentation/Spec.md b/Private/Documentation/Spec.md deleted file mode 100644 index e218947e..00000000 --- a/Private/Documentation/Spec.md +++ /dev/null @@ -1,62 +0,0 @@ -=================================== - -# 0: General Information - -=================================== - -- ABI and Format: PEF/PE32+. -- Kernel architecture: Portable hybrid kernel. -- Language: C++/(Assembly (AMD64, X64000, X86S, ARM64, POWER, RISCV)) - -=================================== - -# 1: The NewKernel - -=================================== - -- Drive/Device Abstraction. -- SMP, Preemptive Multi Threading. -- Separation of Files/Devices. -- Networking. -- Hardware Abstraction Layer. -- Native Filesystem support (NewFS, FAT32 and ffs2). -- Program Loaders. -- Thread Local Storage. -- Semaphore, Locks, Timers. -- Canary mechanisms. -- Dynamic Libraries. -- Cross Platform. -- Permission Selectors. - -=================================== - -# 2: The Filesystem - -=================================== - -- Catalog object with associated forks. -- Large storage support. -- Long file names. -- UNIX path style. - -================================== - -# 3: Common naming conventions: - -================================== - -- Kernel -> ke_init_x -- RunTime -> rt_copy_mem -- Hal -> hal_foo_bar - -=================================== - -# 4: The NewBoot - -=================================== - -- Capable of booting from a network drive. -- Loads a PE file which is the kernel. -- Sanity checks, based on the number of sections. -- Handover compliant. -- Does check for a valid partition (useful in the case of recovering) diff --git a/Private/Documentation/Todo.md b/Private/Documentation/Todo.md deleted file mode 100644 index 2c4af6e5..00000000 --- a/Private/Documentation/Todo.md +++ /dev/null @@ -1,21 +0,0 @@ -- We need preemptive multi-threading. [ X ] -- We then need sync primitives. [ X ] -- We also need a system library for the OS. [ X ] -- We need a bootloader for AMD64 [ X ] - - Implement Boot Services [ X ] - - Design Handover [ X ] - - Load kernel into memory [ X ] - - Fix bug in kernel loader, which causes a 06 #UD. [ X ] - - Load Kernel [ X ] - - Add IDT [ X ] - - AHCI driver [ WiP ] -- Context switch x87/SSE/AVX registers [ X ] -- Framebuffer [ X ] -- AHCI support [ ] -- Make installer [ ] - -Status: - -NewBoot: Need to boot from EPM partition. -NewKernel: New Filesystem in progress. - diff --git a/Private/Documentation/kernel-design.drawio b/Private/Documentation/kernel-design.drawio deleted file mode 100644 index d78ac170..00000000 --- a/Private/Documentation/kernel-design.drawio +++ /dev/null @@ -1,70 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/Private/FirmwareKit/EFI/API.hxx b/Private/FirmwareKit/EFI/API.hxx index 212f3686..0e2ef200 100644 --- a/Private/FirmwareKit/EFI/API.hxx +++ b/Private/FirmwareKit/EFI/API.hxx @@ -61,9 +61,11 @@ enum { inline UInt32 Platform() noexcept { return kPEMachineAMD64; } /*** - * @brief Raise Hard kernel error. + * @brief Throw an error, stop execution as well. + * @param ErrorCode error code to be print. + * @param Reason reason to be print. */ -inline void RaiseHardError(const EfiCharType *ErrorCode, +inline void ThrowError(const EfiCharType *ErrorCode, const EfiCharType *Reason) noexcept { #ifdef __DEBUG__ ST->ConOut->OutputString(ST->ConOut, L"\r\n*** STOP ***\r\n"); @@ -88,19 +90,19 @@ inline void RaiseHardError(const EfiCharType *ErrorCode, /// Show the QR code now. - constexpr auto ver = 7; + constexpr auto ver = 4; auto ecc = qr::Ecc::H; - auto str = "https://www.mahrouss-logic.com/help"; - auto len = BStrLen(L"https://www.mahrouss-logic.com/help"); + auto str = "https://el-mahrouss-logic.com/"; + auto len = BStrLen(L"https://el-mahrouss-logic.com/"); qr::Qr encoder; qr::QrDelegate encoderDelegate; - encoder.encode(str, len, ecc, -1); // Automatic mask. + encoder.encode(str, len, ecc, 0); // Manual mask 0 /// tell delegate to draw encoded QR. - encoderDelegate.draw(encoder, (kHandoverHeader->f_GOP.f_Width - encoder.side_size()) / 2, - (kHandoverHeader->f_GOP.f_Height - encoder.side_size()) - 20); + encoderDelegate.draw(encoder, (kHandoverHeader->f_GOP.f_Width - encoder.side_size()) - 20, + (kHandoverHeader->f_GOP.f_Height - encoder.side_size()) / 2); #endif // ifdef __NEWBOOT__ diff --git a/Private/NewBoot/BootKit/Vendor/Qr.hxx b/Private/NewBoot/BootKit/Vendor/Qr.hxx index 7fec429e..ca5eb566 100644 --- a/Private/NewBoot/BootKit/Vendor/Qr.hxx +++ b/Private/NewBoot/BootKit/Vendor/Qr.hxx @@ -5,6 +5,9 @@ #include #include +#include +#include + #include #include #include @@ -276,7 +279,7 @@ public: void apply_mask(int mask, uint8_t *patterns); private: - static_assert(V <= 40, "invalid version"); + static_assert(V >= 1 && V <= 40, "invalid version"); static constexpr int SIDE = 17 + V * 4; static constexpr int N_BITS = SIDE * SIDE; static constexpr int N_ALIGN = V == 1 ? 0 : V / 7 + 2; @@ -286,42 +289,29 @@ public: static constexpr int N_VER_BITS = V > 6 ? 36 : 0; static constexpr int N_DAT_BITS = N_BITS - (192 + N_ALIGN_BITS + N_TIMING_BITS + 31 + N_VER_BITS); - static constexpr int N_BYTES = N_BITS; // Actual number of bytes_in_bits + static constexpr int N_BYTES = utl::bytes_in_bits(N_BITS); // Actual number of bytes_in_bits // required to store whole Qr code - static constexpr int N_DAT_BYTES = - N_DAT_BITS; // Actual number of bytes_in_bits required to store + static constexpr int N_DAT_BYTES = utl::bytes_in_bits(N_DAT_BITS); // Actual number of bytes_in_bits required to store // [data + ecc] static constexpr int N_DAT_CAPACITY = N_DAT_BITS >> 3; // Capacity of [data + ecc] without remainder bits private: /// @brief internal function to retrieve bit from a bitset. - uint8_t get_arr_bit(uint8_t *arr, uint64_t bit) const { - return ((volatile uint8_t *)arr)[bit]; + uint8_t get_arr_bit(uint8_t *arr, unsigned bit) const { + return utl::get_arr_bit(arr, bit); } /// @brief internal function to set bit from a bitset. - bool set_arr_bit(uint8_t *arr, uint64_t bit) { - if (((volatile uint8_t *)arr)[bit] == 0) { - ((volatile uint8_t *)arr)[bit] = 1; - - return true; - } - - return false; + void set_arr_bit(uint8_t *arr, unsigned bit) { + utl::set_arr_bit(arr, bit); } /// @brief internal function to clear bit from a bitset. - bool clr_arr_bit(uint8_t *arr, uint64_t bit) { - if (((volatile uint8_t *)arr)[bit] == 1) { - ((volatile uint8_t *)arr)[bit] = 0; - - return true; - } - - return false; + void clr_arr_bit(uint8_t *arr, unsigned bit) { + utl::clr_arr_bit(arr, bit); } - uint8_t code[N_BITS] = {0}; + uint8_t code[N_BYTES] = {}; bool status = false; }; diff --git a/Private/NewBoot/BootKit/Vendor/QrVendor/base.h b/Private/NewBoot/BootKit/Vendor/QrVendor/base.h new file mode 100644 index 00000000..d8261d1e --- /dev/null +++ b/Private/NewBoot/BootKit/Vendor/QrVendor/base.h @@ -0,0 +1,25 @@ +#ifndef UTL_BASE_H +#define UTL_BASE_H + +#include +#include +#include + +namespace utl { + +/** + * @brief Helper to get number of elements in array. + * + * @tparam T Auto-deduced element type + * @tparam N Auto-deduced number of elements + * @return Array size + */ +template +constexpr size_t countof(T(&)[N]) +{ + return N; +} + +} + +#endif \ No newline at end of file diff --git a/Private/NewBoot/BootKit/Vendor/QrVendor/bit.h b/Private/NewBoot/BootKit/Vendor/QrVendor/bit.h new file mode 100644 index 00000000..646151b6 --- /dev/null +++ b/Private/NewBoot/BootKit/Vendor/QrVendor/bit.h @@ -0,0 +1,245 @@ +#ifndef UTL_BIT_H +#define UTL_BIT_H + +#include + +namespace utl { + +/** + * @brief Size of object in terms of bits. + * + * @tparam T Object type + * @return Number of bits + */ +template +constexpr auto bit_size() +{ + return sizeof(T) * 8; +} + +/** + * @brief Integer with all bits set to 1. + * + * @tparam T Integer type + * @return All set integer + */ +template +constexpr T bit_full() +{ + return T(-1); +} + +/** + * @brief Wrap around mask for power of two number of bits + * within given integer type. For example: + * [ bit_wrap = 8 - 1 = 0b111 ] + * [ bit_wrap = 16 - 1 = 0b1111 ] + * [ bit_wrap = 32 - 1 = 0b11111 ] + * + * @tparam T Integer type + * @return Wrap around mask for number of bits + */ +template +constexpr T bit_wrap() +{ + return bit_size() - 1; +} + +/** + * @brief Number of bits to fit bit_wrap result, in other words + * bit width of (sizeof(T) * 8 - 1). For example: + * [ bit_shft = bit_width(0b111) = 3 ] + * [ bit_shft = bit_width(0b1111) = 4 ] + * [ bit_shft = bit_width(0b11111) = 5 ] + * + * @tparam T Integer type + * @return Number of bits to shift to divide by sizeof(T) * 8 + */ +template +constexpr auto bit_shft() +{ + return std::bit_width(bit_wrap()); +} + +/** + * @brief Round up division by number of bits within given integer type, + * which sizeof(T) * 8 is power of two. + * + * @tparam T Inetegr type + * @param x Dividend + * @return Quotient + */ +template +constexpr auto bit_ceil(auto x) +{ + return (x + bit_wrap()) >> bit_shft(); +} + +/** + * @brief Count leading zeros. + * + * @param x Unsigned integer argument + * @return Number of leading zeros + */ +constexpr unsigned cntlz(auto x) +{ + if constexpr (std::is_same_v) + return std::countl_zero(unsigned(x)); + else + return std::countl_zero(x); +} + +/** + * @brief Count trailing zeros. + * + * @param x Unsigned integer argument + * @return Number of trailing zeros + */ +constexpr unsigned cnttz(auto x) +{ + if constexpr (std::is_same_v) + return std::countr_zero(unsigned(x)); + else + return std::countr_zero(x); +} + +/** + * @brief Get number of words (integers) required to store N bits. + * + * @tparam T Word integer type + * @param n Number of bits to store + * @return Number of words + */ +template +constexpr size_t words_in_bits(size_t n) +{ + return (n >> bit_shft()) + !!(n & bit_wrap()); +} + +/** + * @brief Get number of bytes required to store N bits. + * + * @param n Number of bits to store + * @return Number of bytes + */ +constexpr size_t bytes_in_bits(size_t n) +{ + return words_in_bits(n); +} + +/** + * @brief Make integer with bit at given position. + * + * @tparam T Inetegr type + * @param n Bit position + * @return Integer with set bit + */ +template +constexpr T bit(int n) +{ + return T(1) << n; +} + +/** + * @brief Get n-th bit of an integer. + * + * @tparam T Integer type + * @param x Integer + * @param n Bit position from LSB + * @return true if set + */ +template +constexpr bool get_bit(T x, int n) +{ + return (x >> n) & 1; +} + +/** + * @brief Set n-th bit of an integer. + * + * @tparam T Integer type + * @param x Integer + * @param n Bit position from LSB + */ +template +constexpr void set_bit(T& x, int n) +{ + x |= 1 << n; +} + +/** + * @brief Clear n-th bit of an integer. + * + * @tparam T Integer type + * @param x Integer + * @param n Bit position from LSB + */ +template +constexpr void clr_bit(T& x, int n) +{ + x &= ~(1 << n); +} + +/** + * @brief Get n-th bit in array of words (starting from LSB). + * + * @tparam T Word type + * @param p Array of words + * @param n Index of bit to get + * @return true if set + */ +template +constexpr bool get_arr_bit(const T* p, unsigned n) +{ + return get_bit(p[n >> bit_shft()], n & bit_wrap()); +} + +/** + * @brief Set n-th bit in array of words (starting from LSB). + * + * @tparam T Word type + * @param p Array of words + * @param n Index of bit to set + */ +template +constexpr void set_arr_bit(T* p, unsigned n) +{ + set_bit(p[n >> bit_shft()], n & bit_wrap()); +} + +/** + * @brief Clear n-th bit in array of words (starting from LSB). + * + * @tparam T Word type + * @param p Array of words + * @param n Index of bit to clear + */ +template +constexpr void clr_arr_bit(T* p, unsigned n) +{ + clr_bit(p[n >> bit_shft()], n & bit_wrap()); +} + +/** + * @brief Shift bits left in array of integer elements from least significant bit + * and considering 0-th byte as the right most. + * uint16_t example: 0b10000000'11100001 ==> 0b00000001'11000010. + * + * @tparam T Integer type + * @tparam L Length of array + * @param x Array of integers, nullptr not acceptable! + * @param len Number of elements + */ +template +constexpr void shift_left(T (&x)[L]) +{ + for (int i = L - 1; i > 0; --i) { + x[i] <<= 1; + x[i] |= x[i - 1] >> bit_wrap(); + } + x[0] <<= 1; +} + +} + +#endif diff --git a/Private/NewBoot/Source/HEL/AMD64/BootFileReader.cxx b/Private/NewBoot/Source/HEL/AMD64/BootFileReader.cxx index aab5db1f..0e126ada 100644 --- a/Private/NewBoot/Source/HEL/AMD64/BootFileReader.cxx +++ b/Private/NewBoot/Source/HEL/AMD64/BootFileReader.cxx @@ -66,7 +66,7 @@ BFileReader::BFileReader(const CharacterTypeUTF16* path, if (efp->OpenVolume(efp, &rootFs) != kEfiOk) { mWriter.Write(L"New Boot: Fetch-Protocol: No-Such-Volume").Write(L"\r\n"); - EFI::RaiseHardError(L"NoSuchVolume", L"No Such volume."); + EFI::ThrowError(L"NoSuchVolume", L"No Such volume."); this->mErrorCode = kNotSupported; return; } @@ -78,7 +78,7 @@ BFileReader::BFileReader(const CharacterTypeUTF16* path, mWriter.Write(L"New Boot: Fetch-Protocol: No-Such-Path: ") .Write(mPath) .Write(L"\r\n"); - EFI::RaiseHardError(L"NoSuchPath", L"No Such file on filesystem."); + EFI::ThrowError(L"NoSuchPath", L"No Such file on filesystem."); this->mErrorCode = kNotSupported; return; } @@ -110,7 +110,7 @@ Void BFileReader::ReadAll(SizeT until, SizeT chunk) { if (auto err = BS->AllocatePool(EfiLoaderCode, until, (VoidPtr*)&mBlob) != kEfiOk) { mWriter.Write(L"*** EFI-Code: ").Write(err).Write(L" ***\r\n"); - EFI::RaiseHardError(L"NewBoot_PageError", L"Allocation error."); + EFI::ThrowError(L"NewBoot_PageError", L"Allocation error."); } } diff --git a/Private/NewBoot/Source/HEL/AMD64/BootMain.cxx b/Private/NewBoot/Source/HEL/AMD64/BootMain.cxx index d314c949..7120bcd9 100644 --- a/Private/NewBoot/Source/HEL/AMD64/BootMain.cxx +++ b/Private/NewBoot/Source/HEL/AMD64/BootMain.cxx @@ -67,7 +67,7 @@ EFI_EXTERN_C EFI_API Int Main(EfiHandlePtr ImageHandle, if (BS->AllocatePool(EfiLoaderData, sizeof(UInt32), (VoidPtr*)&SizePtr) != kEfiOk) { - EFI::RaiseHardError(L"Bad-Alloc", L"New Boot ran out of memory!"); + EFI::ThrowError(L"Bad-Alloc", L"New Boot ran out of memory!"); } /**** @@ -80,7 +80,7 @@ EFI_EXTERN_C EFI_API Int Main(EfiHandlePtr ImageHandle, if (BS->AllocatePool(EfiLoaderData, sizeof(EfiMemoryDescriptor), (VoidPtr*)&Descriptor) != kEfiOk) { - EFI::RaiseHardError(L"Bad-Alloc", L"New Boot ran out of memory!"); + EFI::ThrowError(L"Bad-Alloc", L"New Boot ran out of memory!"); } HEL::HandoverInformationHeader* handoverHdrPtr = nullptr; @@ -179,14 +179,14 @@ EFI_EXTERN_C EFI_API Int Main(EfiHandlePtr ImageHandle, headerKind->Magic[3] == kPefMagic[3] && headerKind->Magic[4] == kPefMagic[4]) { if (headerKind->Abi != kPefAbi || headerKind->Cpu != kPefArchAMD64) { - EFI::RaiseHardError(L"Bad-Architecture", + EFI::ThrowError(L"Bad-Architecture", L"New Boot can't run this architecture."); } NewOS::HEL::BootMainKind main = (NewOS::HEL::BootMainKind) nullptr; if (!main) { - EFI::RaiseHardError(L"Bad-Exec", + EFI::ThrowError(L"Bad-Exec", L"New Boot can't recognize this executable."); } @@ -200,7 +200,7 @@ EFI_EXTERN_C EFI_API Int Main(EfiHandlePtr ImageHandle, } } - EFI::RaiseHardError(L"Invalid-PEF-Executable", L"PEF executable expected. Got something else."); + EFI::ThrowError(L"Invalid-PEF-Executable", L"PEF executable expected. Got something else."); return kEfiFail; } diff --git a/Private/NewLoader/Source/.gitkeep b/Private/NewLoader/Source/.gitkeep new file mode 100644 index 00000000..e69de29b diff --git a/Private/makefile b/Private/makefile index 41f70c81..673a4b56 100644 --- a/Private/makefile +++ b/Private/makefile @@ -28,10 +28,12 @@ COPY = cp # Add assembler, linker, and object files variables. ASMFLAGS = -f win64 + +# NewOS subsystem is 17. LDFLAGS = -e Main --subsystem=17 LDOBJ = Objects/*.obj -# This file is the kernel, responsible of task management, memory, drivers and more. +# This file is the kernel, responsible of task management and memory. KERNEL = NewKernel.exe # The kernel entrypoint @@ -39,6 +41,7 @@ SCRIPT = --script=Linker/Platforms/PC.lds .PHONY: error error: + @echo "=== ERROR ===" @echo "=> Use a specific target." MOVEALL=./MoveAll.sh -- cgit v1.2.3 From 1cae0d2cde6e775ecb1625aa93a5d65d996efad0 Mon Sep 17 00:00:00 2001 From: Amlal El Mahrouss Date: Thu, 25 Apr 2024 09:38:24 +0200 Subject: MHR-16: Load NewLoader correctly. Signed-off-by: Amlal El Mahrouss --- Private/HALKit/AMD64/HalProcessor.cpp | 2 +- Private/HALKit/AMD64/Storage/AHCI.cxx | 8 ++++---- Private/NewBoot/Source/HEL/AMD64/BootMain.cxx | 16 ++++++++-------- ReadMe.md | 4 ++-- 4 files changed, 15 insertions(+), 15 deletions(-) diff --git a/Private/HALKit/AMD64/HalProcessor.cpp b/Private/HALKit/AMD64/HalProcessor.cpp index 4fea4e7e..61d98c8c 100644 --- a/Private/HALKit/AMD64/HalProcessor.cpp +++ b/Private/HALKit/AMD64/HalProcessor.cpp @@ -8,7 +8,7 @@ /** * @file Processor.cpp - * @brief This file is about processor specific functions (in/out...) + * @brief This file is about processor specific functions (in/out/cli/std...) */ namespace NewOS::HAL { diff --git a/Private/HALKit/AMD64/Storage/AHCI.cxx b/Private/HALKit/AMD64/Storage/AHCI.cxx index 5e6b3348..c9db540a 100644 --- a/Private/HALKit/AMD64/Storage/AHCI.cxx +++ b/Private/HALKit/AMD64/Storage/AHCI.cxx @@ -33,11 +33,11 @@ NewOS::Boolean drv_std_init(NewOS::UInt16& PortsImplemented) { for (SizeT devIndex = 0; devIndex < NEWOS_BUS_COUNT; ++devIndex) { if (iterator[devIndex].Leak().Subclass() == kSATASubClass && iterator[devIndex].Leak().ProgIf() == kSATAProgIfAHCI) { - iterator[devIndex].Leak().EnableMmio(); - kAhciDevice = iterator[devIndex].Leak(); + iterator[devIndex].Leak().EnableMmio(); /// enable the memory i/o for this ahci device. + kAhciDevice = iterator[devIndex].Leak(); /// and then leak the reference. kcout << "NewKernel: [PCI] Found AHCI controller.\r\n"; - + return true; } } @@ -54,4 +54,4 @@ NewOS::Void drv_std_read(NewOS::UInt64 Lba, NewOS::Char* Buf, NewOS::Void drv_std_write(NewOS::UInt64 Lba, NewOS::Char* Buf, NewOS::SizeT SectorSz, NewOS::SizeT Size) {} -#endif // __AHCI__ \ No newline at end of file +#endif // __AHCI__ diff --git a/Private/NewBoot/Source/HEL/AMD64/BootMain.cxx b/Private/NewBoot/Source/HEL/AMD64/BootMain.cxx index 7120bcd9..cdbb2f36 100644 --- a/Private/NewBoot/Source/HEL/AMD64/BootMain.cxx +++ b/Private/NewBoot/Source/HEL/AMD64/BootMain.cxx @@ -170,20 +170,20 @@ EFI_EXTERN_C EFI_API Int Main(EfiHandlePtr ImageHandle, kernelFile.ReadAll(MIB(1), 4096); if (kernelFile.Blob()) { - PEFContainer* headerKind = + PEFContainer* containerKind = reinterpret_cast(kernelFile.Blob()); - if (headerKind->Magic[0] == kPefMagic[0] && - headerKind->Magic[1] == kPefMagic[1] && - headerKind->Magic[2] == kPefMagic[2] && - headerKind->Magic[3] == kPefMagic[3] && - headerKind->Magic[4] == kPefMagic[4]) { - if (headerKind->Abi != kPefAbi || headerKind->Cpu != kPefArchAMD64) { + if (containerKind->Magic[0] == kPefMagic[0] && + containerKind->Magic[1] == kPefMagic[1] && + containerKind->Magic[2] == kPefMagic[2] && + containerKind->Magic[3] == kPefMagic[3] && + containerKind->Magic[4] == kPefMagic[4]) { + if (containerKind->Abi != kPefAbi || containerKind->Cpu != kPefArchAMD64) { EFI::ThrowError(L"Bad-Architecture", L"New Boot can't run this architecture."); } - NewOS::HEL::BootMainKind main = (NewOS::HEL::BootMainKind) nullptr; + NewOS::HEL::BootMainKind main = reinterpret_cast(containerKind + containerKind->Start); if (!main) { EFI::ThrowError(L"Bad-Exec", diff --git a/ReadMe.md b/ReadMe.md index e3b6ff8c..c169c960 100644 --- a/ReadMe.md +++ b/ReadMe.md @@ -1,6 +1,6 @@
- -

NewKernel

+ +

NewOS


-- cgit v1.2.3 From 4b7ec5d5d2351f47f3ce423147b956247997d532 Mon Sep 17 00:00:00 2001 From: Amlal El Mahrouss Date: Thu, 25 Apr 2024 10:12:17 +0200 Subject: MHR-16: Update EPM specs. Signed-off-by: Amlal El Mahrouss --- Private/FirmwareKit/EPM.hxx | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) diff --git a/Private/FirmwareKit/EPM.hxx b/Private/FirmwareKit/EPM.hxx index b7f77742..3b3585be 100644 --- a/Private/FirmwareKit/EPM.hxx +++ b/Private/FirmwareKit/EPM.hxx @@ -29,6 +29,7 @@ typedef struct BlockGUID { /** * @brief The EPM bootloader block. + * @note NumBlock and LbaStart are ignored on UEFI. */ struct PACKED BootBlock { NewOS::Char Magic[kEPMMagicLength]; @@ -42,7 +43,7 @@ struct PACKED BootBlock { /** * @brief The EPM partition block. - * used to describe a partition inside a media. + * used to describe a partition inside a media, doesn't exist on uefi. */ struct PACKED PartitionBlock { NewOS::Char Name[kEPMNameLength]; @@ -75,6 +76,10 @@ struct PACKED PartitionBlock { #define kEPMMagicPPC "EPMPC" +/* @brief UEFI magic for EPM */ + +#define kEPMMagicUEFI "EPMUE" + /* @brief Invalid magic for EPM */ #define kEPMMagicError "EPM??" @@ -109,7 +114,10 @@ typedef struct PartitionBlock PartitionBlockType; #define kEPMStartPartitionBlk (0) ///! @brief Current EPM revision (2) -#define kEPMRevision (21) +#define kEPMRevision (2) + +///! @brief Current EPM revision (2) +#define kEPMRevisionUEFI (0xF) /// END SPECS -- cgit v1.2.3 From 8b46ad6f40df85c1939196f0f75e46d212193756 Mon Sep 17 00:00:00 2001 From: Amlal El Mahrouss Date: Thu, 25 Apr 2024 10:21:19 +0200 Subject: MHR-16: Prevent other EFI from booting. Signed-off-by: Amlal El Mahrouss --- Private/FirmwareKit/EFI/API.hxx | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/Private/FirmwareKit/EFI/API.hxx b/Private/FirmwareKit/EFI/API.hxx index 0e2ef200..093d10b3 100644 --- a/Private/FirmwareKit/EFI/API.hxx +++ b/Private/FirmwareKit/EFI/API.hxx @@ -121,6 +121,13 @@ inline void InitEFI(EfiSystemTable *SystemTable) noexcept { ST->BootServices->SetWatchdogTimer(0, 0, 0, nullptr); ST->ConOut->EnableCursor(ST->ConOut, false); + + if (ST->FirmwareVendor[0] != '@' || + ST->FirmwareVendor[1] != 'M' || + ST->FirmwareVendor[1] != 'H' || + ST->FirmwareVendor[1] != 'R') { + EFI::ThrowError(L"Unsupported Firmware", L"Firmware is unsupported, please build OVMF by yourself."); + } } #ifdef __BOOTLOADER__ -- cgit v1.2.3 From d3c9b5287789534340146ffdb696f67aa8b7308d Mon Sep 17 00:00:00 2001 From: Amlal El Mahrouss Date: Thu, 25 Apr 2024 12:12:19 +0200 Subject: MHR-16: Format, and revert previous staged commit. Signed-off-by: Amlal El Mahrouss --- Private/FirmwareKit/EFI/API.hxx | 7 ------- Private/NewBoot/Source/HEL/AMD64/BootMain.cxx | 18 +++++++++++------- 2 files changed, 11 insertions(+), 14 deletions(-) diff --git a/Private/FirmwareKit/EFI/API.hxx b/Private/FirmwareKit/EFI/API.hxx index 093d10b3..0e2ef200 100644 --- a/Private/FirmwareKit/EFI/API.hxx +++ b/Private/FirmwareKit/EFI/API.hxx @@ -121,13 +121,6 @@ inline void InitEFI(EfiSystemTable *SystemTable) noexcept { ST->BootServices->SetWatchdogTimer(0, 0, 0, nullptr); ST->ConOut->EnableCursor(ST->ConOut, false); - - if (ST->FirmwareVendor[0] != '@' || - ST->FirmwareVendor[1] != 'M' || - ST->FirmwareVendor[1] != 'H' || - ST->FirmwareVendor[1] != 'R') { - EFI::ThrowError(L"Unsupported Firmware", L"Firmware is unsupported, please build OVMF by yourself."); - } } #ifdef __BOOTLOADER__ diff --git a/Private/NewBoot/Source/HEL/AMD64/BootMain.cxx b/Private/NewBoot/Source/HEL/AMD64/BootMain.cxx index cdbb2f36..356db88b 100644 --- a/Private/NewBoot/Source/HEL/AMD64/BootMain.cxx +++ b/Private/NewBoot/Source/HEL/AMD64/BootMain.cxx @@ -4,13 +4,13 @@ ------------------------------------------- */ -#include -#include #include #include +#include #include #include #include +#include /** Graphics related. */ @@ -178,16 +178,19 @@ EFI_EXTERN_C EFI_API Int Main(EfiHandlePtr ImageHandle, containerKind->Magic[2] == kPefMagic[2] && containerKind->Magic[3] == kPefMagic[3] && containerKind->Magic[4] == kPefMagic[4]) { - if (containerKind->Abi != kPefAbi || containerKind->Cpu != kPefArchAMD64) { + if (containerKind->Abi != kPefAbi || + containerKind->Cpu != kPefArchAMD64) { EFI::ThrowError(L"Bad-Architecture", - L"New Boot can't run this architecture."); + L"New Boot can't run this architecture."); } - NewOS::HEL::BootMainKind main = reinterpret_cast(containerKind + containerKind->Start); + NewOS::HEL::BootMainKind main = + reinterpret_cast(containerKind + + containerKind->Start); if (!main) { EFI::ThrowError(L"Bad-Exec", - L"New Boot can't recognize this executable."); + L"New Boot can't recognize this executable."); } EFI::ExitBootServices(MapKey, ImageHandle); @@ -200,7 +203,8 @@ EFI_EXTERN_C EFI_API Int Main(EfiHandlePtr ImageHandle, } } - EFI::ThrowError(L"Invalid-PEF-Executable", L"PEF executable expected. Got something else."); + EFI::ThrowError(L"Invalid-PEF-Executable", + L"PEF executable expected. Got something else."); return kEfiFail; } -- cgit v1.2.3 From 14f26421cc6ebd678c2b5a2a04fe6cdc63ee5d38 Mon Sep 17 00:00:00 2001 From: Amlal El Mahrouss Date: Thu, 25 Apr 2024 13:44:36 +0200 Subject: MHR-16: Adding BDiskFormatFactory according to MHR-16, bug fixes and improvements as well. Signed-off-by: Amlal El Mahrouss --- Private/DriverKit/KernelCall.c | 24 +++++ Private/DriverKit/KernelDev.h | 4 + Private/DriverKit/KernelDispatchCall.S | 2 +- Private/DriverKit/KernelStd.c | 24 ----- Private/FSKit/NewFS.hxx | 8 +- Private/NewBoot/BootKit/BootKit.hxx | 108 ++++++++++++++++--- Private/NewBoot/BootKit/HW/ATA.hxx | 4 +- Private/NewBoot/BootKit/Vendor/Qr.hxx | 3 + Private/NewBoot/Source/HEL/AMD64/BootATA.cxx | 11 +- Private/NewBoot/Source/HEL/AMD64/Support.cxx | 14 +++ Private/NewBoot/Source/HEL/POWER/BootCoreBoot.S | 34 ------ Private/NewBoot/Source/HEL/POWER/BootEPM.cxx | 118 --------------------- Private/NewBoot/Source/HEL/POWER/CoreBootStartup.S | 34 ++++++ Private/NewBoot/Source/makefile | 5 +- 14 files changed, 192 insertions(+), 201 deletions(-) create mode 100644 Private/DriverKit/KernelCall.c delete mode 100644 Private/DriverKit/KernelStd.c delete mode 100644 Private/NewBoot/Source/HEL/POWER/BootCoreBoot.S delete mode 100644 Private/NewBoot/Source/HEL/POWER/BootEPM.cxx create mode 100644 Private/NewBoot/Source/HEL/POWER/CoreBootStartup.S diff --git a/Private/DriverKit/KernelCall.c b/Private/DriverKit/KernelCall.c new file mode 100644 index 00000000..494ac0bc --- /dev/null +++ b/Private/DriverKit/KernelCall.c @@ -0,0 +1,24 @@ +/* ------------------------------------------- + + Copyright Mahrouss Logic + + Purpose: Kernel Definitions. + +------------------------------------------- */ + +#include +#include + +DK_EXTERN __attribute__((naked)) void __kernelDispatchCall(int32_t cnt, ...); + +DK_EXTERN void* kernelCall(const char* kernelRpcName, int32_t cnt, ...) { + if (!kernelRpcName || cnt == 0) return NIL; + + va_list arg; + va_start(arg, cnt); + + __kernelDispatchCall(cnt, arg); + + va_end(arg); + +} diff --git a/Private/DriverKit/KernelDev.h b/Private/DriverKit/KernelDev.h index daa60a7c..8b6888f0 100644 --- a/Private/DriverKit/KernelDev.h +++ b/Private/DriverKit/KernelDev.h @@ -10,7 +10,11 @@ #include +struct _kernelDevice; + +/// @brief Kernel Device driver. typedef struct _kernelDevice { + char name[255]; // the device name. Could be /./DEVICE_NAME/ int32_t(*read)(); // read from device. int32_t(*write)(); // write to device. struct _kernelDevice* (*open)(const char* path); // open device. diff --git a/Private/DriverKit/KernelDispatchCall.S b/Private/DriverKit/KernelDispatchCall.S index 4eec8ae0..64b6663e 100644 --- a/Private/DriverKit/KernelDispatchCall.S +++ b/Private/DriverKit/KernelDispatchCall.S @@ -14,7 +14,7 @@ __kernelDispatchCall: #elif defined(__powerpc64__) __kernelDispatchCall: - mflr 3 + /* There is no specific interrupt request id for a system call in POWER. */ sc blr diff --git a/Private/DriverKit/KernelStd.c b/Private/DriverKit/KernelStd.c deleted file mode 100644 index 494ac0bc..00000000 --- a/Private/DriverKit/KernelStd.c +++ /dev/null @@ -1,24 +0,0 @@ -/* ------------------------------------------- - - Copyright Mahrouss Logic - - Purpose: Kernel Definitions. - -------------------------------------------- */ - -#include -#include - -DK_EXTERN __attribute__((naked)) void __kernelDispatchCall(int32_t cnt, ...); - -DK_EXTERN void* kernelCall(const char* kernelRpcName, int32_t cnt, ...) { - if (!kernelRpcName || cnt == 0) return NIL; - - va_list arg; - va_start(arg, cnt); - - __kernelDispatchCall(cnt, arg); - - va_end(arg); - -} diff --git a/Private/FSKit/NewFS.hxx b/Private/FSKit/NewFS.hxx index 339b9832..cc43f51b 100644 --- a/Private/FSKit/NewFS.hxx +++ b/Private/FSKit/NewFS.hxx @@ -82,7 +82,7 @@ default. #define kNewFSLbaType (NewOS::Lba) /// Start After the PM headers, pad 1024 bytes. -#define kNewFSAddressAsLba (1024U) +#define kNewFSAddressAsLba (1024) #define kResourceTypeDialog 10 #define kResourceTypeString 11 @@ -95,6 +95,8 @@ default. #define kNewFSFlagUnallocated 0x00 #define kNewFSFlagCreated 0x0F +#define kNewFSMimeNameLen (216) + typedef NewOS::Char NewCharType; enum { @@ -106,10 +108,10 @@ enum { kNewFSDriveCount = 5, }; -/// @brief Ccatalog type. +/// @brief Catalog type. struct PACKED NewCatalog final { NewCharType Name[kNewFSNodeNameLen]; - NewCharType Mime[kNewFSNodeNameLen]; + NewCharType Mime[kNewFSMimeNameLen]; NewOS::Int32 Flags; NewOS::Int32 Kind; diff --git a/Private/NewBoot/BootKit/BootKit.hxx b/Private/NewBoot/BootKit/BootKit.hxx index 5c3a531d..15700f54 100644 --- a/Private/NewBoot/BootKit/BootKit.hxx +++ b/Private/NewBoot/BootKit/BootKit.hxx @@ -11,6 +11,22 @@ #pragma once +#include +#include + +/// include NewFS header and Support header as well. + +#include +#include +#include + +/***********************************************************************************/ +/// Include other APIs. +/***********************************************************************************/ + +#include +#include "Builtins/ATA/ATA.hxx" + /***********************************************************************************/ /// Framebuffer helpers. /***********************************************************************************/ @@ -22,15 +38,6 @@ class BFileReader; class BFileRunner; class BVersionString; -#include -#include - -/***********************************************************************************/ -/// Include other APIs. -/***********************************************************************************/ - -#include - ///! @note This address is reserved to NewKernel. #define kBootVirtualAddress (0xfffffff80000000) @@ -39,12 +46,6 @@ using namespace NewOS; typedef Char *PEFImagePtr; typedef Char *PEImagePtr; -enum { - kSegmentCode = 2, - kSegmentData = 4, - kSegmentBss = 6, -}; - typedef WideChar CharacterTypeUTF16; typedef Char CharacterTypeUTF8; @@ -169,3 +170,80 @@ static inline const UInt32 kRgbGreen = 0x0000FF00; static inline const UInt32 kRgbBlue = 0x00FF0000; static inline const UInt32 kRgbBlack = 0x00000000; static inline const UInt32 kRgbWhite = 0x00FFFFFF; + +/// @brief BootKit Disk Formatter. +template +class BDiskFormatFactory final { +public: + /// @brief File entry for **BDiskFormatFactory**. + struct BFileDescriptor final { + Char fFilename[255]; + Char fForkName[255]; + + VoidPtr fBlob; + SizeT fBlobSz; + + struct BFileDescriptor* fPrev; + struct BFileDescriptor* fNext; + }; + +public: + explicit BDiskFormatFactory() = default; + explicit BDiskFormatFactory(BootDev dev) : fDiskDev(dev) {} + ~BDiskFormatFactory() = default; + + NEWOS_COPY_DELETE(BDiskFormatFactory); + + /// @brief Format disk. + /// @param Partition Name + /// @param Blobs. + /// @param Number of blobs. + /// @retval True disk has been formatted. + /// @retval False failed to format. + Boolean Format(const char* partName, BFileDescriptor* fileBlobs, SizeT blobCount); + +private: + /// @brief Write all of the requested catalogs into the filesystem. + Boolean _AppendCatalogList(BFileDescriptor* fileBlobs, SizeT blobCount) { + return true; + } + +private: + BootDev fDiskDev; + +}; + +/// @brief Format disk. +/// @param Partition Name +/// @param Blobs. +/// @param Number of blobs. +/// @retval True disk has been formatted. +/// @retval False failed to format. +template +inline Boolean BDiskFormatFactory::Format(const char* partName, + BDiskFormatFactory::BFileDescriptor* fileBlobs, SizeT blobCount) { + // if (!fileBlobs || !blobCount) return false; + + static_assert(kNewFSMinimumSectorSz == kATASectorSize, "Sector size doesn't match!"); + + Char buf[kNewFSMinimumSectorSz] = { 0 }; + NewPartitionBlock* partBlock = reinterpret_cast(buf); + + memcpy(partBlock->PartitionName, partName, strlen(partName)); + + /// @note A catalog roughly equal to a sector. + + partBlock->CatalogCount = blobCount; + partBlock->Kind = kNewFSHardDrive; + partBlock->SectorCount = kNewFSMinimumSectorSz; + partBlock->FreeCatalog = fDiskDev.GetSectorsCount() - partBlock->CatalogCount; + partBlock->SectorCount = fDiskDev.GetSectorsCount(); + partBlock->FreeSectors = fDiskDev.GetSectorsCount() - partBlock->CatalogCount; + partBlock->StartCatalog = kNewFSAddressAsLba + sizeof(NewPartitionBlock); + + fDiskDev.Leak().mBase = (kNewFSAddressAsLba / kNewFSMinimumSectorSz); + fDiskDev.Leak().mSize = kNewFSMinimumSectorSz; + fDiskDev.Write(buf, kNewFSMinimumSectorSz); + + return this->_AppendCatalogList(fileBlobs, blobCount); +} diff --git a/Private/NewBoot/BootKit/HW/ATA.hxx b/Private/NewBoot/BootKit/HW/ATA.hxx index 9127e598..c557aeb8 100644 --- a/Private/NewBoot/BootKit/HW/ATA.hxx +++ b/Private/NewBoot/BootKit/HW/ATA.hxx @@ -34,6 +34,8 @@ class BootDeviceATA final : public Device { public: operator bool(); + SizeT GetSectorsCount() noexcept; + BootDeviceATA& Read(Char* Buf, const SizeT& SecCount) override; BootDeviceATA& Write(Char* Buf, const SizeT& SecCount) override; @@ -41,4 +43,4 @@ class BootDeviceATA final : public Device { private: ATATrait mTrait; -}; \ No newline at end of file +}; diff --git a/Private/NewBoot/BootKit/Vendor/Qr.hxx b/Private/NewBoot/BootKit/Vendor/Qr.hxx index ca5eb566..27db8060 100644 --- a/Private/NewBoot/BootKit/Vendor/Qr.hxx +++ b/Private/NewBoot/BootKit/Vendor/Qr.hxx @@ -12,6 +12,7 @@ #include #include #include +#include namespace qr { inline uint8_t min_poly = @@ -811,6 +812,8 @@ public: explicit QrDelegate() = default; ~QrDelegate() = default; + NEWOS_COPY_DEFAULT(QrDelegate); + /// @brief Draw method delegate. template bool draw(Qr& subject, int x, int y) noexcept { diff --git a/Private/NewBoot/Source/HEL/AMD64/BootATA.cxx b/Private/NewBoot/Source/HEL/AMD64/BootATA.cxx index d3573064..10d4272d 100644 --- a/Private/NewBoot/Source/HEL/AMD64/BootATA.cxx +++ b/Private/NewBoot/Source/HEL/AMD64/BootATA.cxx @@ -25,7 +25,7 @@ static Boolean kATADetected = false; static Int32 kATADeviceType = kATADeviceCount; -static CharacterTypeUTF8 kATAData[kATADataLen] = {0}; +static UInt16 kATAData[kATADataLen] = {0}; Boolean boot_ata_detected(Void); @@ -82,8 +82,6 @@ ATAInit_Retry: Out8(IO + ATA_REG_COMMAND, ATA_CMD_IDENTIFY); - BSetMem(kATAData, 0, kATADataLen); - /// fetch serial info /// model, speed, number of sectors... @@ -269,3 +267,10 @@ BootDeviceATA& BootDeviceATA::Write(CharacterTypeUTF8* Buf, const SizeT& SectorS * @return BootDeviceATA::ATATrait& the drive config. */ BootDeviceATA::ATATrait& BootDeviceATA::Leak() { return mTrait; } + +/*** + @brief Getter, gets the number of sectors inside the drive. +*/ +SizeT BootDeviceATA::GetSectorsCount() noexcept { + return kATAData[60] + kATAData[61]; +} diff --git a/Private/NewBoot/Source/HEL/AMD64/Support.cxx b/Private/NewBoot/Source/HEL/AMD64/Support.cxx index c6b62630..0508d491 100644 --- a/Private/NewBoot/Source/HEL/AMD64/Support.cxx +++ b/Private/NewBoot/Source/HEL/AMD64/Support.cxx @@ -28,5 +28,19 @@ EXTERN_C VoidPtr memcpy(void *dst, const void *src, return dst; } +/// @brief strlen definition in C++. +EXTERN_C size_t strlen(const char *whatToCheck) { + if (!whatToCheck || *whatToCheck == 0) return 0; + + SizeT len = 0; + + while (whatToCheck[len] != 0) { + ++len; + } + + return len; +} + + /// @brief somthing specific to the microsoft ABI, regarding checking the stack. EXTERN_C void ___chkstk_ms(void) {} diff --git a/Private/NewBoot/Source/HEL/POWER/BootCoreBoot.S b/Private/NewBoot/Source/HEL/POWER/BootCoreBoot.S deleted file mode 100644 index c611467d..00000000 --- a/Private/NewBoot/Source/HEL/POWER/BootCoreBoot.S +++ /dev/null @@ -1,34 +0,0 @@ -/* ------------------------------------------- - - Copyright Mahrouss Logic - -------------------------------------------- */ - -.section .boot_hdr -.align 4 - -/* NewBoot boot header begin */ - -boot_hdr_mag: - .ascii "LX" -boot_hdr_name: - // it has to match ten bytes. - .asciz "NewBoot\0\0\0" -boot_hdr_ver: - .word 0x104 -boot_hdr_proc: - .long bootloader_start - -/* NewOS boot header end */ - -.extern bootloader_main -.extern bootloader_stack - -.globl bootloader_start -bootloader_start: - mflr 4 /* real address of .Laddr */ - lwz 0,(bootloader_stack-bootloader_start)(4) /* stack address location */ - mr 1,0 /* use user defined stack */ - - bl bootloader_main - blr diff --git a/Private/NewBoot/Source/HEL/POWER/BootEPM.cxx b/Private/NewBoot/Source/HEL/POWER/BootEPM.cxx deleted file mode 100644 index 72276ef9..00000000 --- a/Private/NewBoot/Source/HEL/POWER/BootEPM.cxx +++ /dev/null @@ -1,118 +0,0 @@ -/* ------------------------------------------- - - Copyright Mahrouss Logic - -------------------------------------------- */ - -#include -#include - -#define kEPMSectorSize (1024U) -#define kEPMSwapSize MIB(16) - -// {310E1FC7-2060-425D-BE7B-75A37CC679BC} -STATIC const BlockGUID kEPMGuid = { - 0x310e1fc7, - 0x2060, - 0x425d, - {0xbe, 0x7b, 0x75, 0xa3, 0x7c, 0xc6, 0x79, 0xbc}}; - -/// @brief Write epm partition to disk. -/// @param namePart partition name -/// @param namePartLength length of name -/// @param bootDev disk interface. -/// @return -EXTERN_C Boolean boot_write_epm_partition(const Char* namePart, SizeT namePartLength, - BootDevice* bootDev) { - if (namePartLength > kEPMNameLength || !namePart) return No; - if (!bootDev) return No; - - bootDev->Leak().mBase = kEPMStartPartitionBlk; - bootDev->Leak().mSize = kEPMSectorSize; - - Char buf[kEPMSectorSize] = {0}; - - bootDev->Read(buf, 1); - - BTextWriter writer; - - writer.Write(L"NewBoot: Checking for an EPM partition...\r\n"); - - for (SizeT index = 0; index < kEPMMagicLength; ++index) { - if (buf[index] != kEPMMagic[index]) { - writer.Write(L"NewBoot: Writing an EPM partition...\r\n"); - - BootBlockType* bootBlock = (BootBlockType*)buf; - - bootBlock->Version = kEPMRevision; - bootBlock->NumBlocks = 2; - - for (SizeT i = 0; i < kEPMNameLength; ++i) { - bootBlock->Magic[i] = kEPMMagic[i]; - } - - for (SizeT i = 0; i < namePartLength; ++i) { - bootBlock->Name[i] = namePart[i]; - } - - bootBlock->LbaStart = - sizeof(BootBlockType) + (sizeof(PartitionBlockType) * kEPMMaxBlks); - - bootBlock->SectorSz = kEPMSectorSize; - - bootBlock->Uuid = kEPMGuid; - - PartitionBlock* partBlock = (PartitionBlock*)(buf + sizeof(BootBlock)); - - char* fsName = "NewFS"; - int fsNameLength = 6; - - for (SizeT i = 0; i < fsNameLength; ++i) { - partBlock->Fs[i] = fsName[i]; - } - - partBlock->Version = kEPMNewOS; - - char* partName = "System HD"; - int partNameLength = 10; - - for (SizeT i = 0; i < partNameLength; ++i) { - partBlock->Name[i] = partName[i]; - } - - partBlock->SectorSz = kEPMSectorSize; - partBlock->LbaStart = kEPMStartPartitionBlk + kEPMSwapSize; - partBlock->Version = kNewFSVersionInteger; - partBlock->Kind = kNewFSPartitionTypeStandard; - partBlock->LbaEnd = 0UL; ///! grows on the disk. - - PartitionBlock* swapBlock = (PartitionBlock*)(buf + sizeof(BootBlock) + sizeof(PartitionBlock)); - - for (SizeT i = 0; i < fsNameLength; ++i) { - swapBlock->Fs[i] = fsName[i]; - } - - swapBlock->Version = kEPMNewOS; - - partName = "Swap HD"; - partNameLength = 8; - - for (SizeT i = 0; i < partNameLength; ++i) { - swapBlock->Name[i] = partName[i]; - } - - swapBlock->SectorSz = kEPMSectorSize; - swapBlock->LbaStart = kEPMStartPartitionBlk; - swapBlock->Version = kNewFSVersionInteger; - swapBlock->Kind = kNewFSPartitionTypePage; - swapBlock->LbaEnd = kEPMSwapSize; /// 4 MIB swap partition. - - bootDev->Write(buf, 1); - - return No; - } - } - - writer.Write(L"NewBoot: Partition found, everything's OK.\r\n"); - return Yes; -} diff --git a/Private/NewBoot/Source/HEL/POWER/CoreBootStartup.S b/Private/NewBoot/Source/HEL/POWER/CoreBootStartup.S new file mode 100644 index 00000000..41fc6ae2 --- /dev/null +++ b/Private/NewBoot/Source/HEL/POWER/CoreBootStartup.S @@ -0,0 +1,34 @@ +/* ------------------------------------------- + + Copyright Mahrouss Logic + +------------------------------------------- */ + +.section .boot_hdr +.align 4 + +/* NewBoot boot header begin */ + +boot_hdr_mag: + .ascii "CB" +boot_hdr_name: + // it has to match ten bytes. + .asciz "NewBoot\0\0\0" +boot_hdr_ver: + .word 0x104 +boot_hdr_proc: + .long bootloader_start + +/* NewOS boot header end */ + +.extern bootloader_main +.extern bootloader_stack + +.globl bootloader_start +bootloader_start: + mflr 4 /* real address of .Laddr */ + lwz 0,(bootloader_stack-bootloader_start)(4) /* stack address location */ + mr 1,0 /* use user defined stack */ + + bl bootloader_main + blr diff --git a/Private/NewBoot/Source/makefile b/Private/NewBoot/Source/makefile index 11c1da75..7ed42abd 100644 --- a/Private/NewBoot/Source/makefile +++ b/Private/NewBoot/Source/makefile @@ -51,6 +51,7 @@ all: compile-amd64 $(DD) if=$(KERNEL_OBJ) of=$(BOOT_LOADER) bs=1 seek=0 conv=notrunc $(COPY) $(BOOT_LOADER) CDROM/EFI/BOOT/BOOTX64.EFI $(COPY) $(BOOT_LOADER) CDROM/EFI/BOOT/NEWBOOT.EFI + $(COPY) ../../$(KERNEL) CDROM/$(KERNEL) $(COPY) $(BOOT_LOADER) ../../Root/Boot/$(BOOT_LOADER) ifneq ($(DEBUG_SUPPORT), ) @@ -68,8 +69,8 @@ run-efi-amd64: .PHONY: epm-img epm-img: - qemu-img create -f raw $(IMG) 256M - qemu-img create -f raw $(IMG_2) 512M + qemu-img create -f qcow2 $(IMG) 256M + qemu-img create -f qcow2 $(IMG_2) 512M .PHONY: download-edk download-edk: -- cgit v1.2.3 From 9bf7420620393fe693576aa04c57ea4eefc925d7 Mon Sep 17 00:00:00 2001 From: Amlal El Mahrouss Date: Thu, 25 Apr 2024 15:05:50 +0200 Subject: MHR-16: Improve clean rule. Signed-off-by: Amlal El Mahrouss --- Private/NewBoot/Source/makefile | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Private/NewBoot/Source/makefile b/Private/NewBoot/Source/makefile index 7ed42abd..6eb14801 100644 --- a/Private/NewBoot/Source/makefile +++ b/Private/NewBoot/Source/makefile @@ -78,7 +78,7 @@ download-edk: .PHONY: clean clean: - $(REM) $(REM_FLAG) $(OBJ) NewBoot.exe NewKernel.exe OVMF.fd $(IMG) $(IMG_2) + $(REM) $(REM_FLAG) $(OBJ) NewBoot.exe NewKernel.exe OVMF.fd $(IMG) $(IMG_2) *.bin .PHONY: help help: -- cgit v1.2.3 From d7420ce44209bf6225df644880c0da2b2fb8638a Mon Sep 17 00:00:00 2001 From: Amlal El Mahrouss Date: Thu, 25 Apr 2024 15:14:28 +0200 Subject: MHR-16: Improve makefile, add $(TARGETS) which encapsulate all of the targets. Signed-off-by: Amlal El Mahrouss --- Private/NewBoot/Source/makefile | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/Private/NewBoot/Source/makefile b/Private/NewBoot/Source/makefile index 6eb14801..f0e44ba2 100644 --- a/Private/NewBoot/Source/makefile +++ b/Private/NewBoot/Source/makefile @@ -76,9 +76,11 @@ epm-img: download-edk: $(HTTP_GET) https://retrage.github.io/edk2-nightly/bin/DEBUGX64_OVMF.fd -O OVMF.fd +TARGETS=$(REM_FLAG) $(OBJ) NewBoot.exe NewKernel.exe OVMF.fd $(IMG) $(IMG_2) *.bin + .PHONY: clean clean: - $(REM) $(REM_FLAG) $(OBJ) NewBoot.exe NewKernel.exe OVMF.fd $(IMG) $(IMG_2) *.bin + $(REM) $(TARGETS) .PHONY: help help: -- cgit v1.2.3 From 9679735cb60011490c92fd8d3b13d337120a22ea Mon Sep 17 00:00:00 2001 From: Amlal El Mahrouss Date: Thu, 25 Apr 2024 16:23:14 +0200 Subject: MHR-16: Made it better. Signed-off-by: Amlal El Mahrouss --- Private/NewBoot/Source/makefile | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/Private/NewBoot/Source/makefile b/Private/NewBoot/Source/makefile index f0e44ba2..93bb5e28 100644 --- a/Private/NewBoot/Source/makefile +++ b/Private/NewBoot/Source/makefile @@ -76,7 +76,10 @@ epm-img: download-edk: $(HTTP_GET) https://retrage.github.io/edk2-nightly/bin/DEBUGX64_OVMF.fd -O OVMF.fd -TARGETS=$(REM_FLAG) $(OBJ) NewBoot.exe NewKernel.exe OVMF.fd $(IMG) $(IMG_2) *.bin +BINS=*.bin +EXECUTABLES=NewBoot.exe NewKernel.exe OVMF.fd + +TARGETS=$(REM_FLAG) $(OBJ) $(BIN) $(IMG) $(IMG_2) $(EXECUTABLES) .PHONY: clean clean: -- cgit v1.2.3 From 3b4a4a290b32fdb4a749b3e581afae450eb543c8 Mon Sep 17 00:00:00 2001 From: Amlal El Mahrouss Date: Fri, 26 Apr 2024 08:13:03 +0200 Subject: MHR-16: NewBoot - BDiskFormatter and QR. Signed-off-by: Amlal El Mahrouss --- Private/FSKit/NewFS.hxx | 9 +- Private/HALKit/AMD64/HalNewBoot.asm | 14 +- Private/HALKit/AMD64/Storage/ATA-PIO.cxx | 2 +- Private/HALKit/POWER/HalStartSequence.s | 8 +- Private/Linker/16x0.json | 2 +- Private/Linker/32x0.json | 2 +- Private/Linker/64x0.json | 2 +- Private/NewBoot/BootKit/BootKit.hxx | 149 ++++++++++++++++++--- Private/NewBoot/BootKit/HW/ATA.hxx | 2 + Private/NewBoot/Source/HEL/AMD64/BootATA.cxx | 26 +--- Private/NewBoot/Source/HEL/AMD64/BootJump.S | 9 ++ Private/NewBoot/Source/HEL/AMD64/BootMain.cxx | 94 ++++++++----- .../NewBoot/Source/HEL/AMD64/BootTextWriter.cxx | 2 +- Private/NewBoot/Source/HEL/AMD64/New+Delete.cxx | 11 ++ Private/NewBoot/Source/makefile | 13 +- Private/NewLoader/ReadMe.md | 9 -- Private/NewLoader/Source/.gitkeep | 0 Private/makefile | 10 +- 18 files changed, 253 insertions(+), 111 deletions(-) create mode 100644 Private/NewBoot/Source/HEL/AMD64/BootJump.S delete mode 100644 Private/NewLoader/ReadMe.md delete mode 100644 Private/NewLoader/Source/.gitkeep diff --git a/Private/FSKit/NewFS.hxx b/Private/FSKit/NewFS.hxx index cc43f51b..d3b72803 100644 --- a/Private/FSKit/NewFS.hxx +++ b/Private/FSKit/NewFS.hxx @@ -38,7 +38,7 @@ default. #define kNewFSIdentLen 8 #define kNewFSIdent " NewFS" -#define kNewFSPadLen 16 +#define kNewFSPadLen 408 /// @brief Partition GUID on EPM and GPT disks. #define kNewFSUUID "@{DD997393-9CCE-4288-A8D5-C0FDE3908DBE}" @@ -83,6 +83,7 @@ default. /// Start After the PM headers, pad 1024 bytes. #define kNewFSAddressAsLba (1024) +#define kNewFSCatalogStartAddress (kNewFSAddressAsLba + sizeof(NewPartitionBlock)) #define kResourceTypeDialog 10 #define kResourceTypeString 11 @@ -139,6 +140,9 @@ struct PACKED NewFork final { NewOS::Lba NextSibling; NewOS::Lba PreviousSibling; + + /// To make a perfect sector. + NewOS::Char Padding[200]; }; /// @brief Partition block type @@ -174,6 +178,9 @@ enum { kNewFSSubDriveCount, }; +/// \brief Resource fork kind. +enum { kNewFSRsrcForkKind = 0, kNewFSDataForkKind = 1 }; + /// /// \name NewFSParser /// \brief NewFS parser class. (catalog creation, remove removal, root, diff --git a/Private/HALKit/AMD64/HalNewBoot.asm b/Private/HALKit/AMD64/HalNewBoot.asm index 995a848c..11b11c0c 100644 --- a/Private/HALKit/AMD64/HalNewBoot.asm +++ b/Private/HALKit/AMD64/HalNewBoot.asm @@ -23,22 +23,16 @@ HandoverMagic: dq kHandoverMagic HandoverType: dw kTypeKernel HandoverArch: dw kArchAmd64 ;; This NewBootStart points to Main. -HandoverStart: dq Main +HandoverStart: dq __ImageStart section .text -global Main +global __ImageStart extern hal_init_platform ;; Just a simple setup, we'd also need to tell some before -Main: - push rax +__ImageStart: push rcx call hal_init_platform pop rcx - pop rax -;; Go to sleep. -MainLoop: - cli - hlt - jmp $ + ret diff --git a/Private/HALKit/AMD64/Storage/ATA-PIO.cxx b/Private/HALKit/AMD64/Storage/ATA-PIO.cxx index 3cbba6f7..652aa6f4 100644 --- a/Private/HALKit/AMD64/Storage/ATA-PIO.cxx +++ b/Private/HALKit/AMD64/Storage/ATA-PIO.cxx @@ -58,7 +58,7 @@ Void drv_std_select(UInt16 Bus) { Boolean drv_std_init(UInt16 Bus, UInt8 Drive, UInt16& OutBus, UInt8& OutMaster) { - if (drv_std_detected()) return false; + if (drv_std_detected()) return true; UInt16 IO = Bus; diff --git a/Private/HALKit/POWER/HalStartSequence.s b/Private/HALKit/POWER/HalStartSequence.s index f50a4d4f..fd018304 100644 --- a/Private/HALKit/POWER/HalStartSequence.s +++ b/Private/HALKit/POWER/HalStartSequence.s @@ -4,11 +4,11 @@ ------------------------------------------- */ -.globl Main -.extern HalKernelMain +.globl __ImageStart +.extern hal_init_platform .align 4 .text -Main: - bl HalKernelMain +__ImageStart: + bl hal_init_platform blr diff --git a/Private/Linker/16x0.json b/Private/Linker/16x0.json index 1dd7abbd..5851a2d3 100644 --- a/Private/Linker/16x0.json +++ b/Private/Linker/16x0.json @@ -1,6 +1,6 @@ { "executable_type": "kernel", "output_name": "NewKernel.exe", - "start_proc": "Main", + "start_proc": "__ImageStart", "format": "PEF" } diff --git a/Private/Linker/32x0.json b/Private/Linker/32x0.json index 1dd7abbd..5851a2d3 100644 --- a/Private/Linker/32x0.json +++ b/Private/Linker/32x0.json @@ -1,6 +1,6 @@ { "executable_type": "kernel", "output_name": "NewKernel.exe", - "start_proc": "Main", + "start_proc": "__ImageStart", "format": "PEF" } diff --git a/Private/Linker/64x0.json b/Private/Linker/64x0.json index 1dd7abbd..5851a2d3 100644 --- a/Private/Linker/64x0.json +++ b/Private/Linker/64x0.json @@ -1,6 +1,6 @@ { "executable_type": "kernel", "output_name": "NewKernel.exe", - "start_proc": "Main", + "start_proc": "__ImageStart", "format": "PEF" } diff --git a/Private/NewBoot/BootKit/BootKit.hxx b/Private/NewBoot/BootKit/BootKit.hxx index 15700f54..6272e4c9 100644 --- a/Private/NewBoot/BootKit/BootKit.hxx +++ b/Private/NewBoot/BootKit/BootKit.hxx @@ -6,7 +6,7 @@ /***********************************************************************************/ /// @file Boot.hxx -/// @brief Bootloader API. +/// @brief Bootloader Programming Interface. /***********************************************************************************/ #pragma once @@ -25,7 +25,7 @@ /***********************************************************************************/ #include -#include "Builtins/ATA/ATA.hxx" +#include /***********************************************************************************/ /// Framebuffer helpers. @@ -49,6 +49,11 @@ typedef Char *PEImagePtr; typedef WideChar CharacterTypeUTF16; typedef Char CharacterTypeUTF8; +namespace EFI { + extern void ThrowError(const CharacterTypeUTF16 *ErrorCode, + const CharacterTypeUTF16 *Reason) noexcept; +} + /** * @brief BootKit Text Writer class * Writes to UEFI StdOut. @@ -58,7 +63,7 @@ class BTextWriter final { public: BTextWriter &Write(const Long &num); - BTextWriter &Write(const UChar *str); + BTextWriter &Write(const Char *str); BTextWriter &Write(const CharacterTypeUTF16 *str); BTextWriter &WriteCharacter(CharacterTypeUTF16 c); @@ -171,14 +176,19 @@ static inline const UInt32 kRgbBlue = 0x00FF0000; static inline const UInt32 kRgbBlack = 0x00000000; static inline const UInt32 kRgbWhite = 0x00FFFFFF; +#define kBKBootFileMime "boot-x/file" +#define kBKBootDirMime "boot-x/dir" + /// @brief BootKit Disk Formatter. template class BDiskFormatFactory final { public: /// @brief File entry for **BDiskFormatFactory**. struct BFileDescriptor final { - Char fFilename[255]; - Char fForkName[255]; + Char fFileName[kNewFSNodeNameLen]; + Char fForkName[kNewFSNodeNameLen]; + + UInt32 fKind; VoidPtr fBlob; SizeT fBlobSz; @@ -190,6 +200,7 @@ public: public: explicit BDiskFormatFactory() = default; explicit BDiskFormatFactory(BootDev dev) : fDiskDev(dev) {} + ~BDiskFormatFactory() = default; NEWOS_COPY_DELETE(BDiskFormatFactory); @@ -204,7 +215,101 @@ public: private: /// @brief Write all of the requested catalogs into the filesystem. - Boolean _AppendCatalogList(BFileDescriptor* fileBlobs, SizeT blobCount) { + Boolean WriteContent(BFileDescriptor* fileBlobs, SizeT blobCount, + SizeT sectorSz, NewPartitionBlock& partBlock) { + if (sectorSz != BootDev::kSectorSize) return false; + + BFileDescriptor* blob = fileBlobs; + Lba startLba = partBlock.FreeCatalog; + + BTextWriter writer; + while (blob) { + NewCatalog catalogKind{ 0 }; + + /// Fill catalog kind. + catalogKind.Kind = blob->fKind; + + /// Allocate fork for blob. + catalogKind.FirstFork = (startLba + sizeof(NewCatalog)); + catalogKind.LastFork = catalogKind.FirstFork; + + NewFork forkKind{ 0 }; + + memcpy(forkKind.Name, blob->fForkName, strlen(blob->fForkName)); + forkKind.Kind = (forkKind.Name[0] == kNewFSDataFork[0]) ? kNewFSDataForkKind : kNewFSRsrcForkKind; + forkKind.Flags = kNewFSFlagCreated; + + /// We don't know. + forkKind.ResourceFlags = 0; + forkKind.ResourceId = 0; + forkKind.ResourceKind = 0; + + /// We're the only fork here. + forkKind.NextSibling = catalogKind.FirstFork; + forkKind.PreviousSibling = catalogKind.FirstFork; + + forkKind.DataOffset = (startLba + sizeof(NewCatalog) + sizeof(NewFork)); + forkKind.DataSize = blob->fBlobSz; + + Lba lbaStart = forkKind.DataOffset; + SizeT cur = 0UL; + + while (cur < forkKind.DataSize) { + this->fDiskDev.Leak().mSize = BootDev::kSectorSize; + this->fDiskDev.Leak().mBase = forkKind.DataOffset / BootDev::kSectorSize; + + this->fDiskDev.Write((Char*)(blob->fBlob) + cur, BootDev::kSectorSize); + + cur += BootDev::kSectorSize; + lbaStart += BootDev::kSectorSize; + } + + writer.Write((catalogKind.Kind == kNewFSCatalogKindFile) ? L"New Boot: Write-File: " : + L"New Boot: Write-Directory: " ).Write(blob->fFileName).Write(L"\r\n"); + + /// Set disk cursor here. + + fDiskDev.Leak().mBase = startLba + sizeof(NewCatalog) / sectorSz; + fDiskDev.Leak().mSize = sizeof(NewFork); + + fDiskDev.Write((Char*)&forkKind, 1); + + /// Fork is done. + + catalogKind.Kind = blob->fKind; + catalogKind.Flags |= kNewFSFlagCreated; + + Lba catalogLba = (sizeof(NewCatalog) - startLba); + + //// Now write catalog as well.. + + catalogKind.PrevSibling = startLba; + catalogKind.NextSibling = (sizeof(NewCatalog) + blob->fBlobSz); + + /// this mime only applies to file. + if (catalogKind.Kind == kNewFSCatalogKindFile) { + memcpy(catalogKind.Mime, kBKBootFileMime, strlen(kBKBootFileMime)); + } else { + memcpy(catalogKind.Mime, kBKBootDirMime, strlen(kBKBootDirMime)); + } + + memcpy(catalogKind.Name, blob->fFileName, strlen(blob->fFileName)); + + fDiskDev.Leak().mBase = startLba / sectorSz; + fDiskDev.Leak().mSize = sizeof(NewCatalog); + + fDiskDev.Write((Char*)&catalogKind, sectorSz); + + startLba += (sizeof(NewCatalog) + blob->fBlobSz); + + --partBlock.FreeCatalog; + --partBlock.FreeSectors; + + ++partBlock.CatalogCount; + + blob = blob->fNext; + } + return true; } @@ -222,28 +327,40 @@ private: template inline Boolean BDiskFormatFactory::Format(const char* partName, BDiskFormatFactory::BFileDescriptor* fileBlobs, SizeT blobCount) { - // if (!fileBlobs || !blobCount) return false; + if (!fileBlobs || !blobCount) return false; /// sanity check - static_assert(kNewFSMinimumSectorSz == kATASectorSize, "Sector size doesn't match!"); + /// convert the sector into something that the disk understands. + SizeT sectorSz = BootDev::kSectorSize; + Char buf[BootDev::kSectorSize] = { 0 }; - Char buf[kNewFSMinimumSectorSz] = { 0 }; NewPartitionBlock* partBlock = reinterpret_cast(buf); + memcpy(partBlock->Ident, kNewFSIdent, kNewFSIdentLen-1); memcpy(partBlock->PartitionName, partName, strlen(partName)); /// @note A catalog roughly equal to a sector. - partBlock->CatalogCount = blobCount; + partBlock->CatalogCount = 0UL; partBlock->Kind = kNewFSHardDrive; - partBlock->SectorCount = kNewFSMinimumSectorSz; + partBlock->SectorSize = sectorSz; partBlock->FreeCatalog = fDiskDev.GetSectorsCount() - partBlock->CatalogCount; partBlock->SectorCount = fDiskDev.GetSectorsCount(); partBlock->FreeSectors = fDiskDev.GetSectorsCount() - partBlock->CatalogCount; - partBlock->StartCatalog = kNewFSAddressAsLba + sizeof(NewPartitionBlock); + partBlock->StartCatalog = kNewFSCatalogStartAddress; - fDiskDev.Leak().mBase = (kNewFSAddressAsLba / kNewFSMinimumSectorSz); - fDiskDev.Leak().mSize = kNewFSMinimumSectorSz; - fDiskDev.Write(buf, kNewFSMinimumSectorSz); + if (this->WriteContent(fileBlobs, blobCount, sectorSz, *partBlock)) { + fDiskDev.Leak().mBase = (kNewFSAddressAsLba / sectorSz); + fDiskDev.Leak().mSize = BootDev::kSectorSize; + + fDiskDev.Write(buf, sectorSz); + + BTextWriter writer; + writer.Write(L"New Boot: Write-Partition, OK.\r\n"); + + return true; + } else { + EFI::ThrowError(L"Filesystem-Failure-Part", L"Filesystem couldn't be partitioned."); + } - return this->_AppendCatalogList(fileBlobs, blobCount); + return false; } diff --git a/Private/NewBoot/BootKit/HW/ATA.hxx b/Private/NewBoot/BootKit/HW/ATA.hxx index c557aeb8..4b96e9fa 100644 --- a/Private/NewBoot/BootKit/HW/ATA.hxx +++ b/Private/NewBoot/BootKit/HW/ATA.hxx @@ -23,6 +23,8 @@ class BootDeviceATA final : public Device { NEWOS_COPY_DEFAULT(BootDeviceATA); + enum { kSectorSize = kATASectorSize }; + struct ATATrait final : public Device::Trait { UInt16 mBus{kPrimary}; UInt8 mMaster{0}; diff --git a/Private/NewBoot/Source/HEL/AMD64/BootATA.cxx b/Private/NewBoot/Source/HEL/AMD64/BootATA.cxx index 10d4272d..8d923a50 100644 --- a/Private/NewBoot/Source/HEL/AMD64/BootATA.cxx +++ b/Private/NewBoot/Source/HEL/AMD64/BootATA.cxx @@ -132,7 +132,7 @@ ATAInit_Retry: Void boot_ata_read(UInt64 Lba, UInt16 IO, UInt8 Master, CharacterTypeUTF8* Buf, SizeT SectorSz, SizeT Size) { - UInt8 Command = (!Master ? 0xE0 : 0xF0); + UInt8 Command = ((!Master) ? 0xE0 : 0xF0); boot_ata_wait_io(IO); @@ -146,27 +146,15 @@ Void boot_ata_read(UInt64 Lba, UInt16 IO, UInt8 Master, CharacterTypeUTF8* Buf, Out8(IO + ATA_REG_COMMAND, ATA_CMD_READ_PIO); - while ((In8(ATA_COMMAND(IO))) & ATA_SR_BSY) boot_ata_wait_io(IO); - - UInt16 byte = In16(IO + ATA_REG_DATA); - SizeT IndexOff = 0UL; - Buf[IndexOff] = byte; - - while (byte != 0xFF) { - if (IndexOff > Size) break; - - ++IndexOff; - - while ((In8(ATA_COMMAND(IO))) & ATA_SR_BSY) boot_ata_wait_io(IO); - - byte = In16(IO + ATA_REG_DATA); - Buf[IndexOff] = byte; + for (SizeT IndexOff = 0; IndexOff < Size; ++IndexOff) { + boot_ata_wait_io(IO); + Buf[IndexOff] = In16(IO + ATA_REG_DATA); } } Void boot_ata_write(UInt64 Lba, UInt16 IO, UInt8 Master, CharacterTypeUTF8* Buf, SizeT SectorSz, SizeT Size) { - UInt8 Command = (!Master ? 0xE0 : 0xF0); + UInt8 Command = ((!Master) ? 0xE0 : 0xF0); boot_ata_wait_io(IO); @@ -209,10 +197,6 @@ BootDeviceATA::BootDeviceATA() noexcept { boot_ata_init(ATA_SECONDARY_IO, true, this->Leak().mBus, this->Leak().mMaster)) { kATADetected = true; - - BTextWriter writer; - - writer.Write(L"New Boot: Drive is OnLine.\r\n"); } } /** diff --git a/Private/NewBoot/Source/HEL/AMD64/BootJump.S b/Private/NewBoot/Source/HEL/AMD64/BootJump.S new file mode 100644 index 00000000..af278cc7 --- /dev/null +++ b/Private/NewBoot/Source/HEL/AMD64/BootJump.S @@ -0,0 +1,9 @@ +.global rt_jump_to_address +.text + +.code64 +.intel_syntax noprefix + +rt_jump_to_address: + jmp rcx + ret diff --git a/Private/NewBoot/Source/HEL/AMD64/BootMain.cxx b/Private/NewBoot/Source/HEL/AMD64/BootMain.cxx index 356db88b..ea3fcbf0 100644 --- a/Private/NewBoot/Source/HEL/AMD64/BootMain.cxx +++ b/Private/NewBoot/Source/HEL/AMD64/BootMain.cxx @@ -9,8 +9,15 @@ #include #include #include -#include +#include #include +#include +#include + +/// make the compiler shut up. +#ifndef kMachineModel +#define kMachineModel "NeWS HD" +#endif // !kMachineModel /** Graphics related. */ @@ -18,6 +25,8 @@ STATIC EfiGraphicsOutputProtocol* kGop = nullptr; STATIC UInt16 kStride = 0U; STATIC EfiGUID kGopGuid; +EXTERN_C Void rt_jump_to_address(VoidPtr blob); + /** @brief Finds and stores the GOP. */ @@ -166,45 +175,66 @@ EFI_EXTERN_C EFI_API Int Main(EfiHandlePtr ImageHandle, } } - BFileReader kernelFile(L"NewLoader.exe", ImageHandle); - kernelFile.ReadAll(MIB(1), 4096); + /// + /// The following checks for an exisiting partition + /// inside the disk, if it doesn't have one, + /// format the disk. + // - if (kernelFile.Blob()) { - PEFContainer* containerKind = - reinterpret_cast(kernelFile.Blob()); + /// need this as well, to invoke BExecutableLoader. + BFileReader readerKernel(L"NewKernel.exe", ImageHandle); + readerKernel.ReadAll(MIB(1), 4096); - if (containerKind->Magic[0] == kPefMagic[0] && - containerKind->Magic[1] == kPefMagic[1] && - containerKind->Magic[2] == kPefMagic[2] && - containerKind->Magic[3] == kPefMagic[3] && - containerKind->Magic[4] == kPefMagic[4]) { - if (containerKind->Abi != kPefAbi || - containerKind->Cpu != kPefArchAMD64) { - EFI::ThrowError(L"Bad-Architecture", - L"New Boot can't run this architecture."); - } + BDiskFormatFactory diskFormatter; - NewOS::HEL::BootMainKind main = - reinterpret_cast(containerKind + - containerKind->Start); + BDiskFormatFactory::BFileDescriptor rootDesc{0}; - if (!main) { - EFI::ThrowError(L"Bad-Exec", - L"New Boot can't recognize this executable."); - } + memcpy(rootDesc.fFileName, "/", strlen("/")); + memcpy(rootDesc.fForkName, kNewFSResourceFork, strlen(kNewFSResourceFork)); - EFI::ExitBootServices(MapKey, ImageHandle); + rootDesc.fBlobSz = strlen(kMachineModel " startup disk."); + rootDesc.fBlob = new Char[rootDesc.fBlobSz]; - main(handoverHdrPtr); + memcpy(rootDesc.fBlob, kMachineModel " startup disk.", + strlen(kMachineModel " startup disk.")); - EFI::Stop(); + rootDesc.fKind = kNewFSCatalogKindDir; - CANT_REACH(); - } - } + BDiskFormatFactory::BFileDescriptor bootDesc{0}; + + bootDesc.fKind = kNewFSCatalogKindDir; + + memcpy(bootDesc.fFileName, "/Boot", strlen("/Boot")); + memcpy(bootDesc.fForkName, kNewFSResourceFork, strlen(kNewFSResourceFork)); + memcpy(bootDesc.fBlob, kMachineModel " startup folder.", + strlen(kMachineModel " startup folder.")); + + bootDesc.fBlobSz = strlen(kMachineModel " startup folder."); + bootDesc.fBlob = new Char[bootDesc.fBlobSz]; + + BDiskFormatFactory::BFileDescriptor kernelDesc{0}; + + kernelDesc.fKind = kNewFSCatalogKindFile; + + memcpy(kernelDesc.fFileName, "/Boot/NewKernel", strlen("/Boot/NewKernel")); + memcpy(kernelDesc.fForkName, kNewFSDataFork, strlen(kNewFSDataFork)); + + kernelDesc.fBlob = readerKernel.Blob(); + kernelDesc.fBlobSz = readerKernel.Size(); + + rootDesc.fNext = &bootDesc; + rootDesc.fNext->fPrev = &rootDesc; + + rootDesc.fNext->fNext = &kernelDesc; + rootDesc.fNext->fNext->fPrev = &bootDesc; + + diskFormatter.Format(kMachineModel, &rootDesc, 3); + + EFI::ExitBootServices(MapKey, ImageHandle); + + rt_jump_to_address(readerKernel.Blob()); - EFI::ThrowError(L"Invalid-PEF-Executable", - L"PEF executable expected. Got something else."); + EFI::Stop(); - return kEfiFail; + CANT_REACH(); } diff --git a/Private/NewBoot/Source/HEL/AMD64/BootTextWriter.cxx b/Private/NewBoot/Source/HEL/AMD64/BootTextWriter.cxx index 81aa6c9d..ff30ff95 100644 --- a/Private/NewBoot/Source/HEL/AMD64/BootTextWriter.cxx +++ b/Private/NewBoot/Source/HEL/AMD64/BootTextWriter.cxx @@ -32,7 +32,7 @@ BTextWriter &BTextWriter::Write(const CharacterTypeUTF16 *str) { return *this; } -BTextWriter &BTextWriter::Write(const UChar *str) { +BTextWriter &BTextWriter::Write(const Char *str) { #ifdef __DEBUG__ if (!str || *str == 0) return *this; diff --git a/Private/NewBoot/Source/HEL/AMD64/New+Delete.cxx b/Private/NewBoot/Source/HEL/AMD64/New+Delete.cxx index 77552ef8..01911c43 100644 --- a/Private/NewBoot/Source/HEL/AMD64/New+Delete.cxx +++ b/Private/NewBoot/Source/HEL/AMD64/New+Delete.cxx @@ -20,6 +20,17 @@ void* operator new(size_t sz) return buf; } +/// @brief Allocates a new object. +/// @param sz the size. +/// @return +void* operator new[](size_t sz) +{ + void* buf = nullptr; + BS->AllocatePool(EfiMemoryType::EfiLoaderData, sz, &buf); + + return buf; +} + /// @brief Deletes the object. /// @param buf the object. void operator delete(void* buf) diff --git a/Private/NewBoot/Source/makefile b/Private/NewBoot/Source/makefile index 93bb5e28..92128b02 100644 --- a/Private/NewBoot/Source/makefile +++ b/Private/NewBoot/Source/makefile @@ -18,6 +18,10 @@ else EMU=qemu-system-x86_64 endif +ifeq ($(NEWS_MODEL), ) +NEWOS_MODEL=-DkMachineModel="\"Generic NeWS HD\"" +endif + IMG=epm.img IMG_2=epm-slave.img EMU_FLAGS=-net none -smp 4 -m 8G -M q35 -bios OVMF.fd -device piix3-ide,id=ide -drive id=disk,file=$(IMG),format=raw,if=none -device ide-hd,drive=disk,bus=ide.0 -drive file=fat:rw:CDROM,index=2,format=raw -d int -hdd epm-slave.img @@ -46,13 +50,10 @@ KERNEL=NewKernel.exe .PHONY: all all: compile-amd64 mkdir -p CDROM/EFI/BOOT - $(LD_GNU) $(OBJ) $(LD_FLAGS) -o $(KERNEL_OBJ) - $(IMG_CREATE) create -f raw $(BOOT_LOADER) $(MAX_KERNEL_SIZE) - $(DD) if=$(KERNEL_OBJ) of=$(BOOT_LOADER) bs=1 seek=0 conv=notrunc + $(LD_GNU) $(OBJ) $(LD_FLAGS) -o $(BOOT_LOADER) $(COPY) $(BOOT_LOADER) CDROM/EFI/BOOT/BOOTX64.EFI $(COPY) $(BOOT_LOADER) CDROM/EFI/BOOT/NEWBOOT.EFI $(COPY) ../../$(KERNEL) CDROM/$(KERNEL) - $(COPY) $(BOOT_LOADER) ../../Root/Boot/$(BOOT_LOADER) ifneq ($(DEBUG_SUPPORT), ) DEBUG = -D__DEBUG__ @@ -61,7 +62,7 @@ endif .PHONY: compile-amd64 compile-amd64: $(WINDRES) BootloaderRsrc.rsrc -O coff -o BootloaderRsrc.o - $(CC_GNU) $(FLAG_GNU) $(DEBUG) $(wildcard HEL/AMD64/*.cxx) $(wildcard *.cxx) + $(CC_GNU) $(NEWOS_MODEL) $(FLAG_GNU) $(DEBUG) $(wildcard HEL/AMD64/*.cxx) $(wildcard HEL/AMD64/*.S) $(wildcard *.cxx) .PHONY: run-efi-amd64 run-efi-amd64: @@ -69,7 +70,7 @@ run-efi-amd64: .PHONY: epm-img epm-img: - qemu-img create -f qcow2 $(IMG) 256M + qemu-img create -f qcow2 $(IMG) 512M qemu-img create -f qcow2 $(IMG_2) 512M .PHONY: download-edk diff --git a/Private/NewLoader/ReadMe.md b/Private/NewLoader/ReadMe.md deleted file mode 100644 index 955f0651..00000000 --- a/Private/NewLoader/ReadMe.md +++ /dev/null @@ -1,9 +0,0 @@ -# NewLoader - -## New OS Stage 2 loader. - -Loads and runs the NewKernel and it's components. - -- Loads: NewKernel.exe, a MicroKernel in C++ (PEF) -- Loads: Bonjour.exe, zeroconf driver. (PEF) -- Loads: MahroussUpdate.exe, mahrouss system update driver. (PEF) diff --git a/Private/NewLoader/Source/.gitkeep b/Private/NewLoader/Source/.gitkeep deleted file mode 100644 index e69de29b..00000000 diff --git a/Private/makefile b/Private/makefile index 673a4b56..977e33ac 100644 --- a/Private/makefile +++ b/Private/makefile @@ -5,7 +5,7 @@ CC = x86_64-w64-mingw32-gcc LD = x86_64-w64-mingw32-ld -CCFLAGS = -c -ffreestanding -fPIE -fPIC -D__NEWOS_AMD64__ -mno-red-zone -fno-rtti -fno-exceptions -std=c++20 -D__FSKIT_NEWFS__ -D__KERNEL__ -D__HAVE_MAHROUSS_APIS__ -D__MAHROUSS__ -I../ -I./ +CCFLAGS = -c -ffreestanding -fPIC -D__NEWOS_AMD64__ -mno-red-zone -fno-rtti -fno-exceptions -std=c++20 -D__FSKIT_NEWFS__ -D__KERNEL__ -D__HAVE_MAHROUSS_APIS__ -D__MAHROUSS__ -I../ -I./ ASM = nasm ifneq ($(ATA_PIO_SUPPORT), ) @@ -30,7 +30,7 @@ COPY = cp ASMFLAGS = -f win64 # NewOS subsystem is 17. -LDFLAGS = -e Main --subsystem=17 +LDFLAGS = -e __ImageStart --subsystem=17 LDOBJ = Objects/*.obj # This file is the kernel, responsible of task management and memory. @@ -59,17 +59,13 @@ newos-amd64-epm: clean OBJCOPY=x86_64-w64-mingw32-objcopy -KERNEL_OBJ=kernel.bin DD=dd IMG_CREATE=qemu-img MAX_KERNEL_SIZE=1024K .PHONY: link-amd64-epm link-amd64-epm: - $(LD) $(LDFLAGS) $(LDOBJ) -o $(KERNEL_OBJ) - $(IMG_CREATE) create -f raw $(KERNEL) $(MAX_KERNEL_SIZE) - $(DD) if=$(KERNEL_OBJ) of=$(KERNEL) bs=1 seek=0 conv=notrunc - $(COPY) $(KERNEL) Root/Boot + $(LD) $(LDFLAGS) $(LDOBJ) -o $(KERNEL) .PHONY: all all: newos-amd64-epm link-amd64-epm -- cgit v1.2.3 From 9cf4007cc5a2d37c8a49cbc25a564cde5981e7b0 Mon Sep 17 00:00:00 2001 From: Amlal El Mahrouss Date: Fri, 26 Apr 2024 08:26:54 +0200 Subject: MHR-16: Last fix and improvements. Signed-off-by: Amlal El Mahrouss --- Private/NewBoot/BootKit/BootKit.hxx | 11 ++++++ Private/NewBoot/Source/HEL/AMD64/BootATA.cxx | 12 +++--- Private/NewBoot/Source/HEL/AMD64/BootMain.cxx | 56 ++++++++++++++------------- 3 files changed, 45 insertions(+), 34 deletions(-) diff --git a/Private/NewBoot/BootKit/BootKit.hxx b/Private/NewBoot/BootKit/BootKit.hxx index 6272e4c9..ffa3af15 100644 --- a/Private/NewBoot/BootKit/BootKit.hxx +++ b/Private/NewBoot/BootKit/BootKit.hxx @@ -213,6 +213,17 @@ public: /// @retval False failed to format. Boolean Format(const char* partName, BFileDescriptor* fileBlobs, SizeT blobCount); + operator bool() noexcept { + fDiskDev.Leak().mBase = (kNewFSAddressAsLba / BootDev::kSectorSize); + fDiskDev.Leak().mSize = BootDev::kSectorSize; + + Char buf[BootDev::kSectorSize] = { 0 }; + + fDiskDev.Read(buf, BootDev::kSectorSize); + + return buf[0] == kNewFSIdent[0]; + } + private: /// @brief Write all of the requested catalogs into the filesystem. Boolean WriteContent(BFileDescriptor* fileBlobs, SizeT blobCount, diff --git a/Private/NewBoot/Source/HEL/AMD64/BootATA.cxx b/Private/NewBoot/Source/HEL/AMD64/BootATA.cxx index 8d923a50..bb634fbf 100644 --- a/Private/NewBoot/Source/HEL/AMD64/BootATA.cxx +++ b/Private/NewBoot/Source/HEL/AMD64/BootATA.cxx @@ -56,7 +56,7 @@ Void boot_ata_select(UInt16 Bus) { Boolean boot_ata_init(UInt16 Bus, UInt8 Drive, UInt16& OutBus, UInt8& OutMaster) { - if (boot_ata_detected()) return false; + if (boot_ata_detected()) return true; BTextWriter writer; @@ -135,14 +135,14 @@ Void boot_ata_read(UInt64 Lba, UInt16 IO, UInt8 Master, CharacterTypeUTF8* Buf, UInt8 Command = ((!Master) ? 0xE0 : 0xF0); boot_ata_wait_io(IO); + boot_ata_select(IO); Out8(IO + ATA_REG_HDDEVSEL, (Command) | (((Lba) >> 24) & 0xF)); - Out8(IO + ATA_REG_SEC_COUNT0, SectorSz); + Out8(IO + ATA_REG_SEC_COUNT0, 1); Out8(IO + ATA_REG_LBA0, (Lba)); Out8(IO + ATA_REG_LBA1, (Lba) >> 8); Out8(IO + ATA_REG_LBA2, (Lba) >> 16); - Out8(IO + ATA_REG_LBA3, (Lba) >> 24); Out8(IO + ATA_REG_COMMAND, ATA_CMD_READ_PIO); @@ -157,14 +157,14 @@ Void boot_ata_write(UInt64 Lba, UInt16 IO, UInt8 Master, CharacterTypeUTF8* Buf, UInt8 Command = ((!Master) ? 0xE0 : 0xF0); boot_ata_wait_io(IO); + boot_ata_select(IO); Out8(IO + ATA_REG_HDDEVSEL, (Command) | (((Lba) >> 24) & 0xF)); - Out8(IO + ATA_REG_SEC_COUNT0, SectorSz); + Out8(IO + ATA_REG_SEC_COUNT0, 1); Out8(IO + ATA_REG_LBA0, (Lba)); Out8(IO + ATA_REG_LBA1, (Lba) >> 8); Out8(IO + ATA_REG_LBA2, (Lba) >> 16); - Out8(IO + ATA_REG_LBA3, (Lba) >> 24); Out8(IO + ATA_REG_COMMAND, ATA_CMD_WRITE_PIO); @@ -190,8 +190,6 @@ Boolean boot_ata_detected(Void) { return kATADetected; } * @param void none. */ BootDeviceATA::BootDeviceATA() noexcept { - if (boot_ata_detected()) return; - if (boot_ata_init(ATA_PRIMARY_IO, true, this->Leak().mBus, this->Leak().mMaster) || boot_ata_init(ATA_SECONDARY_IO, true, this->Leak().mBus, diff --git a/Private/NewBoot/Source/HEL/AMD64/BootMain.cxx b/Private/NewBoot/Source/HEL/AMD64/BootMain.cxx index ea3fcbf0..5e9e2355 100644 --- a/Private/NewBoot/Source/HEL/AMD64/BootMain.cxx +++ b/Private/NewBoot/Source/HEL/AMD64/BootMain.cxx @@ -187,48 +187,50 @@ EFI_EXTERN_C EFI_API Int Main(EfiHandlePtr ImageHandle, BDiskFormatFactory diskFormatter; - BDiskFormatFactory::BFileDescriptor rootDesc{0}; + if (!diskFormatter) { + BDiskFormatFactory::BFileDescriptor rootDesc{0}; - memcpy(rootDesc.fFileName, "/", strlen("/")); - memcpy(rootDesc.fForkName, kNewFSResourceFork, strlen(kNewFSResourceFork)); + memcpy(rootDesc.fFileName, "/", strlen("/")); + memcpy(rootDesc.fForkName, kNewFSResourceFork, strlen(kNewFSResourceFork)); - rootDesc.fBlobSz = strlen(kMachineModel " startup disk."); - rootDesc.fBlob = new Char[rootDesc.fBlobSz]; + rootDesc.fBlobSz = strlen(kMachineModel " startup disk."); + rootDesc.fBlob = new Char[rootDesc.fBlobSz]; - memcpy(rootDesc.fBlob, kMachineModel " startup disk.", - strlen(kMachineModel " startup disk.")); + memcpy(rootDesc.fBlob, kMachineModel " startup disk.", + strlen(kMachineModel " startup disk.")); - rootDesc.fKind = kNewFSCatalogKindDir; + rootDesc.fKind = kNewFSCatalogKindDir; - BDiskFormatFactory::BFileDescriptor bootDesc{0}; + BDiskFormatFactory::BFileDescriptor bootDesc{0}; - bootDesc.fKind = kNewFSCatalogKindDir; + bootDesc.fKind = kNewFSCatalogKindDir; - memcpy(bootDesc.fFileName, "/Boot", strlen("/Boot")); - memcpy(bootDesc.fForkName, kNewFSResourceFork, strlen(kNewFSResourceFork)); - memcpy(bootDesc.fBlob, kMachineModel " startup folder.", - strlen(kMachineModel " startup folder.")); + memcpy(bootDesc.fFileName, "/Boot", strlen("/Boot")); + memcpy(bootDesc.fForkName, kNewFSResourceFork, strlen(kNewFSResourceFork)); + memcpy(bootDesc.fBlob, kMachineModel " startup folder.", + strlen(kMachineModel " startup folder.")); - bootDesc.fBlobSz = strlen(kMachineModel " startup folder."); - bootDesc.fBlob = new Char[bootDesc.fBlobSz]; + bootDesc.fBlobSz = strlen(kMachineModel " startup folder."); + bootDesc.fBlob = new Char[bootDesc.fBlobSz]; - BDiskFormatFactory::BFileDescriptor kernelDesc{0}; + BDiskFormatFactory::BFileDescriptor kernelDesc{0}; - kernelDesc.fKind = kNewFSCatalogKindFile; + kernelDesc.fKind = kNewFSCatalogKindFile; - memcpy(kernelDesc.fFileName, "/Boot/NewKernel", strlen("/Boot/NewKernel")); - memcpy(kernelDesc.fForkName, kNewFSDataFork, strlen(kNewFSDataFork)); + memcpy(kernelDesc.fFileName, "/Boot/NewKernel", strlen("/Boot/NewKernel")); + memcpy(kernelDesc.fForkName, kNewFSDataFork, strlen(kNewFSDataFork)); - kernelDesc.fBlob = readerKernel.Blob(); - kernelDesc.fBlobSz = readerKernel.Size(); + kernelDesc.fBlob = readerKernel.Blob(); + kernelDesc.fBlobSz = readerKernel.Size(); - rootDesc.fNext = &bootDesc; - rootDesc.fNext->fPrev = &rootDesc; + rootDesc.fNext = &bootDesc; + rootDesc.fNext->fPrev = &rootDesc; - rootDesc.fNext->fNext = &kernelDesc; - rootDesc.fNext->fNext->fPrev = &bootDesc; + rootDesc.fNext->fNext = &kernelDesc; + rootDesc.fNext->fNext->fPrev = &bootDesc; - diskFormatter.Format(kMachineModel, &rootDesc, 3); + diskFormatter.Format(kMachineModel, &rootDesc, 3); + } EFI::ExitBootServices(MapKey, ImageHandle); -- cgit v1.2.3 From 4afe2bd4c6e95f2ca4a5b9bdacf51ef5f91fd0d7 Mon Sep 17 00:00:00 2001 From: Amlal El Mahrouss Date: Fri, 26 Apr 2024 08:28:10 +0200 Subject: MHR-16: Fix kernel driver as well. Signed-off-by: Amlal El Mahrouss --- Private/HALKit/AMD64/Storage/ATA-PIO.cxx | 10 ++++------ 1 file changed, 4 insertions(+), 6 deletions(-) diff --git a/Private/HALKit/AMD64/Storage/ATA-PIO.cxx b/Private/HALKit/AMD64/Storage/ATA-PIO.cxx index 652aa6f4..f2ae01a4 100644 --- a/Private/HALKit/AMD64/Storage/ATA-PIO.cxx +++ b/Private/HALKit/AMD64/Storage/ATA-PIO.cxx @@ -132,15 +132,14 @@ ATAInit_Retry: Void drv_std_read(UInt64 Lba, UInt16 IO, UInt8 Master, Char* Buf, SizeT SectorSz, SizeT Size) { - UInt8 Command = (!Master ? 0xE0 : 0xF0); + UInt8 Command = ((!Master )? 0xE0 : 0xF0); Out8(IO + ATA_REG_HDDEVSEL, (Command) | (((Lba) >> 24) & 0xF)); - Out8(IO + ATA_REG_SEC_COUNT0, SectorSz); + Out8(IO + ATA_REG_SEC_COUNT0, 1); Out8(IO + ATA_REG_LBA0, (Lba)); Out8(IO + ATA_REG_LBA1, (Lba) >> 8); Out8(IO + ATA_REG_LBA2, (Lba) >> 16); - Out8(IO + ATA_REG_LBA3, (Lba) >> 24); Out8(IO + ATA_REG_COMMAND, ATA_CMD_READ_PIO); @@ -155,15 +154,14 @@ Void drv_std_read(UInt64 Lba, UInt16 IO, UInt8 Master, Char* Buf, Void drv_std_write(UInt64 Lba, UInt16 IO, UInt8 Master, Char* Buf, SizeT SectorSz, SizeT Size) { - UInt8 Command = (!Master ? 0xE0 : 0xF0); + UInt8 Command = ((!Master) ? 0xE0 : 0xF0); Out8(IO + ATA_REG_HDDEVSEL, (Command) | (((Lba) >> 24) & 0xF)); - Out8(IO + ATA_REG_SEC_COUNT0, SectorSz); + Out8(IO + ATA_REG_SEC_COUNT0, 1); Out8(IO + ATA_REG_LBA0, (Lba)); Out8(IO + ATA_REG_LBA1, (Lba) >> 8); Out8(IO + ATA_REG_LBA2, (Lba) >> 16); - Out8(IO + ATA_REG_LBA3, (Lba) >> 24); Out8(IO + ATA_REG_COMMAND, ATA_CMD_WRITE_PIO); -- cgit v1.2.3 From ba80f513dd5cd82feae0b8f794b3367caf9ce8bb Mon Sep 17 00:00:00 2001 From: Amlal El Mahrouss Date: Fri, 26 Apr 2024 10:20:01 +0200 Subject: MHR-16: a lot of fixes. Regarding the disk driver and the filesystem class BDiskFormatFactory. Signed-off-by: Amlal El Mahrouss --- Private/Builtins/ATA/ATA.hxx | 3 +- Private/HALKit/AMD64/Storage/ATA-PIO.cxx | 6 +- Private/NewBoot/BootKit/BootKit.hxx | 110 +++++++++++++++----------- Private/NewBoot/BootKit/HW/ATA.hxx | 1 + Private/NewBoot/Source/HEL/AMD64/BootATA.cxx | 67 +++++++--------- Private/NewBoot/Source/HEL/AMD64/BootMain.cxx | 13 ++- Private/NewBoot/Source/makefile | 2 +- 7 files changed, 110 insertions(+), 92 deletions(-) diff --git a/Private/Builtins/ATA/ATA.hxx b/Private/Builtins/ATA/ATA.hxx index 66856d8a..a2ce79ba 100644 --- a/Private/Builtins/ATA/ATA.hxx +++ b/Private/Builtins/ATA/ATA.hxx @@ -102,7 +102,8 @@ #define ATA_PRIMARY 0x00 #define ATA_SECONDARY 0x01 -#define ATA_CYL_LOW 4 +#define ATA_CYL_LOW 3 +#define ATA_CYL_MID 4 #define ATA_CYL_HIGH 5 ///! IO Direction diff --git a/Private/HALKit/AMD64/Storage/ATA-PIO.cxx b/Private/HALKit/AMD64/Storage/ATA-PIO.cxx index f2ae01a4..beb113d3 100644 --- a/Private/HALKit/AMD64/Storage/ATA-PIO.cxx +++ b/Private/HALKit/AMD64/Storage/ATA-PIO.cxx @@ -134,12 +134,13 @@ Void drv_std_read(UInt64 Lba, UInt16 IO, UInt8 Master, Char* Buf, SizeT SectorSz, SizeT Size) { UInt8 Command = ((!Master )? 0xE0 : 0xF0); - Out8(IO + ATA_REG_HDDEVSEL, (Command) | (((Lba) >> 24) & 0xF)); + Out8(IO + ATA_REG_HDDEVSEL, (Command) | (((Lba) >> 24) & 0x0F)); Out8(IO + ATA_REG_SEC_COUNT0, 1); Out8(IO + ATA_REG_LBA0, (Lba)); Out8(IO + ATA_REG_LBA1, (Lba) >> 8); Out8(IO + ATA_REG_LBA2, (Lba) >> 16); + Out8(IO + ATA_REG_LBA4, (Lba) >> 24); Out8(IO + ATA_REG_COMMAND, ATA_CMD_READ_PIO); @@ -156,12 +157,13 @@ Void drv_std_write(UInt64 Lba, UInt16 IO, UInt8 Master, Char* Buf, SizeT SectorSz, SizeT Size) { UInt8 Command = ((!Master) ? 0xE0 : 0xF0); - Out8(IO + ATA_REG_HDDEVSEL, (Command) | (((Lba) >> 24) & 0xF)); + Out8(IO + ATA_REG_HDDEVSEL, (Command) | (((Lba) >> 24) & 0x0F)); Out8(IO + ATA_REG_SEC_COUNT0, 1); Out8(IO + ATA_REG_LBA0, (Lba)); Out8(IO + ATA_REG_LBA1, (Lba) >> 8); Out8(IO + ATA_REG_LBA2, (Lba) >> 16); + Out8(IO + ATA_REG_LBA4, (Lba) >> 24); Out8(IO + ATA_REG_COMMAND, ATA_CMD_WRITE_PIO); diff --git a/Private/NewBoot/BootKit/BootKit.hxx b/Private/NewBoot/BootKit/BootKit.hxx index ffa3af15..b3a81160 100644 --- a/Private/NewBoot/BootKit/BootKit.hxx +++ b/Private/NewBoot/BootKit/BootKit.hxx @@ -214,14 +214,25 @@ public: Boolean Format(const char* partName, BFileDescriptor* fileBlobs, SizeT blobCount); operator bool() noexcept { - fDiskDev.Leak().mBase = (kNewFSAddressAsLba / BootDev::kSectorSize); + fDiskDev.Leak().mBase = (kNewFSAddressAsLba); fDiskDev.Leak().mSize = BootDev::kSectorSize; Char buf[BootDev::kSectorSize] = { 0 }; fDiskDev.Read(buf, BootDev::kSectorSize); - return buf[0] == kNewFSIdent[0]; + NewPartitionBlock* blockPart = reinterpret_cast(buf); + + for (SizeT indexMag = 0UL; indexMag < kNewFSIdentLen; ++indexMag) { + if (blockPart->Ident[indexMag] != kNewFSIdent[indexMag]) + return false; + } + + BTextWriter writer; + + writer.Write(L"Disk Partition: ").Write(blockPart->PartitionName).Write(L" is okay.\r\n"); + + return true; } private: @@ -231,43 +242,55 @@ private: if (sectorSz != BootDev::kSectorSize) return false; BFileDescriptor* blob = fileBlobs; - Lba startLba = partBlock.FreeCatalog; - + Lba startLba = partBlock.StartCatalog; BTextWriter writer; + while (blob) { - NewCatalog catalogKind{ 0 }; + NewCatalog* catalogKind = new NewCatalog(); + memset(catalogKind, 0, sizeof(NewCatalog)); /// Fill catalog kind. - catalogKind.Kind = blob->fKind; + catalogKind->Kind = blob->fKind; /// Allocate fork for blob. - catalogKind.FirstFork = (startLba + sizeof(NewCatalog)); - catalogKind.LastFork = catalogKind.FirstFork; + catalogKind->FirstFork = (startLba + sizeof(NewCatalog)); + catalogKind->LastFork = catalogKind->FirstFork; - NewFork forkKind{ 0 }; + NewFork* forkKind = new NewFork(); + memset(forkKind, 0, sizeof(NewFork)); - memcpy(forkKind.Name, blob->fForkName, strlen(blob->fForkName)); - forkKind.Kind = (forkKind.Name[0] == kNewFSDataFork[0]) ? kNewFSDataForkKind : kNewFSRsrcForkKind; - forkKind.Flags = kNewFSFlagCreated; + memcpy(forkKind->Name, blob->fForkName, strlen(blob->fForkName)); + forkKind->Kind = (forkKind->Name[0] == kNewFSDataFork[0]) ? kNewFSDataForkKind : kNewFSRsrcForkKind; + forkKind->Flags = kNewFSFlagCreated; /// We don't know. - forkKind.ResourceFlags = 0; - forkKind.ResourceId = 0; - forkKind.ResourceKind = 0; + forkKind->ResourceFlags = 0; + forkKind->ResourceId = 0; + forkKind->ResourceKind = 0; /// We're the only fork here. - forkKind.NextSibling = catalogKind.FirstFork; - forkKind.PreviousSibling = catalogKind.FirstFork; + forkKind->NextSibling = catalogKind->FirstFork; + forkKind->PreviousSibling = catalogKind->FirstFork; - forkKind.DataOffset = (startLba + sizeof(NewCatalog) + sizeof(NewFork)); - forkKind.DataSize = blob->fBlobSz; + forkKind->DataOffset = (startLba + sizeof(NewCatalog) + sizeof(NewFork)); + forkKind->DataSize = blob->fBlobSz; - Lba lbaStart = forkKind.DataOffset; + Lba lbaStart = forkKind->DataOffset; SizeT cur = 0UL; - while (cur < forkKind.DataSize) { + writer.Write((catalogKind->Kind == kNewFSCatalogKindFile) ? L"New Boot: Write-File: " : + L"New Boot: Write-Directory: " ).Write(blob->fFileName).Write(L"\r\n"); + + /// Set disk cursor here. + + fDiskDev.Leak().mBase = startLba + sizeof(NewCatalog); + fDiskDev.Leak().mSize = sizeof(NewFork); + + fDiskDev.Write((Char*)forkKind, sizeof(NewFork)); + + while (cur < forkKind->DataSize) { this->fDiskDev.Leak().mSize = BootDev::kSectorSize; - this->fDiskDev.Leak().mBase = forkKind.DataOffset / BootDev::kSectorSize; + this->fDiskDev.Leak().mBase = (forkKind->DataOffset + cur); this->fDiskDev.Write((Char*)(blob->fBlob) + cur, BootDev::kSectorSize); @@ -275,48 +298,40 @@ private: lbaStart += BootDev::kSectorSize; } - writer.Write((catalogKind.Kind == kNewFSCatalogKindFile) ? L"New Boot: Write-File: " : - L"New Boot: Write-Directory: " ).Write(blob->fFileName).Write(L"\r\n"); - - /// Set disk cursor here. - - fDiskDev.Leak().mBase = startLba + sizeof(NewCatalog) / sectorSz; - fDiskDev.Leak().mSize = sizeof(NewFork); - - fDiskDev.Write((Char*)&forkKind, 1); /// Fork is done. - catalogKind.Kind = blob->fKind; - catalogKind.Flags |= kNewFSFlagCreated; + catalogKind->Kind = blob->fKind; + catalogKind->Flags |= kNewFSFlagCreated; Lba catalogLba = (sizeof(NewCatalog) - startLba); //// Now write catalog as well.. - catalogKind.PrevSibling = startLba; - catalogKind.NextSibling = (sizeof(NewCatalog) + blob->fBlobSz); + catalogKind->PrevSibling = startLba; + catalogKind->NextSibling = (sizeof(NewCatalog) + blob->fBlobSz); /// this mime only applies to file. - if (catalogKind.Kind == kNewFSCatalogKindFile) { - memcpy(catalogKind.Mime, kBKBootFileMime, strlen(kBKBootFileMime)); + if (catalogKind->Kind == kNewFSCatalogKindFile) { + memcpy(catalogKind->Mime, kBKBootFileMime, strlen(kBKBootFileMime)); } else { - memcpy(catalogKind.Mime, kBKBootDirMime, strlen(kBKBootDirMime)); + memcpy(catalogKind->Mime, kBKBootDirMime, strlen(kBKBootDirMime)); } - memcpy(catalogKind.Name, blob->fFileName, strlen(blob->fFileName)); + memcpy(catalogKind->Name, blob->fFileName, strlen(blob->fFileName)); - fDiskDev.Leak().mBase = startLba / sectorSz; + fDiskDev.Leak().mBase = startLba; fDiskDev.Leak().mSize = sizeof(NewCatalog); - fDiskDev.Write((Char*)&catalogKind, sectorSz); + fDiskDev.Write((Char*)catalogKind, sizeof(NewCatalog)); - startLba += (sizeof(NewCatalog) + blob->fBlobSz); + startLba += (sizeof(NewCatalog) + sizeof(NewFork) + blob->fBlobSz); --partBlock.FreeCatalog; --partBlock.FreeSectors; - ++partBlock.CatalogCount; + delete forkKind; + delete catalogKind; blob = blob->fNext; } @@ -346,22 +361,23 @@ inline Boolean BDiskFormatFactory::Format(const char* partName, NewPartitionBlock* partBlock = reinterpret_cast(buf); - memcpy(partBlock->Ident, kNewFSIdent, kNewFSIdentLen-1); + memcpy(partBlock->Ident, kNewFSIdent, kNewFSIdentLen - 1); memcpy(partBlock->PartitionName, partName, strlen(partName)); /// @note A catalog roughly equal to a sector. - partBlock->CatalogCount = 0UL; + partBlock->CatalogCount = blobCount; partBlock->Kind = kNewFSHardDrive; partBlock->SectorSize = sectorSz; partBlock->FreeCatalog = fDiskDev.GetSectorsCount() - partBlock->CatalogCount; partBlock->SectorCount = fDiskDev.GetSectorsCount(); partBlock->FreeSectors = fDiskDev.GetSectorsCount() - partBlock->CatalogCount; partBlock->StartCatalog = kNewFSCatalogStartAddress; + partBlock->DiskSize = fDiskDev.GetDiskSize(); if (this->WriteContent(fileBlobs, blobCount, sectorSz, *partBlock)) { - fDiskDev.Leak().mBase = (kNewFSAddressAsLba / sectorSz); - fDiskDev.Leak().mSize = BootDev::kSectorSize; + fDiskDev.Leak().mBase = (kNewFSAddressAsLba); + fDiskDev.Leak().mSize = sectorSz; fDiskDev.Write(buf, sectorSz); diff --git a/Private/NewBoot/BootKit/HW/ATA.hxx b/Private/NewBoot/BootKit/HW/ATA.hxx index 4b96e9fa..5bdcec56 100644 --- a/Private/NewBoot/BootKit/HW/ATA.hxx +++ b/Private/NewBoot/BootKit/HW/ATA.hxx @@ -37,6 +37,7 @@ class BootDeviceATA final : public Device { operator bool(); SizeT GetSectorsCount() noexcept; + SizeT GetDiskSize() noexcept; BootDeviceATA& Read(Char* Buf, const SizeT& SecCount) override; BootDeviceATA& Write(Char* Buf, const SizeT& SecCount) override; diff --git a/Private/NewBoot/Source/HEL/AMD64/BootATA.cxx b/Private/NewBoot/Source/HEL/AMD64/BootATA.cxx index bb634fbf..41ea04ac 100644 --- a/Private/NewBoot/Source/HEL/AMD64/BootATA.cxx +++ b/Private/NewBoot/Source/HEL/AMD64/BootATA.cxx @@ -88,44 +88,13 @@ ATAInit_Retry: boot_ata_wait_io(IO); for (SizeT indexData = 0ul; indexData < kATADataLen; ++indexData) { - kATAData[indexData] = In16(IO + ATA_REG_DATA); + kATAData[indexData] = In8(IO + ATA_REG_DATA); } OutBus = (Bus == ATA_PRIMARY_IO) ? BootDeviceATA::kPrimary : BootDeviceATA::kSecondary; - OutMaster = (Bus == ATA_PRIMARY_IO) ? ATA_MASTER : ATA_SLAVE; - - Out8(Bus + ATA_REG_HDDEVSEL, 0xA0 | ATA_MASTER << 4); - - In8(Bus + ATA_REG_CONTROL); - In8(Bus + ATA_REG_CONTROL); - In8(Bus + ATA_REG_CONTROL); - In8(Bus + ATA_REG_CONTROL); - - unsigned cl = In8(Bus + ATA_CYL_LOW); /* get the "signature bytes" */ - unsigned ch = In8(Bus + ATA_CYL_HIGH); - - /* differentiate ATA, ATAPI, SATA and SATAPI */ - if (cl == 0x14 && ch == 0xEB) { - writer.Write(L"New Boot: PATAPI drive detected.\r\n"); - kATADeviceType = kATADevicePATA_PI; - } - if (cl == 0x69 && ch == 0x96) { - writer.Write(L"New Boot: SATAPI drive detected.\r\n"); - kATADeviceType = kATADeviceSATA_PI; - } - - if (cl == 0x0 && ch == 0x0) { - writer.Write(L"New Boot: PATA drive detected.\r\n"); - kATADeviceType = kATADevicePATA; - } - - if (cl == 0x3c && ch == 0xc3) { - writer.Write(L"New Boot: SATA drive detected.\r\n"); - kATADeviceType = kATADeviceSATA; - } - Out8(IO + ATA_REG_CONTROL, 0x02); + OutMaster = (Bus == ATA_PRIMARY_IO) ? ATA_MASTER : ATA_SLAVE; return true; } @@ -137,12 +106,13 @@ Void boot_ata_read(UInt64 Lba, UInt16 IO, UInt8 Master, CharacterTypeUTF8* Buf, boot_ata_wait_io(IO); boot_ata_select(IO); - Out8(IO + ATA_REG_HDDEVSEL, (Command) | (((Lba) >> 24) & 0xF)); + Out8(IO + ATA_REG_HDDEVSEL, (Command) | (((Lba) >> 24) & 0x0F)); Out8(IO + ATA_REG_SEC_COUNT0, 1); Out8(IO + ATA_REG_LBA0, (Lba)); Out8(IO + ATA_REG_LBA1, (Lba) >> 8); Out8(IO + ATA_REG_LBA2, (Lba) >> 16); + Out8(IO + ATA_REG_LBA4, (Lba) >> 24); Out8(IO + ATA_REG_COMMAND, ATA_CMD_READ_PIO); @@ -159,12 +129,13 @@ Void boot_ata_write(UInt64 Lba, UInt16 IO, UInt8 Master, CharacterTypeUTF8* Buf, boot_ata_wait_io(IO); boot_ata_select(IO); - Out8(IO + ATA_REG_HDDEVSEL, (Command) | (((Lba) >> 24) & 0xF)); + Out8(IO + ATA_REG_HDDEVSEL, (Command) | (((Lba) >> 24) & 0x0F)); Out8(IO + ATA_REG_SEC_COUNT0, 1); Out8(IO + ATA_REG_LBA0, (Lba)); Out8(IO + ATA_REG_LBA1, (Lba) >> 8); Out8(IO + ATA_REG_LBA2, (Lba) >> 16); + Out8(IO + ATA_REG_LBA4, (Lba) >> 24); Out8(IO + ATA_REG_COMMAND, ATA_CMD_WRITE_PIO); @@ -217,7 +188,9 @@ BootDeviceATA& BootDeviceATA::Read(CharacterTypeUTF8* Buf, const SizeT& SectorSz if (!Buf || SectorSz < 1) return *this; - boot_ata_read(this->Leak().mBase, this->Leak().mBus, this->Leak().mMaster, + auto lba = this->Leak().mBase / BootDeviceATA::kSectorSize; + + boot_ata_read(lba, this->Leak().mBus, this->Leak().mMaster, Buf, SectorSz, this->Leak().mSize); return *this; @@ -238,7 +211,9 @@ BootDeviceATA& BootDeviceATA::Write(CharacterTypeUTF8* Buf, const SizeT& SectorS if (!Buf || SectorSz < 1) return *this; - boot_ata_write(this->Leak().mBase, this->Leak().mBus, this->Leak().mMaster, + auto lba = this->Leak().mBase / BootDeviceATA::kSectorSize; + + boot_ata_write(lba, this->Leak().mBus, this->Leak().mMaster, Buf, SectorSz, this->Leak().mSize); return *this; @@ -256,3 +231,21 @@ BootDeviceATA::ATATrait& BootDeviceATA::Leak() { return mTrait; } SizeT BootDeviceATA::GetSectorsCount() noexcept { return kATAData[60] + kATAData[61]; } + +SizeT BootDeviceATA::GetDiskSize() noexcept { + Out8(this->Leak().mBus + ATA_REG_COMMAND, 0xF8); + + boot_ata_wait_io(this->Leak().mBus); + + SizeT result = 0; + + result += In8(this->Leak().mBus + ATA_CYL_LOW); + result += In8(this->Leak().mBus + ATA_CYL_MID) << 8; + result += In8(this->Leak().mBus + ATA_CYL_HIGH) << 16; + result += In8(this->Leak().mBus + ATA_CYL_HIGH) << 24; + + BTextWriter writer; + writer.Write(L"Disk-Size: ").Write(result).Write(L"\r\n"); + + return result; +} diff --git a/Private/NewBoot/Source/HEL/AMD64/BootMain.cxx b/Private/NewBoot/Source/HEL/AMD64/BootMain.cxx index 5e9e2355..a928a41a 100644 --- a/Private/NewBoot/Source/HEL/AMD64/BootMain.cxx +++ b/Private/NewBoot/Source/HEL/AMD64/BootMain.cxx @@ -193,9 +193,11 @@ EFI_EXTERN_C EFI_API Int Main(EfiHandlePtr ImageHandle, memcpy(rootDesc.fFileName, "/", strlen("/")); memcpy(rootDesc.fForkName, kNewFSResourceFork, strlen(kNewFSResourceFork)); - rootDesc.fBlobSz = strlen(kMachineModel " startup disk."); + rootDesc.fBlobSz = BootDeviceATA::kSectorSize; rootDesc.fBlob = new Char[rootDesc.fBlobSz]; + memset(rootDesc.fBlob, 0, rootDesc.fBlobSz); + memcpy(rootDesc.fBlob, kMachineModel " startup disk.", strlen(kMachineModel " startup disk.")); @@ -207,12 +209,15 @@ EFI_EXTERN_C EFI_API Int Main(EfiHandlePtr ImageHandle, memcpy(bootDesc.fFileName, "/Boot", strlen("/Boot")); memcpy(bootDesc.fForkName, kNewFSResourceFork, strlen(kNewFSResourceFork)); + + bootDesc.fBlobSz = BootDeviceATA::kSectorSize; + bootDesc.fBlob = new Char[rootDesc.fBlobSz]; + + memset(bootDesc.fBlob, 0, bootDesc.fBlobSz); + memcpy(bootDesc.fBlob, kMachineModel " startup folder.", strlen(kMachineModel " startup folder.")); - bootDesc.fBlobSz = strlen(kMachineModel " startup folder."); - bootDesc.fBlob = new Char[bootDesc.fBlobSz]; - BDiskFormatFactory::BFileDescriptor kernelDesc{0}; kernelDesc.fKind = kNewFSCatalogKindFile; diff --git a/Private/NewBoot/Source/makefile b/Private/NewBoot/Source/makefile index 92128b02..4d8e1100 100644 --- a/Private/NewBoot/Source/makefile +++ b/Private/NewBoot/Source/makefile @@ -70,7 +70,7 @@ run-efi-amd64: .PHONY: epm-img epm-img: - qemu-img create -f qcow2 $(IMG) 512M + qemu-img create -f qcow2 $(IMG) 1G qemu-img create -f qcow2 $(IMG_2) 512M .PHONY: download-edk -- cgit v1.2.3 From e9b93cb61f130c2b07bdc031a2487e27ca5333f1 Mon Sep 17 00:00:00 2001 From: Amlal El Mahrouss Date: Fri, 26 Apr 2024 10:44:18 +0200 Subject: MHR-16: NewBoot - BDiskFormatter and QR. Signed-off-by: Amlal El Mahrouss --- Private/NewBoot/BootKit/BootKit.hxx | 18 ++++++++++++------ Private/NewBoot/Source/HEL/AMD64/BootATA.cxx | 13 +++++++++---- Private/NewBoot/Source/HEL/AMD64/BootFileReader.cxx | 2 +- Private/NewBoot/Source/HEL/AMD64/BootMain.cxx | 4 +++- 4 files changed, 25 insertions(+), 12 deletions(-) diff --git a/Private/NewBoot/BootKit/BootKit.hxx b/Private/NewBoot/BootKit/BootKit.hxx index b3a81160..76bfbfb0 100644 --- a/Private/NewBoot/BootKit/BootKit.hxx +++ b/Private/NewBoot/BootKit/BootKit.hxx @@ -213,6 +213,7 @@ public: /// @retval False failed to format. Boolean Format(const char* partName, BFileDescriptor* fileBlobs, SizeT blobCount); + /// @brief check if partition is good. operator bool() noexcept { fDiskDev.Leak().mBase = (kNewFSAddressAsLba); fDiskDev.Leak().mSize = BootDev::kSectorSize; @@ -228,9 +229,17 @@ public: return false; } + if (blockPart->DiskSize != this->fDiskDev.GetDiskSize()) { + EFI::ThrowError(L"Invalid-Disk-Geometry", L"Invalid disk geometry."); + } + + if (blockPart->DiskSize < 1) { + EFI::ThrowError(L"Invalid-Disk-Geometry", L"Invalid disk geometry."); + } + BTextWriter writer; - writer.Write(L"Disk Partition: ").Write(blockPart->PartitionName).Write(L" is okay.\r\n"); + writer.Write(L"Disk Partition: ").Write(blockPart->PartitionName).Write(L" is healthy.\r\n"); return true; } @@ -275,7 +284,6 @@ private: forkKind->DataOffset = (startLba + sizeof(NewCatalog) + sizeof(NewFork)); forkKind->DataSize = blob->fBlobSz; - Lba lbaStart = forkKind->DataOffset; SizeT cur = 0UL; writer.Write((catalogKind->Kind == kNewFSCatalogKindFile) ? L"New Boot: Write-File: " : @@ -288,16 +296,14 @@ private: fDiskDev.Write((Char*)forkKind, sizeof(NewFork)); - while (cur < forkKind->DataSize) { + do { this->fDiskDev.Leak().mSize = BootDev::kSectorSize; this->fDiskDev.Leak().mBase = (forkKind->DataOffset + cur); this->fDiskDev.Write((Char*)(blob->fBlob) + cur, BootDev::kSectorSize); cur += BootDev::kSectorSize; - lbaStart += BootDev::kSectorSize; - } - + } while (cur < forkKind->DataSize); /// Fork is done. diff --git a/Private/NewBoot/Source/HEL/AMD64/BootATA.cxx b/Private/NewBoot/Source/HEL/AMD64/BootATA.cxx index 41ea04ac..4bf7bc96 100644 --- a/Private/NewBoot/Source/HEL/AMD64/BootATA.cxx +++ b/Private/NewBoot/Source/HEL/AMD64/BootATA.cxx @@ -237,15 +237,20 @@ SizeT BootDeviceATA::GetDiskSize() noexcept { boot_ata_wait_io(this->Leak().mBus); - SizeT result = 0; + UInt64 result = 0; - result += In8(this->Leak().mBus + ATA_CYL_LOW); + result = In8(this->Leak().mBus + ATA_CYL_LOW); result += In8(this->Leak().mBus + ATA_CYL_MID) << 8; result += In8(this->Leak().mBus + ATA_CYL_HIGH) << 16; - result += In8(this->Leak().mBus + ATA_CYL_HIGH) << 24; + + Out8(this->Leak().mBus + ATA_REG_CONTROL, 0x80); + + result += In8(this->Leak().mBus + ATA_CYL_LOW) << 24; + result += In8(this->Leak().mBus + ATA_CYL_MID) << 32; + result += In8(this->Leak().mBus + ATA_CYL_HIGH) << 40; BTextWriter writer; - writer.Write(L"Disk-Size: ").Write(result).Write(L"\r\n"); + writer.Write(L"Device-Size: ").Write(result).Write(L"\r\n"); return result; } diff --git a/Private/NewBoot/Source/HEL/AMD64/BootFileReader.cxx b/Private/NewBoot/Source/HEL/AMD64/BootFileReader.cxx index 0e126ada..b2d728ae 100644 --- a/Private/NewBoot/Source/HEL/AMD64/BootFileReader.cxx +++ b/Private/NewBoot/Source/HEL/AMD64/BootFileReader.cxx @@ -110,7 +110,7 @@ Void BFileReader::ReadAll(SizeT until, SizeT chunk) { if (auto err = BS->AllocatePool(EfiLoaderCode, until, (VoidPtr*)&mBlob) != kEfiOk) { mWriter.Write(L"*** EFI-Code: ").Write(err).Write(L" ***\r\n"); - EFI::ThrowError(L"NewBoot_PageError", L"Allocation error."); + EFI::ThrowError(L"OutOfMemory", L"Allocation error."); } } diff --git a/Private/NewBoot/Source/HEL/AMD64/BootMain.cxx b/Private/NewBoot/Source/HEL/AMD64/BootMain.cxx index a928a41a..1c969b28 100644 --- a/Private/NewBoot/Source/HEL/AMD64/BootMain.cxx +++ b/Private/NewBoot/Source/HEL/AMD64/BootMain.cxx @@ -181,9 +181,11 @@ EFI_EXTERN_C EFI_API Int Main(EfiHandlePtr ImageHandle, /// format the disk. // + constexpr auto binarySize = KIB(512); + /// need this as well, to invoke BExecutableLoader. BFileReader readerKernel(L"NewKernel.exe", ImageHandle); - readerKernel.ReadAll(MIB(1), 4096); + readerKernel.ReadAll(binarySize, BootDeviceATA::kSectorSize); BDiskFormatFactory diskFormatter; -- cgit v1.2.3 From 72b014b98fab4a6f875648a4b7b42347f780067e Mon Sep 17 00:00:00 2001 From: Amlal El Mahrouss Date: Fri, 26 Apr 2024 11:00:27 +0200 Subject: MHR-16: bug fix Write number method, as well as an improved partition checker. Signed-off-by: Amlal El Mahrouss --- Private/NewBoot/BootKit/BootKit.hxx | 10 +++++----- Private/NewBoot/Source/HEL/AMD64/BootTextWriter.cxx | 4 ++-- Private/NewBoot/Source/makefile | 2 +- 3 files changed, 8 insertions(+), 8 deletions(-) diff --git a/Private/NewBoot/BootKit/BootKit.hxx b/Private/NewBoot/BootKit/BootKit.hxx index 76bfbfb0..2d8b535d 100644 --- a/Private/NewBoot/BootKit/BootKit.hxx +++ b/Private/NewBoot/BootKit/BootKit.hxx @@ -229,12 +229,12 @@ public: return false; } - if (blockPart->DiskSize != this->fDiskDev.GetDiskSize()) { + if (blockPart->DiskSize != this->fDiskDev.GetDiskSize() || + blockPart->DiskSize < 1 || + blockPart->SectorSize != BootDev::kSectorSize) { EFI::ThrowError(L"Invalid-Disk-Geometry", L"Invalid disk geometry."); - } - - if (blockPart->DiskSize < 1) { - EFI::ThrowError(L"Invalid-Disk-Geometry", L"Invalid disk geometry."); + } else if (blockPart->PartitionName[0] == 0) { + EFI::ThrowError(L"Invalid-Partition-Name", L"Invalid disk partition."); } BTextWriter writer; diff --git a/Private/NewBoot/Source/HEL/AMD64/BootTextWriter.cxx b/Private/NewBoot/Source/HEL/AMD64/BootTextWriter.cxx index ff30ff95..fc91a02a 100644 --- a/Private/NewBoot/Source/HEL/AMD64/BootTextWriter.cxx +++ b/Private/NewBoot/Source/HEL/AMD64/BootTextWriter.cxx @@ -75,8 +75,8 @@ BTextWriter &BTextWriter::Write(const Long &x) { BTextWriter &BTextWriter::_Write(const Long &x) { #ifdef __DEBUG__ - int y = x / 16; - int h = x % 16; + UInt64 y = (x > 0 ? x : -x) / 16; + UInt64 h = (x > 0 ? x : -x) % 16; if (y) this->_Write(y); diff --git a/Private/NewBoot/Source/makefile b/Private/NewBoot/Source/makefile index 4d8e1100..92128b02 100644 --- a/Private/NewBoot/Source/makefile +++ b/Private/NewBoot/Source/makefile @@ -70,7 +70,7 @@ run-efi-amd64: .PHONY: epm-img epm-img: - qemu-img create -f qcow2 $(IMG) 1G + qemu-img create -f qcow2 $(IMG) 512M qemu-img create -f qcow2 $(IMG_2) 512M .PHONY: download-edk -- cgit v1.2.3 From fc19214c74c39177f85a4ee0748ac4ec9c1d4f33 Mon Sep 17 00:00:00 2001 From: Amlal El Mahrouss Date: Fri, 26 Apr 2024 12:23:00 +0200 Subject: MHR-16: Fix bug inside GetDiskSize, use a simple formula instead of doing stupid sh*t. Signed-off-by: Amlal El Mahrouss --- Private/NewBoot/BootKit/BootKit.hxx | 7 ++++--- Private/NewBoot/Source/HEL/AMD64/BootATA.cxx | 23 ++--------------------- 2 files changed, 6 insertions(+), 24 deletions(-) diff --git a/Private/NewBoot/BootKit/BootKit.hxx b/Private/NewBoot/BootKit/BootKit.hxx index 2d8b535d..f7f33958 100644 --- a/Private/NewBoot/BootKit/BootKit.hxx +++ b/Private/NewBoot/BootKit/BootKit.hxx @@ -229,6 +229,9 @@ public: return false; } + BTextWriter writer; + writer.Write(L"Device Size: ").Write(this->fDiskDev.GetDiskSize()).Write(L"\r\n"); + if (blockPart->DiskSize != this->fDiskDev.GetDiskSize() || blockPart->DiskSize < 1 || blockPart->SectorSize != BootDev::kSectorSize) { @@ -237,9 +240,7 @@ public: EFI::ThrowError(L"Invalid-Partition-Name", L"Invalid disk partition."); } - BTextWriter writer; - - writer.Write(L"Disk Partition: ").Write(blockPart->PartitionName).Write(L" is healthy.\r\n"); + writer.Write(L"Device Partition: ").Write(blockPart->PartitionName).Write(L" is healthy.\r\n"); return true; } diff --git a/Private/NewBoot/Source/HEL/AMD64/BootATA.cxx b/Private/NewBoot/Source/HEL/AMD64/BootATA.cxx index 4bf7bc96..8ab7dc20 100644 --- a/Private/NewBoot/Source/HEL/AMD64/BootATA.cxx +++ b/Private/NewBoot/Source/HEL/AMD64/BootATA.cxx @@ -229,28 +229,9 @@ BootDeviceATA::ATATrait& BootDeviceATA::Leak() { return mTrait; } @brief Getter, gets the number of sectors inside the drive. */ SizeT BootDeviceATA::GetSectorsCount() noexcept { - return kATAData[60] + kATAData[61]; + return (kATAData[61] << 16)| kATAData[60]; } SizeT BootDeviceATA::GetDiskSize() noexcept { - Out8(this->Leak().mBus + ATA_REG_COMMAND, 0xF8); - - boot_ata_wait_io(this->Leak().mBus); - - UInt64 result = 0; - - result = In8(this->Leak().mBus + ATA_CYL_LOW); - result += In8(this->Leak().mBus + ATA_CYL_MID) << 8; - result += In8(this->Leak().mBus + ATA_CYL_HIGH) << 16; - - Out8(this->Leak().mBus + ATA_REG_CONTROL, 0x80); - - result += In8(this->Leak().mBus + ATA_CYL_LOW) << 24; - result += In8(this->Leak().mBus + ATA_CYL_MID) << 32; - result += In8(this->Leak().mBus + ATA_CYL_HIGH) << 40; - - BTextWriter writer; - writer.Write(L"Device-Size: ").Write(result).Write(L"\r\n"); - - return result; + return this->GetSectorsCount() * BootDeviceATA::kSectorSize; } -- cgit v1.2.3 From 313c303fab092b1c45e615f960826375e7eef093 Mon Sep 17 00:00:00 2001 From: Amlal El Mahrouss Date: Fri, 26 Apr 2024 14:23:37 +0200 Subject: MHR-16: Last commit on branch, merging now. - boot manager and micro kernel have been unified, as the USA design states. Signed-off-by: Amlal El Mahrouss --- Private/HALKit/AMD64/HalNewBoot.asm | 3 +++ Private/NewBoot/Source/CDROM/SplashScreen.fmt | 5 +++-- Private/NewBoot/Source/HEL/AMD64/BootMain.cxx | 25 ++++------------------- Private/NewBoot/Source/HEL/AMD64/BootPlatform.cxx | 9 ++++++++ Private/NewBoot/Source/HEL/AMD64/New+Delete.cxx | 4 ++++ Private/NewBoot/Source/HEL/AMD64/Support.cxx | 5 ++++- Private/NewBoot/Source/makefile | 5 ++--- Private/Source/Utils.cxx | 9 ++++++-- 8 files changed, 36 insertions(+), 29 deletions(-) diff --git a/Private/HALKit/AMD64/HalNewBoot.asm b/Private/HALKit/AMD64/HalNewBoot.asm index 11b11c0c..e9034f05 100644 --- a/Private/HALKit/AMD64/HalNewBoot.asm +++ b/Private/HALKit/AMD64/HalNewBoot.asm @@ -28,9 +28,12 @@ HandoverStart: dq __ImageStart section .text global __ImageStart +global __NewBootJumpProc + extern hal_init_platform ;; Just a simple setup, we'd also need to tell some before +__NewBootJumpProc: __ImageStart: push rcx call hal_init_platform diff --git a/Private/NewBoot/Source/CDROM/SplashScreen.fmt b/Private/NewBoot/Source/CDROM/SplashScreen.fmt index 339b94e7..857c63a1 100644 --- a/Private/NewBoot/Source/CDROM/SplashScreen.fmt +++ b/Private/NewBoot/Source/CDROM/SplashScreen.fmt @@ -1,6 +1,7 @@ Welcome to NeWS. -Brought to you by: -* MicroKernel, Bootloader: Amlal EL Mahrouss. +Brought to you by: Amlal EL Mahrouss. +* NewBoot, NewKernel: Amlal EL Mahrouss. +This copy can boot directly to NewKernel (Unified System). Copyright Mahrouss-Logic, all rights reserved. diff --git a/Private/NewBoot/Source/HEL/AMD64/BootMain.cxx b/Private/NewBoot/Source/HEL/AMD64/BootMain.cxx index 1c969b28..68762089 100644 --- a/Private/NewBoot/Source/HEL/AMD64/BootMain.cxx +++ b/Private/NewBoot/Source/HEL/AMD64/BootMain.cxx @@ -21,6 +21,8 @@ /** Graphics related. */ +EXTERN_C Void hal_init_platform(HEL::HandoverInformationHeader* HIH); + STATIC EfiGraphicsOutputProtocol* kGop = nullptr; STATIC UInt16 kStride = 0U; STATIC EfiGUID kGopGuid; @@ -181,12 +183,6 @@ EFI_EXTERN_C EFI_API Int Main(EfiHandlePtr ImageHandle, /// format the disk. // - constexpr auto binarySize = KIB(512); - - /// need this as well, to invoke BExecutableLoader. - BFileReader readerKernel(L"NewKernel.exe", ImageHandle); - readerKernel.ReadAll(binarySize, BootDeviceATA::kSectorSize); - BDiskFormatFactory diskFormatter; if (!diskFormatter) { @@ -220,28 +216,15 @@ EFI_EXTERN_C EFI_API Int Main(EfiHandlePtr ImageHandle, memcpy(bootDesc.fBlob, kMachineModel " startup folder.", strlen(kMachineModel " startup folder.")); - BDiskFormatFactory::BFileDescriptor kernelDesc{0}; - - kernelDesc.fKind = kNewFSCatalogKindFile; - - memcpy(kernelDesc.fFileName, "/Boot/NewKernel", strlen("/Boot/NewKernel")); - memcpy(kernelDesc.fForkName, kNewFSDataFork, strlen(kNewFSDataFork)); - - kernelDesc.fBlob = readerKernel.Blob(); - kernelDesc.fBlobSz = readerKernel.Size(); - rootDesc.fNext = &bootDesc; rootDesc.fNext->fPrev = &rootDesc; - rootDesc.fNext->fNext = &kernelDesc; - rootDesc.fNext->fNext->fPrev = &bootDesc; - - diskFormatter.Format(kMachineModel, &rootDesc, 3); + diskFormatter.Format(kMachineModel, &rootDesc, 2); } EFI::ExitBootServices(MapKey, ImageHandle); - rt_jump_to_address(readerKernel.Blob()); + hal_init_platform(kHandoverHeader); EFI::Stop(); diff --git a/Private/NewBoot/Source/HEL/AMD64/BootPlatform.cxx b/Private/NewBoot/Source/HEL/AMD64/BootPlatform.cxx index f47e3532..2ac90dd8 100644 --- a/Private/NewBoot/Source/HEL/AMD64/BootPlatform.cxx +++ b/Private/NewBoot/Source/HEL/AMD64/BootPlatform.cxx @@ -7,6 +7,9 @@ #include #include #include +#include "HALKit/AMD64/Processor.hpp" + +#if 0 EXTERN_C void rt_hlt() { asm volatile("hlt"); } @@ -50,3 +53,9 @@ EXTERN_C UInt32 In32(UInt16 port) { return value; } + +#else + +void rt_hlt() { NewOS::HAL::rt_halt(); } + +#endif // 0 diff --git a/Private/NewBoot/Source/HEL/AMD64/New+Delete.cxx b/Private/NewBoot/Source/HEL/AMD64/New+Delete.cxx index 01911c43..909ccca6 100644 --- a/Private/NewBoot/Source/HEL/AMD64/New+Delete.cxx +++ b/Private/NewBoot/Source/HEL/AMD64/New+Delete.cxx @@ -9,6 +9,8 @@ #include #include /* Since we're using GCC for this EFI program. */ +#if 0 + /// @brief Allocates a new object. /// @param sz the size. /// @return @@ -45,3 +47,5 @@ void operator delete(void* buf, size_t size) { BS->FreePool(buf); } + +#endif // Inactive diff --git a/Private/NewBoot/Source/HEL/AMD64/Support.cxx b/Private/NewBoot/Source/HEL/AMD64/Support.cxx index 0508d491..a8e2c275 100644 --- a/Private/NewBoot/Source/HEL/AMD64/Support.cxx +++ b/Private/NewBoot/Source/HEL/AMD64/Support.cxx @@ -8,6 +8,8 @@ #include #include +#if 0 + /// @brief memset definition in C++. /// @param dst destination pointer. /// @param byte value to fill in. @@ -41,6 +43,7 @@ EXTERN_C size_t strlen(const char *whatToCheck) { return len; } - /// @brief somthing specific to the microsoft ABI, regarding checking the stack. EXTERN_C void ___chkstk_ms(void) {} + +#endif diff --git a/Private/NewBoot/Source/makefile b/Private/NewBoot/Source/makefile index 92128b02..8306f844 100644 --- a/Private/NewBoot/Source/makefile +++ b/Private/NewBoot/Source/makefile @@ -28,7 +28,7 @@ EMU_FLAGS=-net none -smp 4 -m 8G -M q35 -bios OVMF.fd -device piix3-ide,id=ide - LD_FLAGS=-e Main --subsystem=10 -OBJ=*.o +OBJ=*.o ../../Objects/*.obj REM=rm REM_FLAG=-f @@ -53,7 +53,6 @@ all: compile-amd64 $(LD_GNU) $(OBJ) $(LD_FLAGS) -o $(BOOT_LOADER) $(COPY) $(BOOT_LOADER) CDROM/EFI/BOOT/BOOTX64.EFI $(COPY) $(BOOT_LOADER) CDROM/EFI/BOOT/NEWBOOT.EFI - $(COPY) ../../$(KERNEL) CDROM/$(KERNEL) ifneq ($(DEBUG_SUPPORT), ) DEBUG = -D__DEBUG__ @@ -61,7 +60,7 @@ endif .PHONY: compile-amd64 compile-amd64: - $(WINDRES) BootloaderRsrc.rsrc -O coff -o BootloaderRsrc.o + # $(WINDRES) BootloaderRsrc.rsrc -O coff -o BootloaderRsrc.o $(CC_GNU) $(NEWOS_MODEL) $(FLAG_GNU) $(DEBUG) $(wildcard HEL/AMD64/*.cxx) $(wildcard HEL/AMD64/*.S) $(wildcard *.cxx) .PHONY: run-efi-amd64 diff --git a/Private/Source/Utils.cxx b/Private/Source/Utils.cxx index e12041c8..fcdddc4a 100644 --- a/Private/Source/Utils.cxx +++ b/Private/Source/Utils.cxx @@ -169,10 +169,15 @@ char *rt_string_frofchar(char *str, const char chr) { } } // namespace NewOS -extern "C" void memset(void *dst, char src, size_t len) { +EXTERN_C void memset(void *dst, char src, size_t len) { NewOS::rt_set_memory(dst, src, len); } -extern "C" void memcpy(void *dst, void *src, size_t len) { +EXTERN_C void memcpy(void *dst, void *src, size_t len) { NewOS::rt_copy_memory(src, dst, len); } + +/// @brief strlen definition in C++. +EXTERN_C size_t strlen(const char *whatToCheck) { + return NewOS::rt_string_len(whatToCheck); +} -- cgit v1.2.3