71 Commits

Author SHA1 Message Date
27fec1bacb Add boot options with on-screen debugging 2025-09-05 21:30:01 +02:00
d8e0e07805 Correct format specifier for partition size to prevent stack corruption 2025-09-04 12:21:04 +02:00
8898a427df Rewrite and clarify kernel subsystem descriptions 2025-09-04 11:16:03 +02:00
7e039c47ae Simplify BlpDebugPutChar return path 2025-09-04 10:56:17 +02:00
c2a4ad026a Implement KD subsystem, add serial & framebuffer debug providers 2025-09-04 10:49:40 +02:00
db81e43525 Add missing forward references for RTL types 2025-09-04 10:28:32 +02:00
9cc776e06a Add generic kernel information support 2025-09-03 21:00:18 +02:00
602da0960c Unify string API parameter types to PCSTR/PCWSTR 2025-09-03 19:54:46 +02:00
9577a39046 Fix initialization block size calculation to account for variable-length kernel parameters 2025-09-03 18:10:42 +02:00
f9fe20ba68 Adjust forward references for HL_FRAMEBUFFER_DATA and HL_SCROLL_REGION_DATA 2025-09-03 16:44:52 +02:00
227da47bfc Add scroll region support and refactor framebuffer handling 2025-09-03 15:06:25 +02:00
9f5daafad9 Unify wide string types across console and debug functions 2025-09-03 10:41:24 +02:00
b2df65f5cc Fix KeDbgPrint prototype to use PCWSTR 2025-09-03 10:29:21 +02:00
d6999fad2f Extend RTL with substring search and character case functions 2025-09-02 21:51:10 +02:00
e4981b52ed Comment RtlTokenizeWideString for clarity 2025-09-02 20:18:33 +02:00
3c25934495 Add explanatory comments to string handling code 2025-09-02 19:31:13 +02:00
e23a4c71a2 Fix framebuffer address calculations by using Pitch and BytesPerPixel 2025-09-02 12:42:06 +02:00
6ee7243e04 Refactor APIC delivery mode handling and unify naming 2025-09-01 19:54:12 +02:00
d45cc5ffe5 Fix incorrect APIC delivery mode definitions 2025-09-01 19:32:29 +02:00
3c8b7cb1f2 Remove unused variable 2025-09-01 19:25:45 +02:00
2e415f6ec2 Remove broadcast INIT IPI 2025-09-01 19:23:02 +02:00
5ff9303bd1 Add debug screen clear at end of kernel initialization 2025-09-01 16:27:28 +02:00
84ac8f00e0 Fix APIC initialization and refine comments 2025-09-01 15:41:06 +02:00
418ff68be4 Add ESP boot support and improve block device enumeration 2025-09-01 14:02:38 +02:00
2d1b6363e6 Add CTRL-B shortcut to boot OS directly from edit menu 2025-09-01 12:43:33 +02:00
34cebf2810 Allow editing boot options using 'e' key 2025-09-01 11:47:36 +02:00
0fa4a175e0 Correct Backspace behavior in input dialog 2025-09-01 11:40:48 +02:00
72a832f190 Fix type mismatch in BlGetEditableOptions OptionsCount parameter 2025-08-30 20:35:01 +02:00
ba65264d1e Remove unnecessary console input buffer reset 2025-08-27 22:21:39 +02:00
2ee33ab229 Refactor BlGetConfigValue to return EFI_STATUS and output value via parameter 2025-08-27 19:44:52 +02:00
1eea654a36 Expose BlGetBootOptionValue, BlGetEditableOptions and BlSetBootOptionValue 2025-08-27 19:26:01 +02:00
c6643125e1 Implement boot entry editor 2025-08-27 19:15:38 +02:00
b68514b176 Limit boot menu entry names to available menu width 2025-08-25 19:03:57 +02:00
960e913222 Optimize boot menu drawing to eliminate screen flickering 2025-08-25 17:56:40 +02:00
e99e563aff Correct .modinfo section parsing 2025-08-25 12:07:49 +02:00
0b40a3fb10 Refactor MMU for multi-paging support and add 5-Level paging 2025-08-23 20:03:56 +02:00
a84ef21571 Adjust LA57 base addresses to prevent overflow 2025-08-21 01:42:36 +02:00
1ef2560ef6 Enable LA57 by invoking the trampoline code 2025-08-21 00:14:49 +02:00
d1b14fccdd Resolve build issues caused by the last commit 2025-08-20 21:08:43 +02:00
88b3a57962 Allow specifying an allocation type when allocating pages 2025-08-20 20:59:31 +02:00
9f6121e9b2 Map the physical page for trampoline code 2025-08-20 20:37:55 +02:00
4a7ea6009d Expose ArEnableExtendedPhysicalAddressing function in XTDK 2025-08-20 20:23:44 +02:00
c4a7df6f38 Extract trampoline code into a separate file 2025-08-20 20:20:35 +02:00
2468d80078 Add trampoline to enable 5-level paging 2025-08-20 00:20:10 +02:00
ebae8c655c Expand CR4, MSR, and EFER register definitions 2025-08-19 23:59:58 +02:00
1a0bc7f65f Update and correct CR4 bit definitions 2025-08-19 21:45:13 +02:00
91a5db2ee4 Implement PML5 support in XtpMapHardwareMemoryPool 2025-08-18 12:13:48 +02:00
b639bf3077 Implement PML5 self-mapping 2025-08-18 11:59:05 +02:00
c409400cbf Correct VA masking in AMD64 page mapping functions 2025-08-18 01:07:28 +02:00
d602038858 Temporarily disable LA57 paging 2025-08-18 00:10:32 +02:00
017b8603d5 Align parameters in PTE manipulation functions 2025-08-17 21:55:21 +02:00
a9dd1eaacd Implement MmpSetPteCaching function for AMD64 architecture 2025-08-17 21:51:43 +02:00
f30d3df5b3 Implement PTE manipulation functions for AMD64 architecture 2025-08-17 21:48:28 +02:00
c3ece4f317 Fix type usage in XtpMapHardwareMemoryPool 2025-08-17 00:51:26 +02:00
1e11acee72 Refactor hardware memory mapping to use page map routine callbacks 2025-08-17 00:47:56 +02:00
57193eecc0 Implement PML2/PML3 page table routines 2025-08-17 00:45:12 +02:00
720d525b95 Assign page map routines 2025-08-17 00:29:28 +02:00
f77f2bbf92 Introduce architecture-specific page map routines 2025-08-17 00:23:19 +02:00
0ed59f223c Relocate page mapping helpers and add PML5 support 2025-08-16 21:07:54 +02:00
de2973ac42 Implement page map info initialization 2025-08-16 20:28:05 +02:00
8491e5fed1 Remove PageMapLevel from the loader information block 2025-08-16 20:18:34 +02:00
6a330e38f2 Consolidate paging-related globals into MmpPageMapInfo 2025-08-16 20:14:18 +02:00
1dcd3fceed Define page map information structure for both supported architectures 2025-08-16 20:08:12 +02:00
5768d4bba6 Prepare for architecture-specific paging initialization 2025-08-16 19:58:00 +02:00
f85fe31b38 Adapt i686 memory mapping to new PML3 types 2025-08-16 00:36:20 +02:00
22f81a106b Update forward declarations for PML2/PML3 types 2025-08-16 00:33:18 +02:00
7e08dc286e Separate types for legacy (PML2) and PAE (PML3) paging 2025-08-16 00:29:20 +02:00
3ca6d04f6b Add definitions for 5-level paging and refactor constants 2025-08-16 00:22:21 +02:00
e57985da8d Rename MM_LA57_SHIFT to MM_P5I_SHIFT for consistency 2025-08-15 20:49:25 +02:00
8a23cc444f Merge branch 'master' into harraiken_mm 2025-08-15 11:30:48 +02:00
e8771dfc5b Use __asm__ to comply with disabled GNU extensions 2025-08-15 00:32:56 +02:00
78 changed files with 3877 additions and 746 deletions

View File

@@ -40,6 +40,14 @@ SystemPath=multi(0)disk(0)rdisk(0)partition(1)/ExectOS
KernelFile=xtoskrnl.exe
Parameters=DEBUG=COM1,115200
[ExectOS_FBDEBUG]
SystemName="ExectOS Operating System (FBDEBUG)"
SystemType=XTOS
BootModules=xtos_o
SystemPath=multi(0)disk(0)rdisk(0)partition(1)/ExectOS
KernelFile=xtoskrnl.exe
Parameters=DEBUG=COM1,115200;SCREEN
[ExectOS_NOXPA]
SystemName="ExectOS Operating System (NOXPA)"
SystemType=XTOS
@@ -48,6 +56,14 @@ SystemPath=multi(0)disk(0)rdisk(0)partition(1)/ExectOS
KernelFile=xtoskrnl.exe
Parameters=DEBUG=COM1,115200 NOXPA
[ExectOS_NOXPA_FBDEBUG]
SystemName="ExectOS Operating System (NOXPA / FBDEBUG)"
SystemType=XTOS
BootModules=xtos_o
SystemPath=multi(0)disk(0)rdisk(0)partition(1)/ExectOS
KernelFile=xtoskrnl.exe
Parameters=DEBUG=COM1,115200;SCREEN NOXPA
[Windows]
SystemName="Microsoft Windows 2000"
SystemType=NT50

View File

@@ -24,6 +24,10 @@ XTCDECL
BOOLEAN
ArCpuId(IN OUT PCPUID_REGISTERS Registers);
XTCDECL
VOID
ArEnableExtendedPhysicalAddressing(IN ULONG_PTR PageMap);
XTCDECL
VOID
ArHalt(VOID);

View File

@@ -39,13 +39,22 @@
#define CR4_PCE 0x00000100
#define CR4_FXSR 0x00000200
#define CR4_XMMEXCPT 0x00000400
#define CR4_UMIP 0x00000800
#define CR4_LA57 0x00001000
#define CR4_RESERVED1 0x00001800
#define CR4_VMXE 0x00002000
#define CR4_SMXE 0x00004000
#define CR4_RESERVED2 0x00018000
#define CR4_XSAVE 0x00020000
#define CR4_RESERVED3 0xFFFC0000
#define CR4_FSGSBASE 0x00010000
#define CR4_PCIDE 0x00020000
#define CR4_XSAVE 0x00040000
#define CR4_KL 0x00080000
#define CR4_SMEP 0x00100000
#define CR4_SMAP 0x00200000
#define CR4_PKE 0x00400000
#define CR4_CET 0x00800000
#define CR4_PKS 0x01000000
#define CR4_UINTR 0x02000000
#define CR4_LASS 0x08000000
#define CR4_LAM_SUP 0x10000000
/* Descriptors size */
#define GDT_ENTRIES 128
@@ -84,6 +93,7 @@
#define X86_MSR_FSBASE 0xC0000100
#define X86_MSR_GSBASE 0xC0000101
#define X86_MSR_KERNEL_GSBASE 0xC0000102
#define X86_MSR_TSC_AUX 0xC0000103
/* Processor features in the EFER MSR */
#define X86_MSR_EFER_SCE (1 << 0)
@@ -91,6 +101,10 @@
#define X86_MSR_EFER_LMA (1 << 10)
#define X86_MSR_EFER_NXE (1 << 11)
#define X86_MSR_EFER_SVME (1 << 12)
#define X86_EFER_LMSLE (1 << 13)
#define X86_EFER_FFXSR (1 << 14)
#define X86_EFER_TCE (1 << 15)
#define X86_EFER_AUTOIBRS (1 << 21)
/* X86 EFLAG bit masks definitions */
#define X86_EFLAGS_NF_MASK 0x00000000 /* None */

View File

@@ -42,16 +42,6 @@
#define APIC_DF_FLAT 0xFFFFFFFF
#define APIC_DF_CLUSTER 0x0FFFFFFF
/* APIC delivery modes */
#define APIC_DM_FIXED 0x00000000
#define APIC_DM_LOWPRIO 0x00000100
#define APIC_DM_SMI 0x00000200
#define APIC_DM_REMOTE 0x00000300
#define APIC_DM_NMI 0x00000400
#define APIC_DM_INIT 0x00000500
#define APIC_DM_STARTUP 0x00000600
#define APIC_DM_EXTINT 0x00000700
/* APIC trigger modes */
#define APIC_TGM_EDGE 0
#define APIC_TGM_LEVEL 1
@@ -79,6 +69,35 @@
/* Initial stall factor */
#define INITIAL_STALL_FACTOR 100
/* APIC delivery mode enumeration list */
typedef enum _APIC_DM
{
APIC_DM_FIXED,
APIC_DM_LOWPRIO,
APIC_DM_SMI,
APIC_DM_REMOTE,
APIC_DM_NMI,
APIC_DM_INIT,
APIC_DM_STARTUP,
APIC_DM_EXTINT,
} APIC_DM, *PAPIC_DM;
/* APIC destination short-hand enumeration list */
typedef enum _APIC_DSH
{
APIC_DSH_Destination,
APIC_DSH_Self,
APIC_DSH_AllIncludingSelf,
APIC_DSH_AllExclusingSelf
} APIC_DSH, *PAPIC_DSH;
/* APIC mode list */
typedef enum _APIC_MODE
{
APIC_MODE_COMPAT,
APIC_MODE_X2APIC
} APIC_MODE, *PAPIC_MODE;
/* APIC Register Address Map */
typedef enum _APIC_REGISTER
{
@@ -116,35 +135,6 @@ typedef enum _APIC_REGISTER
APIC_EXT3LVTR = 0x53 /* Extended Interrupt 3 Local Vector Table */
} APIC_REGISTER, *PAPIC_REGISTER;
/* APIC mode list */
typedef enum _APIC_MODE
{
APIC_MODE_COMPAT,
APIC_MODE_X2APIC
} APIC_MODE, *PAPIC_MODE;
/* APIC destination short-hand enumeration list */
typedef enum _APIC_DSH
{
APIC_DSH_Destination,
APIC_DSH_Self,
APIC_DSH_AllIncludingSelf,
APIC_DSH_AllExclusingSelf
} APIC_DSH, *PAPIC_DSH;
/* APIC message type enumeration list */
typedef enum _APIC_MT
{
APIC_MT_Fixed,
APIC_MT_LowestPriority,
APIC_MT_SMI,
APIC_MT_RemoteRead,
APIC_MT_NMI,
APIC_MT_INIT,
APIC_MT_Startup,
APIC_MT_ExtInt,
} APIC_MT, *PAPIC_MT;
/* I8259 PIC interrupt mode enumeration list */
typedef enum _PIC_I8259_ICW1_INTERRUPT_MODE
{
@@ -217,7 +207,7 @@ typedef union _APIC_COMMAND_REGISTER
struct
{
ULONGLONG Vector:8;
ULONGLONG MessageType:3;
ULONGLONG DeliveryMode:3;
ULONGLONG DestinationMode:1;
ULONGLONG DeliveryStatus:1;
ULONGLONG ReservedMBZ:1;
@@ -237,7 +227,7 @@ typedef union _APIC_LVT_REGISTER
struct
{
ULONG Vector:8;
ULONG MessageType:3;
ULONG DeliveryMode:3;
ULONG Reserved1:1;
ULONG DeliveryStatus:1;
ULONG Reserved2:1;

View File

@@ -18,11 +18,18 @@
#define MM_PAGE_SHIFT 12L
#define MM_PAGE_SIZE 4096
/* Page directory and page base addresses */
#define MM_PTE_BASE 0xFFFFF68000000000UI64
#define MM_PDE_BASE 0xFFFFF6FB40000000UI64
#define MM_PPE_BASE 0xFFFFF6FB7DA00000UI64
#define MM_PXE_BASE 0xFFFFF6FB7DBED000UI64
/* Page directory and page base addresses for 4-level paging */
#define MM_PTE_BASE 0xFFFFF68000000000ULL
#define MM_PDE_BASE 0xFFFFF6FB40000000ULL
#define MM_PPE_BASE 0xFFFFF6FB7DA00000ULL
#define MM_PXE_BASE 0xFFFFF6FB7DBED000ULL
/* Page directory and page base addresses for 5-level paging */
#define MM_PTE_LA57_BASE 0xFFFF000000000000ULL
#define MM_PDE_LA57_BASE 0xFFFF010000000000ULL
#define MM_PPE_LA57_BASE 0xFFFF010800000000ULL
#define MM_PXE_LA57_BASE 0xFFFF010840000000ULL
#define MM_P5E_LA57_BASE 0xFFFF010840200000ULL
/* PTE shift values */
#define MM_PTE_SHIFT 3
@@ -30,7 +37,7 @@
#define MM_PDI_SHIFT 21
#define MM_PPI_SHIFT 30
#define MM_PXI_SHIFT 39
#define MM_LA57_SHIFT 48
#define MM_P5I_SHIFT 48
/* Number of PTEs per page */
#define MM_PTE_PER_PAGE 512
@@ -54,7 +61,10 @@
#define MM_HARDWARE_VA_START 0xFFFFFFFFFFC00000ULL
/* Maximum physical address used by HAL allocations */
#define MM_MAXIMUM_PHYSICAL_ADDRESS 0x00000000FFFFFFFF
#define MM_MAXIMUM_PHYSICAL_ADDRESS 0x00000000FFFFFFFFULL
/* Trampoline code address */
#define MM_TRAMPOLINE_ADDRESS 0x80000
/* Page size enumeration list */
typedef enum _PAGE_SIZE
@@ -85,6 +95,18 @@ typedef struct _HARDWARE_PTE
ULONGLONG NoExecute:1;
} HARDWARE_PTE, *PHARDWARE_PTE;
/* Page map information structure definition */
typedef struct _MMPAGEMAP_INFO
{
BOOLEAN Xpa;
ULONGLONG PteBase;
ULONGLONG PdeBase;
ULONGLONG PpeBase;
ULONGLONG PxeBase;
ULONGLONG P5eBase;
ULONG VaBits;
} MMPAGEMAP_INFO, *PMMPAGEMAP_INFO;
/* A Page Table Entry on AMD64 system */
typedef struct _MMPTE_HARDWARE
{

View File

@@ -13,9 +13,9 @@
/* Architecture-specific enumeration lists forward references */
typedef enum _APIC_DM APIC_DM, *PAPIC_DM;
typedef enum _APIC_DSH APIC_DSH, *PAPIC_DSH;
typedef enum _APIC_MODE APIC_MODE, *PAPIC_MODE;
typedef enum _APIC_MT APIC_MT, *PAPIC_MT;
typedef enum _APIC_REGISTER APIC_REGISTER, *PAPIC_REGISTER;
typedef enum _CPU_VENDOR CPU_VENDOR, *PCPU_VENDOR;
typedef enum _CPUID_FEATURES_EXTENDED CPUID_FEATURES_EXTENDED, *PCPUID_FEATURES_EXTENDED;
@@ -51,6 +51,7 @@ typedef struct _KSWITCH_FRAME KSWITCH_FRAME, *PKSWITCH_FRAME;
typedef struct _KTHREAD_INIT_FRAME KTHREAD_INIT_FRAME, *PKTHREAD_INIT_FRAME;
typedef struct _KTRAP_FRAME KTRAP_FRAME, *PKTRAP_FRAME;
typedef struct _KTSS KTSS, *PKTSS;
typedef struct _MMPAGEMAP_INFO MMPAGEMAP_INFO, *PMMPAGEMAP_INFO;
typedef struct _MMPFN MMPFN, *PMMPFN;
typedef struct _MMPTE_HARDWARE MMPTE_HARDWARE, *PMMPTE_HARDWARE;
typedef struct _MMPTE_HARDWARE_LARGEPAGE MMPTE_HARDWARE_LARGEPAGE, *PMMPTE_HARDWARE_LARGEPAGE;
@@ -66,6 +67,7 @@ typedef union _APIC_BASE_REGISTER APIC_BASE_REGISTER, *PAPIC_BASE_REGISTER;
typedef union _APIC_COMMAND_REGISTER APIC_COMMAND_REGISTER, *PAPIC_COMMAND_REGISTER;
typedef union _APIC_LVT_REGISTER APIC_LVT_REGISTER, *PAPIC_LVT_REGISTER;
typedef union _APIC_SPURIOUS_REGISTER APIC_SPURIOUS_REGISTER, *PAPIC_SPURIOUS_REGISTER;
typedef union _MMPTE MMP5E, *PMMP5E;
typedef union _MMPTE MMPDE, *PMMPDE;
typedef union _MMPTE MMPPE, *PMMPPE;
typedef union _MMPTE MMPTE, *PMMPTE;

View File

@@ -18,10 +18,11 @@
/* EFI XT boot devices */
#define XTBL_BOOT_DEVICE_UNKNOWN 0x00
#define XTBL_BOOT_DEVICE_CDROM 0x01
#define XTBL_BOOT_DEVICE_FLOPPY 0x02
#define XTBL_BOOT_DEVICE_HARDDISK 0x03
#define XTBL_BOOT_DEVICE_RAMDISK 0x04
#define XTBL_BOOT_DEVICE_ESP 0x01
#define XTBL_BOOT_DEVICE_CDROM 0x02
#define XTBL_BOOT_DEVICE_FLOPPY 0x04
#define XTBL_BOOT_DEVICE_HARDDISK 0x08
#define XTBL_BOOT_DEVICE_RAMDISK 0x10
/* XTLDR Debug Port type definitions */
#define XTBL_DEBUGPORT_SCREEN 1
@@ -43,28 +44,31 @@
typedef LONG (*PBL_GET_MEMTYPE_ROUTINE)(IN EFI_MEMORY_TYPE EfiMemoryType);
/* Boot Loader protocol routine pointers */
typedef EFI_STATUS (*PBL_ALLOCATE_PAGES)(IN ULONGLONG Size, OUT PEFI_PHYSICAL_ADDRESS Memory);
typedef EFI_STATUS (*PBL_ALLOCATE_PAGES)(IN EFI_ALLOCATE_TYPE AllocationType, IN ULONGLONG Size, OUT PEFI_PHYSICAL_ADDRESS Memory);
typedef EFI_STATUS (*PBL_ALLOCATE_POOL)(IN UINT_PTR Size, OUT PVOID *Memory);
typedef EFI_STATUS (*PBL_BOOTMENU_INITIALIZE_OS_LIST)(OUT PXTBL_BOOTMENU_ITEM *MenuEntries, OUT PULONG EntriesCount, OUT PULONG DefaultId);
typedef EFI_STATUS (*PBL_BOOTMENU_INITIALIZE_OS_LIST)(IN ULONG MaxNameLength, OUT PXTBL_BOOTMENU_ITEM *MenuEntries, OUT PULONG EntriesCount, OUT PULONG DefaultId);
typedef BOOLEAN (*PBL_BOOTUTIL_GET_BOOLEAN_PARAMETER)(IN CONST PWCHAR Parameters, IN CONST PWCHAR Needle);
typedef EFI_STATUS (*PBL_BUILD_PAGE_MAP)(IN PXTBL_PAGE_MAPPING PageMap, IN ULONG_PTR SelfMapAddress);
typedef EFI_STATUS (*PBL_CLOSE_VOLUME)(IN PEFI_HANDLE VolumeHandle);
typedef VOID (*PBL_CLEAR_CONSOLE_LINE)(IN ULONGLONG LineNo);
typedef EFI_STATUS (*PBL_CLOSE_XT_PROTOCOL)(IN PEFI_HANDLE Handle, IN PEFI_GUID ProtocolGuid);
typedef BOOLEAN (*PBL_CONFIG_GET_BOOLEAN_VALUE)(IN CONST PWCHAR ConfigName);
typedef PWCHAR (*PBL_CONFIG_GET_VALUE)(IN CONST PWCHAR ConfigName);
typedef EFI_STATUS (*PBL_CONFIG_GET_BOOT_OPTION_VALUE)(IN PLIST_ENTRY Options, IN CONST PWCHAR OptionName, OUT PWCHAR *OptionValue);
typedef VOID (*PBL_CONFIG_GET_EDITABLE_OPTIONS)(OUT CONST PWCHAR **OptionsArray, OUT PULONG OptionsCount);
typedef EFI_STATUS (*PBL_CONFIG_GET_VALUE)(IN CONST PWCHAR ConfigName, OUT PWCHAR *ConfigValue);
typedef EFI_STATUS (*PBL_CONFIG_SET_BOOT_OPTION_VALUE)(IN PLIST_ENTRY Options, IN CONST PWCHAR OptionName, IN CONST PWCHAR OptionValue);
typedef VOID (*PBL_CONSOLE_CLEAR_SCREEN)();
typedef VOID (*PBL_CONSOLE_DISABLE_CURSOR)();
typedef VOID (*PBL_CONSOLE_ENABLE_CURSOR)();
typedef VOID (*PBL_CONSOLE_PRINT)(IN PUSHORT Format, IN ...);
typedef VOID (*PBL_CONSOLE_PRINT)(IN PCWSTR Format, IN ...);
typedef VOID (*PBL_CONSOLE_QUERY_MODE)(OUT PUINT_PTR ResX, OUT PUINT_PTR ResY);
typedef VOID (*PBL_CONSOLE_READ_KEY_STROKE)(OUT PEFI_INPUT_KEY Key);
typedef VOID (*PBL_CONSOLE_RESET_INPUT_BUFFER)();
typedef VOID (*PBL_CONSOLE_SET_ATTRIBUTES)(IN ULONGLONG Attributes);
typedef VOID (*PBL_CONSOLE_SET_CURSOR_POSITION)(IN ULONGLONG PosX, IN ULONGLONG PosY);
typedef VOID (*PBL_CONSOLE_WRITE)(IN PUSHORT String);
typedef VOID (*PBL_CONSOLE_WRITE)(IN PCWSTR String);
typedef VOID (XTAPI *PBL_COPY_MEMORY)(OUT PVOID Destination, IN PCVOID Source, IN SIZE_T Length);
typedef VOID (*PBL_DEBUG_PRINT)(IN PUSHORT Format, IN ...);
typedef VOID (*PBL_DEBUG_PRINT)(IN PCWSTR Format, IN ...);
typedef EFI_STATUS (*PBL_ENTER_FIRMWARE_SETUP)();
typedef EFI_STATUS (*PBL_EXIT_BOOT_SERVICES)();
typedef EFI_STATUS (*PBL_FIND_BOOT_PROTOCOL)(IN PWCHAR SystemType, OUT PEFI_GUID BootProtocolGuid);
@@ -153,6 +157,7 @@ typedef struct _XTBL_BOOT_PARAMETERS
typedef struct _XTBL_BOOTMENU_ITEM
{
PWCHAR EntryName;
PWCHAR FullName;
PWCHAR ShortName;
PLIST_ENTRY Options;
} XTBL_BOOTMENU_ITEM, *PXTBL_BOOTMENU_ITEM;
@@ -361,7 +366,10 @@ typedef struct _XTBL_LOADER_PROTOCOL
struct
{
PBL_CONFIG_GET_BOOLEAN_VALUE GetBooleanValue;
PBL_CONFIG_GET_BOOT_OPTION_VALUE GetBootOptionValue;
PBL_CONFIG_GET_EDITABLE_OPTIONS GetEditableOptions;
PBL_CONFIG_GET_VALUE GetValue;
PBL_CONFIG_SET_BOOT_OPTION_VALUE SetBootOptionValue;
} Config;
struct
{

View File

@@ -366,8 +366,8 @@ typedef struct _CPPORT
UCHAR Ring;
} CPPORT, *PCPPORT;
/* HAL framebuffer data structure */
typedef struct _HAL_FRAMEBUFFER_DATA
/* Framebuffer data structure */
typedef struct _HL_FRAMEBUFFER_DATA
{
BOOLEAN Initialized;
PVOID Address;
@@ -375,7 +375,7 @@ typedef struct _HAL_FRAMEBUFFER_DATA
UINT Width;
UINT Height;
UINT PixelsPerScanLine;
UINT BitsPerPixel;
UINT BytesPerPixel;
UINT Pitch;
PVOID Font;
struct
@@ -389,7 +389,22 @@ typedef struct _HAL_FRAMEBUFFER_DATA
USHORT ReservedShift;
USHORT ReservedSize;
} Pixels;
} HAL_FRAMEBUFFER_DATA, *PHAL_FRAMEBUFFER_DATA;
} HL_FRAMEBUFFER_DATA, *PHL_FRAMEBUFFER_DATA;
/* Scroll region data structure */
typedef struct _HL_SCROLL_REGION_DATA
{
ULONG Left;
ULONG Top;
ULONG Right;
ULONG Bottom;
ULONG WidthInChars;
ULONG HeightInChars;
ULONG CursorX;
ULONG CursorY;
ULONG BackgroundColor;
ULONG TextColor;
} HL_SCROLL_REGION_DATA, *PHL_SCROLL_REGION_DATA;
/* Processor identity structure */
typedef struct _PROCESSOR_IDENTITY

View File

@@ -39,13 +39,22 @@
#define CR4_PCE 0x00000100
#define CR4_FXSR 0x00000200
#define CR4_XMMEXCPT 0x00000400
#define CR4_UMIP 0x00000800
#define CR4_LA57 0x00001000
#define CR4_RESERVED1 0x00001800
#define CR4_VMXE 0x00002000
#define CR4_SMXE 0x00004000
#define CR4_RESERVED2 0x00018000
#define CR4_XSAVE 0x00020000
#define CR4_RESERVED3 0xFFFC0000
#define CR4_FSGSBASE 0x00010000
#define CR4_PCIDE 0x00020000
#define CR4_XSAVE 0x00040000
#define CR4_KL 0x00080000
#define CR4_SMEP 0x00100000
#define CR4_SMAP 0x00200000
#define CR4_PKE 0x00400000
#define CR4_CET 0x00800000
#define CR4_PKS 0x01000000
#define CR4_UINTR 0x02000000
#define CR4_LASS 0x08000000
#define CR4_LAM_SUP 0x10000000
/* Descriptors size */
#define GDT_ENTRIES 128

View File

@@ -47,16 +47,6 @@
#define APIC_DF_FLAT 0xFFFFFFFF
#define APIC_DF_CLUSTER 0x0FFFFFFF
/* APIC delivery modes */
#define APIC_DM_FIXED 0x00000000
#define APIC_DM_LOWPRIO 0x00000100
#define APIC_DM_SMI 0x00000200
#define APIC_DM_REMOTE 0x00000300
#define APIC_DM_NMI 0x00000400
#define APIC_DM_INIT 0x00000500
#define APIC_DM_STARTUP 0x00000600
#define APIC_DM_EXTINT 0x00000700
/* APIC trigger modes */
#define APIC_TGM_EDGE 0
#define APIC_TGM_LEVEL 1
@@ -86,6 +76,35 @@
/* Initial stall factor */
#define INITIAL_STALL_FACTOR 100
/* APIC delivery mode enumeration list */
typedef enum _APIC_DM
{
APIC_DM_FIXED,
APIC_DM_LOWPRIO,
APIC_DM_SMI,
APIC_DM_REMOTE,
APIC_DM_NMI,
APIC_DM_INIT,
APIC_DM_STARTUP,
APIC_DM_EXTINT,
} APIC_DM, *PAPIC_DM;
/* APIC destination short-hand enumeration list */
typedef enum _APIC_DSH
{
APIC_DSH_Destination,
APIC_DSH_Self,
APIC_DSH_AllIncludingSelf,
APIC_DSH_AllExclusingSelf
} APIC_DSH, *PAPIC_DSH;
/* APIC mode list */
typedef enum _APIC_MODE
{
APIC_MODE_COMPAT,
APIC_MODE_X2APIC
} APIC_MODE, *PAPIC_MODE;
/* APIC Register Address Map */
typedef enum _APIC_REGISTER
{
@@ -123,35 +142,6 @@ typedef enum _APIC_REGISTER
APIC_EXT3LVTR = 0x53 /* Extended Interrupt 3 Local Vector Table */
} APIC_REGISTER, *PAPIC_REGISTER;
/* APIC mode list */
typedef enum _APIC_MODE
{
APIC_MODE_COMPAT,
APIC_MODE_X2APIC
} APIC_MODE, *PAPIC_MODE;
/* APIC destination short-hand enumeration list */
typedef enum _APIC_DSH
{
APIC_DSH_Destination,
APIC_DSH_Self,
APIC_DSH_AllIncludingSelf,
APIC_DSH_AllExclusingSelf
} APIC_DSH, *PAPIC_DSH;
/* APIC message type enumeration list */
typedef enum _APIC_MT
{
APIC_MT_Fixed,
APIC_MT_LowestPriority,
APIC_MT_SMI,
APIC_MT_RemoteRead,
APIC_MT_NMI,
APIC_MT_INIT,
APIC_MT_Startup,
APIC_MT_ExtInt,
} APIC_MT, *PAPIC_MT;
/* I8259 PIC interrupt mode enumeration list */
typedef enum _PIC_I8259_ICW1_INTERRUPT_MODE
{
@@ -224,7 +214,7 @@ typedef union _APIC_COMMAND_REGISTER
struct
{
ULONGLONG Vector:8;
ULONGLONG MessageType:3;
ULONGLONG DeliveryMode:3;
ULONGLONG DestinationMode:1;
ULONGLONG DeliveryStatus:1;
ULONGLONG ReservedMBZ:1;
@@ -244,7 +234,7 @@ typedef union _APIC_LVT_REGISTER
struct
{
ULONG Vector:8;
ULONG MessageType:3;
ULONG DeliveryMode:3;
ULONG Reserved1:1;
ULONG DeliveryStatus:1;
ULONG Reserved2:1;

View File

@@ -28,7 +28,11 @@
#define MM_PDI_SHIFT 21
#define MM_PPI_SHIFT 30
/* Page directory and page base legacy address */
#define MM_PDE_LEGACY_BASE 0xC0300000
/* PTE legacy shift values */
#define MM_PTE_LEGACY_SHIFT 2
#define MM_PDI_LEGACY_SHIFT 22
/* Minimum number of physical pages needed by the system */
@@ -49,6 +53,8 @@
/* Maximum physical address used by HAL allocations */
#define MM_MAXIMUM_PHYSICAL_ADDRESS 0xFFFFFFFF
/* Trampoline code address */
#define MM_TRAMPOLINE_ADDRESS 0x80000
/* Page size enumeration list */
typedef enum _PAGE_SIZE
@@ -58,8 +64,26 @@ typedef enum _PAGE_SIZE
Size4M
} PAGE_SIZE, *PPAGE_SIZE;
/* Page Table entry structure definition (with PAE support) */
typedef struct _HARDWARE_PTE
/* Legacy Page Table entry structure definition (PML2) */
typedef struct _HARDWARE_LEGACY_PTE
{
ULONG Valid:1;
ULONG Writable:1;
ULONG Owner:1;
ULONG WriteThrough:1;
ULONG CacheDisable:1;
ULONG Accessed:1;
ULONG Dirty:1;
ULONG LargePage:1;
ULONG Global:1;
ULONG CopyOnWrite:1;
ULONG Prototype:1;
ULONG Reserved0:1;
ULONG PageFrameNumber:20;
} HARDWARE_LEGACY_PTE, *PHARDWARE_LEGACY_PTE;
/* Page Table entry structure definition (PML3) */
typedef struct _HARDWARE_MODERN_PTE
{
ULONGLONG Valid:1;
ULONGLONG Writable:1;
@@ -77,10 +101,117 @@ typedef struct _HARDWARE_PTE
ULONGLONG Reserved1:14;
ULONGLONG SoftwareWsIndex:11;
ULONGLONG NoExecute:1;
} HARDWARE_MODERN_PTE, *PHARDWARE_MODERN_PTE;
/* Generic Page Table entry union to abstract PML2 and PML3 formats */
typedef union _HARDWARE_PTE
{
ULONGLONG Long;
HARDWARE_LEGACY_PTE Pml2;
HARDWARE_MODERN_PTE Pml3;
} HARDWARE_PTE, *PHARDWARE_PTE;
/* Page Table Entry on PAE enabled system */
typedef struct _MMPTE_HARDWARE
/* Page map information structure definition */
typedef struct _MMPAGEMAP_INFO
{
BOOLEAN Xpa;
ULONG PteBase;
ULONG PdeBase;
ULONG PdiShift;
ULONG PteShift;
} MMPAGEMAP_INFO, *PMMPAGEMAP_INFO;
/* Legacy Page Table Entry hardware structure definition (PML2) */
typedef struct _MMPML2_PTE_HARDWARE
{
ULONG Valid:1;
ULONG Writable:1;
ULONG Owner:1;
ULONG WriteThrough:1;
ULONG CacheDisable:1;
ULONG Accessed:1;
ULONG Dirty:1;
ULONG LargePage:1;
ULONG Global:1;
ULONG CopyOnWrite:1;
ULONG Prototype:1;
ULONG Write:1;
ULONG PageFrameNumber:20;
} MMPML2_PTE_HARDWARE, *PMMPML2_PTE_HARDWARE;
/* Legacy Page Table Entry list structure definition (PML2) */
typedef struct _MMPML2_PTE_LIST
{
ULONG Valid:1;
ULONG OneEntry:1;
ULONG Reserved0:8;
ULONG Prototype:1;
ULONG Reserved1:1;
ULONG NextEntry:20;
} MMPML2_PTE_LIST, *PMMPML2_PTE_LIST;
/* Legacy Page Table Entry subsection structure definition (PML2) */
typedef struct _MMPML2_PTE_PROTOTYPE
{
ULONG Valid:1;
ULONG ProtoAddressLow:7;
ULONG ReadOnly:1;
ULONG WhichPool:1;
ULONG Prototype:1;
ULONG ProtoAddressHigh:21;
} MMPML2_PTE_PROTOTYPE, *PMMPML2_PTE_PROTOTYPE;
/* Legacy Page Table Entry software structure definition (PML2) */
typedef struct _MMPML2_PTE_SOFTWARE
{
ULONG Valid:1;
ULONG PageFileLow:4;
ULONG Protection:5;
ULONG Prototype:1;
ULONG Transition:1;
ULONG PageFileHigh:20;
} MMPML2_PTE_SOFTWARE, *PMMPML2_PTE_SOFTWARE;
/* Legacy Page Table Entry subsection structure definition (PML2) */
typedef struct _MMPML2_PTE_SUBSECTION
{
ULONG Valid:1;
ULONG SubsectionAddressLow:4;
ULONG Protection:5;
ULONG Prototype:1;
ULONG SubsectionAddressHigh:20;
ULONG WhichPool:1;
} MMPML2_PTE_SUBSECTION, *PMMPML2_PTE_SUBSECTION;
/* Legacy Page Table Entry transition structure definition (PML2) */
typedef struct _MMPML2_PTE_TRANSITION
{
ULONG Valid:1;
ULONG Write:1;
ULONG Owner:1;
ULONG WriteThrough:1;
ULONG CacheDisable:1;
ULONG Protection:5;
ULONG Prototype:1;
ULONG Transition:1;
ULONG PageFrameNumber:20;
} MMPML2_PTE_TRANSITION, *PMMPML2_PTE_TRANSITION;
/* Legacy Page Table Entry union definition (PML2) */
typedef union _MMPML2_PTE
{
ULONG Long;
HARDWARE_PTE Flush;
MMPML2_PTE_HARDWARE Hard;
MMPML2_PTE_PROTOTYPE Proto;
MMPML2_PTE_SOFTWARE Soft;
MMPML2_PTE_TRANSITION Trans;
MMPML2_PTE_SUBSECTION Subsect;
MMPML2_PTE_LIST List;
} MMPML2_PTE, *PMMPML2_PTE;
/* Page Table Entry hardware structure definition (PML3) */
typedef struct _MMPML3_PTE_HARDWARE
{
ULONGLONG Valid:1;
ULONGLONG Writable:1;
@@ -95,59 +226,59 @@ typedef struct _MMPTE_HARDWARE
ULONGLONG Prototype:1;
ULONGLONG Write:1;
ULONGLONG PageFrameNumber:26;
ULONGLONG Reserved1:25;
ULONGLONG Reserved0:25;
ULONGLONG NoExecute:1;
} MMPTE_HARDWARE, *PMMPTE_HARDWARE;
} MMPML3_PTE_HARDWARE, *PMMPML3_PTE_HARDWARE;
/* Page Table Entry list structure definition (with PAE support) */
typedef struct _MMPTE_LIST
/* Page Table Entry list structure definition (PML3) */
typedef struct _MMPML3_PTE_LIST
{
ULONGLONG Valid:1;
ULONGLONG OneEntry:1;
ULONGLONG Reserved1:8;
ULONGLONG Reserved0:8;
ULONGLONG Prototype:1;
ULONGLONG Reserved2:21;
ULONGLONG Reserved1:21;
ULONGLONG NextEntry:32;
} MMPTE_LIST, *PMMPTE_LIST;
} MMPML3_PTE_LIST, *PMMPML3_PTE_LIST;
/* Page Table Entry subsection structure definition (with PAE support) */
typedef struct _MMPTE_PROTOTYPE
/* Page Table Entry subsection structure definition (PML3) */
typedef struct _MMPML3_PTE_PROTOTYPE
{
ULONGLONG Valid:1;
ULONGLONG Reserved1:7;
ULONGLONG Reserved0:7;
ULONGLONG ReadOnly:1;
ULONGLONG Reserved2:1;
ULONGLONG Reserved1:1;
ULONGLONG Prototype:1;
ULONGLONG Protection:5;
ULONGLONG Reserved3:16;
ULONGLONG Reserved2:16;
ULONGLONG ProtoAddress:32;
} MMPTE_PROTOTYPE, *PMMPTE_PROTOTYPE;
} MMPML3_PTE_PROTOTYPE, *PMMPML3_PTE_PROTOTYPE;
/* Page Table Entry software structure definition (with PAE support) */
typedef struct _MMPTE_SOFTWARE
/* Page Table Entry software structure definition (PML3) */
typedef struct _MMPML3_PTE_SOFTWARE
{
ULONGLONG Valid:1;
ULONGLONG PageFileLow:4;
ULONGLONG Protection:5;
ULONGLONG Prototype:1;
ULONGLONG Transition:1;
ULONGLONG Reserved1:20;
ULONGLONG Reserved0:20;
ULONGLONG PageFileHigh:32;
} MMPTE_SOFTWARE, *PMMPTE_SOFTWARE;
} MMPML3_PTE_SOFTWARE, *PMMPML3_PTE_SOFTWARE;
/* Page Table Entry subsection structure definition (with PAE support) */
typedef struct _MMPTE_SUBSECTION
/* Page Table Entry subsection structure definition (PML3) */
typedef struct _MMPML3_PTE_SUBSECTION
{
ULONGLONG Valid:1;
ULONGLONG Reserved1:4;
ULONGLONG Reserved0:4;
ULONGLONG Protection:5;
ULONGLONG Prototype:1;
ULONGLONG Reserved2:21;
ULONGLONG Reserved1:21;
ULONGLONG SubsectionAddress:32;
} MMPTE_SUBSECTION, *PMMPTE_SUBSECTION;
} MMPML3_PTE_SUBSECTION, *PMMPML3_PTE_SUBSECTION;
/* Page Table Entry transition structure definition (with PAE support) */
typedef struct _MMPTE_TRANSITION
/* Page Table Entry transition structure definition (PML3) */
typedef struct _MMPML3_PTE_TRANSITION
{
ULONGLONG Valid:1;
ULONGLONG Write:1;
@@ -159,38 +290,28 @@ typedef struct _MMPTE_TRANSITION
ULONGLONG Transition:1;
ULONGLONG PageFrameNumber:26;
ULONGLONG Unused:26;
} MMPTE_TRANSITION, *PMMPTE_TRANSITION;
} MMPML3_PTE_TRANSITION, *PMMPML3_PTE_TRANSITION;
/* Page Table Entry structure definition (with PAE support) */
typedef union _MMPTE
/* Page Table Entry union definition (PML3) */
typedef union _MMPML3_PTE
{
ULONGLONG Long;
HARDWARE_PTE Flush;
MMPTE_HARDWARE Hardware;
MMPTE_PROTOTYPE Prototype;
MMPTE_SOFTWARE Software;
MMPTE_TRANSITION Transition;
MMPTE_SUBSECTION Subsection;
MMPTE_LIST List;
} MMPTE, *PMMPTE;
MMPML3_PTE_HARDWARE Hardware;
MMPML3_PTE_PROTOTYPE Prototype;
MMPML3_PTE_SOFTWARE Software;
MMPML3_PTE_TRANSITION Transition;
MMPML3_PTE_SUBSECTION Subsection;
MMPML3_PTE_LIST List;
} MMPML3_PTE, *PMMPML3_PTE;
/* Legacy Page Table entry structure definition (without PAE support) */
typedef struct _HARDWARE_LEGACY_PTE
/* Generic Page Table Entry union to abstract PML2 and PML3 formats */
typedef union _MMPTE
{
ULONG Valid:1;
ULONG Writable:1;
ULONG Owner:1;
ULONG WriteThrough:1;
ULONG CacheDisable:1;
ULONG Accessed:1;
ULONG Dirty:1;
ULONG LargePage:1;
ULONG Global:1;
ULONG CopyOnWrite:1;
ULONG Prototype:1;
ULONG Reserved0:1;
ULONG PageFrameNumber:20;
} HARDWARE_LEGACY_PTE, *PHARDWARE_LEGACY_PTE;
ULONGLONG Long;
MMPML2_PTE Pml2;
MMPML3_PTE Pml3;
} MMPTE, *PMMPTE;
/* Page Frame Number structure definition */
typedef struct _MMPFN

View File

@@ -13,9 +13,9 @@
/* Architecture-specific enumeration lists forward references */
typedef enum _APIC_DM APIC_DM, *PAPIC_DM;
typedef enum _APIC_DSH APIC_DSH, *PAPIC_DSH;
typedef enum _APIC_MODE APIC_MODE, *PAPIC_MODE;
typedef enum _APIC_MT APIC_MT, *PAPIC_MT;
typedef enum _APIC_REGISTER APIC_REGISTER, *PAPIC_REGISTER;
typedef enum _CPU_VENDOR CPU_VENDOR, *PCPU_VENDOR;
typedef enum _CPUID_FEATURES_EXTENDED CPUID_FEATURES_EXTENDED, *PCPUID_FEATURES_EXTENDED;
@@ -40,7 +40,7 @@ typedef struct _FN_SAVE_FORMAT FN_SAVE_FORMAT, *PFN_SAVE_FORMAT;
typedef struct _FX_SAVE_AREA FX_SAVE_AREA, *PFX_SAVE_AREA;
typedef struct _FX_SAVE_FORMAT FX_SAVE_FORMAT, *PFX_SAVE_FORMAT;
typedef struct _HARDWARE_LEGACY_PTE HARDWARE_LEGACY_PTE, *PHARDWARE_LEGACY_PTE;
typedef struct _HARDWARE_PTE HARDWARE_PTE, *PHARDWARE_PTE;
typedef struct _HARDWARE_MODERN_PTE HARDWARE_MODERN_PTE, *PHARDWARE_MODERN_PTE;
typedef struct _KDESCRIPTOR KDESCRIPTOR, *PKDESCRIPTOR;
typedef struct _KEXCEPTION_FRAME KEXCEPTION_FRAME, *PKEXCEPTION_FRAME;
typedef struct _KGDTENTRY KGDTENTRY, *PKGDTENTRY;
@@ -55,13 +55,20 @@ typedef struct _KSWITCH_FRAME KSWITCH_FRAME, *PKSWITCH_FRAME;
typedef struct _KTHREAD_INIT_FRAME KTHREAD_INIT_FRAME, *PKTHREAD_INIT_FRAME;
typedef struct _KTRAP_FRAME KTRAP_FRAME, *PKTRAP_FRAME;
typedef struct _KTSS KTSS, *PKTSS;
typedef struct _MMPAGEMAP_INFO MMPAGEMAP_INFO, *PMMPAGEMAP_INFO;
typedef struct _MMPFN MMPFN, *PMMPFN;
typedef struct _MMPTE_HARDWARE MMPTE_HARDWARE, *PMMPTE_HARDWARE;
typedef struct _MMPTE_LIST MMPTE_LIST, *PMMPTE_LIST;
typedef struct _MMPTE_PROTOTYPE MMPTE_PROTOTYPE, *PMMPTE_PROTOTYPE;
typedef struct _MMPTE_SOFTWARE MMPTE_SOFTWARE, *PMMPTE_SOFTWARE;
typedef struct _MMPTE_SUBSECTION MMPTE_SUBSECTION, *PMMPTE_SUBSECTION;
typedef struct _MMPTE_TRANSITION MMPTE_TRANSITION, *PMMPTE_TRANSITION;
typedef struct _MMPML2_PTE_HARDWARE MMPML2_PTE_HARDWARE, *PMMPML2_PTE_HARDWARE;
typedef struct _MMPML2_PTE_LIST MMPML2_PTE_LIST, *PMMPML2_PTE_LIST;
typedef struct _MMPML2_PTE_PROTOTYPE MMPML2_PTE_PROTOTYPE, *PMMPML2_PTE_PROTOTYPE;
typedef struct _MMPML2_PTE_SOFTWARE MMPML2_PTE_SOFTWARE, *PMMPML2_PTE_SOFTWARE;
typedef struct _MMPML2_PTE_SUBSECTION MMPML2_PTE_SUBSECTION, *PMMPML2_PTE_SUBSECTION;
typedef struct _MMPML2_PTE_TRANSITION MMPML2_PTE_TRANSITION, *PMMPML2_PTE_TRANSITION;
typedef struct _MMPML3_PTE_HARDWARE MMPML3_PTE_HARDWARE, *PMMPML3_PTE_HARDWARE;
typedef struct _MMPML3_PTE_LIST MMPML3_PTE_LIST, *PMMPML3_PTE_LIST;
typedef struct _MMPML3_PTE_PROTOTYPE MMPML3_PTE_PROTOTYPE, *PMMPML3_PTE_PROTOTYPE;
typedef struct _MMPML3_PTE_SOFTWARE MMPML3_PTE_SOFTWARE, *PMMPML3_PTE_SOFTWARE;
typedef struct _MMPML3_PTE_SUBSECTION MMPML3_PTE_SUBSECTION, *PMMPML3_PTE_SUBSECTION;
typedef struct _MMPML3_PTE_TRANSITION MMPML3_PTE_TRANSITION, *PMMPML3_PTE_TRANSITION;
typedef struct _THREAD_ENVIRONMENT_BLOCK THREAD_ENVIRONMENT_BLOCK, *PTHREAD_ENVIRONMENT_BLOCK;
/* Unions forward references */
@@ -69,12 +76,15 @@ typedef union _APIC_BASE_REGISTER APIC_BASE_REGISTER, *PAPIC_BASE_REGISTER;
typedef union _APIC_COMMAND_REGISTER APIC_COMMAND_REGISTER, *PAPIC_COMMAND_REGISTER;
typedef union _APIC_LVT_REGISTER APIC_LVT_REGISTER, *PAPIC_LVT_REGISTER;
typedef union _APIC_SPURIOUS_REGISTER APIC_SPURIOUS_REGISTER, *PAPIC_SPURIOUS_REGISTER;
typedef union _HARDWARE_PTE HARDWARE_PTE, *PHARDWARE_PTE;
typedef union _MMPML2_PTE MMPML2_PTE, *PMMPML2_PTE;
typedef union _MMPML3_PTE MMPML3_PTE, *PMMPML3_PTE;
typedef union _MMPTE MMPDE, *PMMPDE;
typedef union _MMPTE MMPPE, *PMMPPE;
typedef union _MMPTE MMPTE, *PMMPTE;
typedef union _PIC_I8259_ICW1 PIC_I8259_ICW1, *PPIC_I8259_ICW1;
typedef union _PIC_I8259_ICW2 PIC_I8259_ICW2, *PPIC_I8259_ICW2;
typedef union _PIC_I8259_ICW3 PIC_I8259_ICW3, *PPIC_I8259_ICW3;
typedef union _PIC_I8259_ICW4 PIC_I8259_ICW4, *PPIC_I8259_ICW4;
#endif /* __XTDK_I686_XTSTRUCT_H */

45
sdk/xtdk/kdtypes.h Normal file
View File

@@ -0,0 +1,45 @@
/**
* PROJECT: ExectOS
* COPYRIGHT: See COPYING.md in the top level directory
* FILE: sdk/xtdk/kdtypes.h
* DESCRIPTION: Kernel Debugger data structures
* DEVELOPERS: Aiken Harris <harraiken91@gmail.com>
*/
#ifndef __XTDK_KDTYPES_H
#define __XTDK_KDTYPES_H
#include <xtbase.h>
#include <xtstruct.h>
#include <rtltypes.h>
/* Number of debug providers */
#define KDBG_PROVIDERS_COUNT 2
/* Debug providers bitmask definitions */
#define DEBUG_PROVIDER_COMPORT 0x00000001
#define DEBUG_PROVIDER_FRAMEBUFFER 0x00000002
/* Kernel routine callbacks */
typedef XTSTATUS (XTAPI *PKD_INIT_ROUTINE)();
typedef VOID (*PKD_PRINT_ROUTINE)(IN PCWSTR Format, IN ...);
/* Debug mode structure definition */
typedef struct _KD_DEBUG_MODE
{
BOOLEAN Enabled;
ULONG Mode;
ULONG ComPortAddress;
ULONG ComPortNumber;
ULONG ComPortBaudRate;
} KD_DEBUG_MODE, *PKD_DEBUG_MODE;
/* Kernel debugger dispatch table structure definition */
typedef struct _KD_DISPATCH_TABLE
{
LIST_ENTRY ListEntry;
RTL_PRINT_CONTEXT PrintContext;
} KD_DISPATCH_TABLE, *PKD_DISPATCH_TABLE;
#endif /* __XTDK_KDTYPES_H */

View File

@@ -10,8 +10,18 @@
#define __XTDK_MMTYPES_H
#include <xtbase.h>
#include ARCH_HEADER(xtstruct.h)
/* Page map routines structure definition */
typedef CONST STRUCT _CMMPAGEMAP_ROUTINES
{
VOID (XTAPI *ClearPte)(PHARDWARE_PTE PtePointer);
BOOLEAN (XTAPI *PteValid)(PHARDWARE_PTE PtePointer);
VOID (XTAPI *SetPteCaching)(PHARDWARE_PTE PtePointer, BOOLEAN CacheDisable, BOOLEAN WriteThrough);
VOID (XTAPI *SetPte)(PHARDWARE_PTE PtePointer, PFN_NUMBER PageFrameNumber, BOOLEAN Writable);
} CMMPAGEMAP_ROUTINES, *PCMMPAGEMAP_ROUTINES;
/* Color tables structure definition */
typedef struct _MMCOLOR_TABLES
{

View File

@@ -83,26 +83,26 @@ RtlCompareMemory(IN PCVOID LeftBuffer,
XTAPI
SIZE_T
RtlCompareString(IN CONST PCHAR String1,
IN CONST PCHAR String2,
RtlCompareString(IN PCSTR String1,
IN PCSTR String2,
IN SIZE_T Length);
XTAPI
SIZE_T
RtlCompareStringInsensitive(IN CONST PCHAR String1,
IN CONST PCHAR String2,
RtlCompareStringInsensitive(IN PCSTR String1,
IN PCSTR String2,
IN SIZE_T Length);
XTAPI
SIZE_T
RtlCompareWideString(IN CONST PWCHAR String1,
IN CONST PWCHAR String2,
RtlCompareWideString(IN PCWSTR String1,
IN PCWSTR String2,
IN SIZE_T Length);
XTAPI
SIZE_T
RtlCompareWideStringInsensitive(IN CONST PWCHAR String1,
IN CONST PWCHAR String2,
RtlCompareWideStringInsensitive(IN PCWSTR String1,
IN PCWSTR String2,
IN SIZE_T Length);
XTAPI
@@ -134,13 +134,13 @@ RtlCopyMemory(OUT PVOID Destination,
XTAPI
VOID
RtlCopyString(IN PCHAR Destination,
IN PCCHAR Source,
IN PCSTR Source,
IN ULONG Length);
XTAPI
VOID
RtlCopyWideString(IN PWCHAR Destination,
IN CONST PWCHAR Source,
IN PCWSTR Source,
IN ULONG Length);
XTAPI
@@ -161,6 +161,26 @@ RtlFindSetBits(IN PRTL_BITMAP BitMap,
IN ULONG_PTR Length,
IN ULONG_PTR Index);
XTAPI
PCSTR
RtlFindString(IN PCSTR Source,
IN PCSTR Search);
XTAPI
PCSTR
RtlFindStringInsensitive(IN PCSTR Source,
IN PCSTR Search);
XTAPI
PCWSTR
RtlFindWideString(IN PCWSTR Source,
IN PCWSTR Search);
XTAPI
PCWSTR
RtlFindWideStringInsensitive(IN PCWSTR Source,
IN PCWSTR Search);
XTAPI
XTSTATUS
RtlFormatWideString(IN PRTL_PRINT_CONTEXT Context,
@@ -229,13 +249,13 @@ RtlSetMemory(OUT PVOID Destination,
XTAPI
SIZE_T
RtlStringLength(IN CONST PCHAR String,
RtlStringLength(IN PCSTR String,
IN SIZE_T MaxLength);
XTAPI
SIZE_T
RtlStringToWideString(OUT PWCHAR Destination,
IN CONST PCHAR *Source,
IN PCSTR *Source,
IN SIZE_T Length);
XTAPI
@@ -246,42 +266,58 @@ RtlTestBit(IN PRTL_BITMAP BitMap,
XTAPI
PCHAR
RtlTokenizeString(IN PCHAR String,
IN CONST PCHAR Delimiter,
IN PCSTR Delimiter,
IN OUT PCHAR *SavePtr);
XTAPI
PWCHAR
RtlTokenizeWideString(IN PWCHAR String,
IN CONST PWCHAR Delimiter,
IN PCWSTR Delimiter,
IN OUT PWCHAR *SavePtr);
XTAPI
PCHAR
RtlTrimLeftString(IN CONST PCHAR String);
CHAR
RtlToLowerCharacter(IN CHAR Character);
XTAPI
PWCHAR
RtlTrimLeftWideString(IN CONST PWCHAR String);
WCHAR
RtlToLowerWideCharacter(IN WCHAR Character);
XTAPI
CHAR
RtlToUpperCharacter(IN CHAR Character);
XTAPI
WCHAR
RtlToUpperWideCharacter(IN WCHAR Character);
XTAPI
PCHAR
RtlTrimRightString(IN CONST PCHAR String);
RtlTrimLeftString(IN PCHAR String);
XTAPI
PWCHAR
RtlTrimRightWideString(IN CONST PWCHAR String);
RtlTrimLeftWideString(IN PWCHAR String);
XTAPI
PCHAR
RtlTrimString(IN CONST PCHAR String);
RtlTrimRightString(IN PCHAR String);
XTAPI
PWCHAR
RtlTrimWideString(IN CONST PWCHAR String);
RtlTrimRightWideString(IN PWCHAR String);
XTAPI
PCHAR
RtlTrimString(IN PCHAR String);
XTAPI
PWCHAR
RtlTrimWideString(IN PWCHAR String);
XTAPI
SIZE_T
RtlWideStringLength(IN CONST PWCHAR String,
RtlWideStringLength(IN PCWSTR String,
IN SIZE_T MaxLength);
XTAPI

View File

@@ -20,7 +20,7 @@
/* XTOS platform debugging macros */
#ifdef DBG
#define DEBUG 1
#define DebugPrint(Format, ...) if(KeDbgPrint) KeDbgPrint(Format, __VA_ARGS__);
#define DebugPrint(Format, ...) if(KdPrint) KdPrint(Format, __VA_ARGS__);
#else
#define DEBUG 0
#define DebugPrint(Format, ...) ((VOID)NULL)

View File

@@ -89,7 +89,6 @@ typedef struct _FIRMWARE_INFORMATION_BLOCK
typedef struct _LOADER_INFORMATION_BLOCK
{
PVOID DbgPrint;
ULONG PageMapLevel;
} LOADER_INFORMATION_BLOCK, *PLOADER_INFORMATION_BLOCK;
/* Boot Loader memory mapping information */

View File

@@ -30,6 +30,7 @@
#include <extypes.h>
#include <hltypes.h>
#include <iotypes.h>
#include <kdtypes.h>
#include <ketypes.h>
#include <ldrtypes.h>
#include <mmtypes.h>

View File

@@ -59,6 +59,7 @@
#define STATUS_INVALID_PARAMETER ((XTSTATUS) 0xC000000DL)
#define STATUS_END_OF_FILE ((XTSTATUS) 0xC0000011L)
#define STATUS_NO_MEMORY ((XTSTATUS) 0xC0000017L)
#define STATUS_PORT_DISCONNECTED ((XTSTATUS) 0xC0000037L)
#define STATUS_CRC_ERROR ((XTSTATUS) 0xC000003FL)
#define STATUS_INSUFFICIENT_RESOURCES ((XTSTATUS) 0xC000009AL)
#define STATUS_DEVICE_NOT_READY ((XTSTATUS) 0xC00000A3L)

View File

@@ -50,6 +50,7 @@ typedef enum _KTIMER_TYPE KTIMER_TYPE, *PKTIMER_TYPE;
typedef enum _KUBSAN_DATA_TYPE KUBSAN_DATA_TYPE, *PKUBSAN_DATA_TYPE;
typedef enum _LOADER_MEMORY_TYPE LOADER_MEMORY_TYPE, *PLOADER_MEMORY_TYPE;
typedef enum _MODE MODE, *PMODE;
typedef enum _RTL_VARIABLE_TYPE RTL_VARIABLE_TYPE, *PRTL_VARIABLE_TYPE;
typedef enum _SYSTEM_FIRMWARE_TYPE SYSTEM_FIRMWARE_TYPE, *PSYSTEM_FIRMWARE_TYPE;
typedef enum _WAIT_TYPE WAIT_TYPE, *PWAIT_TYPE;
@@ -69,6 +70,7 @@ typedef struct _ANSI_STRING ANSI_STRING, *PANSI_STRING;
typedef struct _ANSI_STRING32 ANSI_STRING32, *PANSI_STRING32;
typedef struct _ANSI_STRING64 ANSI_STRING64, *PANSI_STRING64;
typedef struct _CPPORT CPPORT, *PCPPORT;
typedef const struct _CMMPAGEMAP_ROUTINES CMMPAGEMAP_ROUTINES, *PCMMPAGEMAP_ROUTINES;
typedef struct _CSTRING CSTRING, *PCSTRING;
typedef struct _EFI_1394_DEVICE_PATH EFI_1394_DEVICE_PATH, *PEFI_1394_DEVICE_PATH;
typedef struct _EFI_ACPI_ADDRESS_SPACE_DESCRIPTOR EFI_ACPI_ADDRESS_SPACE_DESCRIPTOR, *PEFI_ACPI_ADDRESS_SPACE_DESCRIPTOR;
@@ -233,9 +235,12 @@ typedef struct _FIRMWARE_INFORMATION_BLOCK FIRMWARE_INFORMATION_BLOCK, *PFIRMWAR
typedef struct _FLOAT128 FLOAT128, *PFLOAT128;
typedef struct _GENERIC_ADDRESS GENERIC_ADDRESS, *PGENERIC_ADDRESS;
typedef struct _GUID GUID, *PGUID;
typedef struct _HAL_FRAMEBUFFER_DATA HAL_FRAMEBUFFER_DATA, *PHAL_FRAMEBUFFER_DATA;
typedef struct _HL_FRAMEBUFFER_DATA HL_FRAMEBUFFER_DATA, *PHL_FRAMEBUFFER_DATA;
typedef struct _HL_SCROLL_REGION_DATA HL_SCROLL_REGION_DATA, *PHL_SCROLL_REGION_DATA;
typedef struct _KAPC KAPC, *PKAPC;
typedef struct _KAPC_STATE KAPC_STATE, *PKAPC_STATE;
typedef struct _KD_DEBUG_MODE KD_DEBUG_MODE, *PKD_DEBUG_MODE;
typedef struct _KD_DISPATCH_TABLE KD_DISPATCH_TABLE, *PKD_DISPATCH_TABLE;
typedef struct _KDPC KDPC, *PKDPC;
typedef struct _KDPC_DATA KDPC_DATA, *PKDPC_DATA;
typedef struct _KERNEL_INITIALIZATION_BLOCK KERNEL_INITIALIZATION_BLOCK, *PKERNEL_INITIALIZATION_BLOCK;
@@ -300,6 +305,9 @@ typedef struct _PECOFF_IMAGE_SECTION_HEADER PECOFF_IMAGE_SECTION_HEADER, *PPECOF
typedef struct _PECOFF_IMAGE_VXD_HEADER PECOFF_IMAGE_VXD_HEADER, *PPECOFF_IMAGE_VXD_HEADER;
typedef struct _PROCESSOR_IDENTITY PROCESSOR_IDENTITY, *PPROCESSOR_IDENTITY;
typedef struct _PROCESSOR_POWER_STATE PROCESSOR_POWER_STATE, *PPROCESSOR_POWER_STATE;
typedef struct _RTL_BITMAP RTL_BITMAP, *PRTL_BITMAP;
typedef struct _RTL_PRINT_CONTEXT RTL_PRINT_CONTEXT, *PRTL_PRINT_CONTEXT;
typedef struct _RTL_PRINT_FORMAT_PROPERTIES RTL_PRINT_FORMAT_PROPERTIES, *PRTL_PRINT_FORMAT_PROPERTIES;
typedef struct _SINGLE_LIST_ENTRY SINGLE_LIST_ENTRY, *PSINGLE_LIST_ENTRY;
typedef struct _SMBIOS_TABLE_HEADER SMBIOS_TABLE_HEADER, *PSMBIOS_TABLE_HEADER;
typedef struct _SMBIOS3_TABLE_HEADER SMBIOS3_TABLE_HEADER, *PSMBIOS3_TABLE_HEADER;

View File

@@ -35,7 +35,7 @@ BlBuildPageMap(IN PXTBL_PAGE_MAPPING PageMap,
EFI_STATUS Status;
/* Allocate pages for the Page Map */
Status = BlAllocateMemoryPages(1, &Address);
Status = BlAllocateMemoryPages(AllocateAnyPages, 1, &Address);
if(Status != STATUS_EFI_SUCCESS)
{
/* Memory allocation failure */
@@ -54,6 +54,15 @@ BlBuildPageMap(IN PXTBL_PAGE_MAPPING PageMap,
return Status;
}
/* Map the trampoline code area */
Status = BlMapVirtualMemory(PageMap, (PVOID)MM_TRAMPOLINE_ADDRESS,(PVOID)MM_TRAMPOLINE_ADDRESS,
1, LoaderFirmwareTemporary);
if(Status != STATUS_EFI_SUCCESS)
{
/* Mapping trampoline code failed */
return Status;
}
/* Get list of XTLDR modules */
ModulesList = BlGetModulesList();
ModulesListEntry = ModulesList->Flink;
@@ -167,7 +176,7 @@ BlMapPage(IN PXTBL_PAGE_MAPPING PageMap,
while(NumberOfPages > 0)
{
/* Calculate the indices in the various Page Tables from the virtual address */
Pml5Entry = (VirtualAddress & ((ULONGLONG)0x1FF << MM_LA57_SHIFT)) >> MM_LA57_SHIFT;
Pml5Entry = (VirtualAddress & ((ULONGLONG)0x1FF << MM_P5I_SHIFT)) >> MM_P5I_SHIFT;
Pml4Entry = (VirtualAddress & ((ULONGLONG)0x1FF << MM_PXI_SHIFT)) >> MM_PXI_SHIFT;
Pml3Entry = (VirtualAddress & ((ULONGLONG)0x1FF << MM_PPI_SHIFT)) >> MM_PPI_SHIFT;
Pml2Entry = (VirtualAddress & ((ULONGLONG)0x1FF << MM_PDI_SHIFT)) >> MM_PDI_SHIFT;
@@ -279,7 +288,7 @@ BlpGetNextPageTable(IN PXTBL_PAGE_MAPPING PageMap,
else
{
/* Allocate pages for new PML entry */
Status = BlAllocateMemoryPages(1, &Address);
Status = BlAllocateMemoryPages(AllocateAnyPages, 1, &Address);
if(Status != STATUS_EFI_SUCCESS)
{
/* Memory allocation failure */
@@ -338,22 +347,21 @@ BlpSelfMapPml(IN PXTBL_PAGE_MAPPING PageMap,
/* Check page map level */
if(PageMap->PageMapLevel == 5)
{
/* Self-mapping for PML5 is not supported */
BlDebugPrint(L"PML5 self-mapping not supported yet!\n");
return STATUS_EFI_UNSUPPORTED;
/* Calculate PML index based on provided self map address for PML5 */
PmlIndex = (SelfMapAddress >> MM_P5I_SHIFT) & 0x1FF;
}
else
{
/* Calculate PML index based on provided self map address */
/* Calculate PML index based on provided self map address for PML4 */
PmlIndex = (SelfMapAddress >> MM_PXI_SHIFT) & 0x1FF;
/* Add self-mapping for PML4 */
RtlZeroMemory(&PmlBase[PmlIndex], sizeof(HARDWARE_PTE));
PmlBase[PmlIndex].PageFrameNumber = (UINT_PTR)PageMap->PtePointer / EFI_PAGE_SIZE;
PmlBase[PmlIndex].Valid = 1;
PmlBase[PmlIndex].Writable = 1;
}
/* Add self-mapping */
RtlZeroMemory(&PmlBase[PmlIndex], sizeof(HARDWARE_PTE));
PmlBase[PmlIndex].PageFrameNumber = (UINT_PTR)PageMap->PtePointer / EFI_PAGE_SIZE;
PmlBase[PmlIndex].Valid = 1;
PmlBase[PmlIndex].Writable = 1;
/* Return success */
return STATUS_EFI_SUCCESS;
}

View File

@@ -36,7 +36,7 @@ BlBuildPageMap(IN PXTBL_PAGE_MAPPING PageMap,
if(PageMap->PageMapLevel == 3)
{
/* Allocate a page for the 3-level page map structure (PAE enabled) */
Status = BlAllocateMemoryPages(1, &Address);
Status = BlAllocateMemoryPages(AllocateAnyPages, 1, &Address);
if(Status != STATUS_EFI_SUCCESS)
{
/* Memory allocation failed, cannot proceed with page map creation */
@@ -48,7 +48,7 @@ BlBuildPageMap(IN PXTBL_PAGE_MAPPING PageMap,
RtlZeroMemory(PageMap->PtePointer, EFI_PAGE_SIZE);
/* Allocate 4 pages for the Page Directories (PDs) */
Status = BlAllocateMemoryPages(4, &DirectoryAddress);
Status = BlAllocateMemoryPages(AllocateAnyPages, 4, &DirectoryAddress);
if(Status != STATUS_EFI_SUCCESS)
{
/* Memory allocation failed, cannot proceed with page map creation */
@@ -61,16 +61,16 @@ BlBuildPageMap(IN PXTBL_PAGE_MAPPING PageMap,
/* Fill the PDPT with pointers to the Page Directories */
for(Index = 0; Index < 4; Index++)
{
RtlZeroMemory(&((PHARDWARE_PTE)PageMap->PtePointer)[Index], sizeof(HARDWARE_PTE));
((PHARDWARE_PTE)PageMap->PtePointer)[Index].PageFrameNumber = DirectoryAddress / EFI_PAGE_SIZE;
((PHARDWARE_PTE)PageMap->PtePointer)[Index].Valid = 1;
RtlZeroMemory(&((PHARDWARE_MODERN_PTE)PageMap->PtePointer)[Index], sizeof(HARDWARE_MODERN_PTE));
((PHARDWARE_MODERN_PTE)PageMap->PtePointer)[Index].PageFrameNumber = DirectoryAddress / EFI_PAGE_SIZE;
((PHARDWARE_MODERN_PTE)PageMap->PtePointer)[Index].Valid = 1;
DirectoryAddress += EFI_PAGE_SIZE;
}
}
else
{
/* Allocate a page for the 2-level page map structure (PAE disabled) */
Status = BlAllocateMemoryPages(1, &Address);
Status = BlAllocateMemoryPages(AllocateAnyPages, 1, &Address);
if(Status != STATUS_EFI_SUCCESS)
{
/* Memory allocation failed, cannot proceed with page map creation */
@@ -90,6 +90,15 @@ BlBuildPageMap(IN PXTBL_PAGE_MAPPING PageMap,
return Status;
}
/* Map the trampoline code area */
Status = BlMapVirtualMemory(PageMap, (PVOID)MM_TRAMPOLINE_ADDRESS,(PVOID)MM_TRAMPOLINE_ADDRESS,
1, LoaderFirmwareTemporary);
if(Status != STATUS_EFI_SUCCESS)
{
/* Mapping trampoline code failed */
return Status;
}
/* Get list of XTLDR modules */
ModulesList = BlGetModulesList();
ModulesListEntry = ModulesList->Flink;
@@ -193,8 +202,8 @@ BlMapPage(IN PXTBL_PAGE_MAPPING PageMap,
SIZE_T PageFrameNumber;
PVOID Pml1, Pml2, Pml3;
SIZE_T Pml1Entry, Pml2Entry, Pml3Entry;
PHARDWARE_PTE PmlTable;
PHARDWARE_LEGACY_PTE LegacyPmlTable;
PHARDWARE_MODERN_PTE PmlTable;
EFI_STATUS Status;
/* Set the Page Frame Number (PFN) */
@@ -231,8 +240,8 @@ BlMapPage(IN PXTBL_PAGE_MAPPING PageMap,
}
/* Set the 64-bit PTE entry */
PmlTable = (PHARDWARE_PTE)Pml1;
RtlZeroMemory(&PmlTable[Pml1Entry], sizeof(HARDWARE_PTE));
PmlTable = (PHARDWARE_MODERN_PTE)Pml1;
RtlZeroMemory(&PmlTable[Pml1Entry], sizeof(HARDWARE_MODERN_PTE));
PmlTable[Pml1Entry].PageFrameNumber = PageFrameNumber;
PmlTable[Pml1Entry].Valid = 1;
PmlTable[Pml1Entry].Writable = 1;
@@ -304,14 +313,14 @@ BlpGetNextPageTable(IN PXTBL_PAGE_MAPPING PageMap,
ULONGLONG PmlPointer = 0;
EFI_STATUS Status;
PHARDWARE_LEGACY_PTE LegacyPmlTable;
PHARDWARE_PTE PmlTable;
PHARDWARE_MODERN_PTE PmlTable;
BOOLEAN ValidPte = FALSE;
/* Check page map level to determine PTE size */
if(PageMap->PageMapLevel >= 3)
{
/* 64-bit PTE for PML3 (PAE enabled) */
PmlTable = (PHARDWARE_PTE)PageTable;
PmlTable = (PHARDWARE_MODERN_PTE)PageTable;
if(PmlTable[Entry].Valid)
{
/* Get page frame number from page table entry */
@@ -340,7 +349,7 @@ BlpGetNextPageTable(IN PXTBL_PAGE_MAPPING PageMap,
else
{
/* Allocate pages for new PML entry */
Status = BlAllocateMemoryPages(1, &Address);
Status = BlAllocateMemoryPages(AllocateAnyPages, 1, &Address);
if(Status != STATUS_EFI_SUCCESS)
{
/* Memory allocation failure */
@@ -362,7 +371,7 @@ BlpGetNextPageTable(IN PXTBL_PAGE_MAPPING PageMap,
if(PageMap->PageMapLevel >= 3)
{
/* 64-bit PTE for PML3 (PAE enabled) */
PmlTable = (PHARDWARE_PTE)PageTable;
PmlTable = (PHARDWARE_MODERN_PTE)PageTable;
PmlTable[Entry].PageFrameNumber = Address / EFI_PAGE_SIZE;
PmlTable[Entry].Valid = 1;
PmlTable[Entry].Writable = 1;
@@ -406,7 +415,7 @@ BlpSelfMapPml(IN PXTBL_PAGE_MAPPING PageMap,
IN ULONG_PTR SelfMapAddress)
{
PHARDWARE_LEGACY_PTE LegacyPml;
PHARDWARE_PTE Pml;
PHARDWARE_MODERN_PTE Pml;
ULONGLONG PmlIndex;
ULONG Index;
@@ -417,13 +426,13 @@ BlpSelfMapPml(IN PXTBL_PAGE_MAPPING PageMap,
PmlIndex = (SelfMapAddress >> MM_PDI_SHIFT) & 0x1FF;
/* Get Page Directory */
Pml = (PHARDWARE_PTE)(((PHARDWARE_PTE)PageMap->PtePointer)[SelfMapAddress >> MM_PPI_SHIFT].PageFrameNumber * EFI_PAGE_SIZE);
Pml = (PHARDWARE_MODERN_PTE)(((PHARDWARE_MODERN_PTE)PageMap->PtePointer)[SelfMapAddress >> MM_PPI_SHIFT].PageFrameNumber * EFI_PAGE_SIZE);
/* Add self-mapping for PML3 (PAE enabled) */
for(Index = 0; Index < 4; Index++)
{
RtlZeroMemory(&Pml[PmlIndex + Index], sizeof(HARDWARE_PTE));
Pml[PmlIndex + Index].PageFrameNumber = ((PHARDWARE_PTE)PageMap->PtePointer)[Index].PageFrameNumber;
RtlZeroMemory(&Pml[PmlIndex + Index], sizeof(HARDWARE_MODERN_PTE));
Pml[PmlIndex + Index].PageFrameNumber = ((PHARDWARE_MODERN_PTE)PageMap->PtePointer)[Index].PageFrameNumber;
Pml[PmlIndex + Index].Valid = 1;
Pml[PmlIndex + Index].Writable = 1;
}

View File

@@ -4,11 +4,84 @@
* FILE: xtldr/config.c
* DESCRIPTION: XT Boot Loader Configuration
* DEVELOPERS: Rafal Kupiec <belliash@codingworkshop.eu.org>
* Aiken Harris <harraiken91@gmail.com>
*/
#include <xtldr.h>
/**
* @brief Retrieves the value of a specific OS boot option from a list.
*
* @param Options
* A pointer to the head of a list of XTBL_CONFIG_ENTRY structures.
*
* @param OptionName
* A pointer to wide string that contains the name of the boot option to retrieve.
*
* @param OptionValue
* A pointer to a variable that receives a pointer to the retrieved boot option's value.
*
* @return This routine returns a status code.
*
* @since XT 1.0
*/
XTCDECL
EFI_STATUS
BlGetBootOptionValue(IN PLIST_ENTRY Options,
IN CONST PWCHAR OptionName,
OUT PWCHAR *OptionValue)
{
PXTBL_CONFIG_ENTRY ConfigEntry;
PLIST_ENTRY ConfigList;
ULONG KeyLength, ValueLength;
EFI_STATUS Status;
/* Assume the option will not be found */
*OptionValue = NULL;
/* Get the length of the option name we are looking for */
KeyLength = RtlWideStringLength(OptionName, 0);
/* Start iterating from the first entry in the options list */
ConfigList = Options->Flink;
while(ConfigList != Options)
{
/* Get the container record for the current config entry */
ConfigEntry = CONTAIN_RECORD(ConfigList, XTBL_CONFIG_ENTRY, Flink);
/* Compare the current entry's name with the requested option name */
if(RtlCompareWideStringInsensitive(ConfigEntry->Name, OptionName, KeyLength) == 0)
{
/* Found the option, now prepare to copy its value */
ValueLength = RtlWideStringLength(ConfigEntry->Value, 0);
/* Allocate memory for the output value string */
Status = BlAllocateMemoryPool((ValueLength + 1) * sizeof(WCHAR), (PVOID *)OptionValue);
if(Status != STATUS_EFI_SUCCESS)
{
/* Memory allocation failure, print debug message and return status code */
BlDebugPrint(L"ERROR: Memory allocation failure (Status Code: 0x%zX)\n", Status);
*OptionValue = NULL;
return Status;
}
/* Copy the value and NULL-terminate the new string */
RtlCopyMemory(*OptionValue, ConfigEntry->Value, ValueLength * sizeof(WCHAR));
(*OptionValue)[ValueLength] = L'\0';
/* Successfully retrieved the option value, return success */
return STATUS_EFI_SUCCESS;
}
/* Move to the next entry in the list */
ConfigList = ConfigList->Flink;
}
/* Option not found */
return STATUS_EFI_NOT_FOUND;
}
/**
* Returns a boolean value of the specified configuration key.
*
@@ -26,7 +99,7 @@ BlGetConfigBooleanValue(IN CONST PWCHAR ConfigName)
PWCHAR Value;
/* Get config value */
Value = BlGetConfigValue(ConfigName);
BlGetConfigValue(ConfigName, &Value);
/* Check if option is enabled */
if(RtlCompareWideStringInsensitive(Value, L"ENABLED", 0) == 0 ||
@@ -53,8 +126,9 @@ BlGetConfigBooleanValue(IN CONST PWCHAR ConfigName)
* @since XT 1.0
*/
XTCDECL
PWCHAR
BlGetConfigValue(IN CONST PWCHAR ConfigName)
EFI_STATUS
BlGetConfigValue(IN CONST PWCHAR ConfigName,
OUT PWCHAR *ConfigValue)
{
PXTBL_CONFIG_ENTRY ConfigEntry;
PLIST_ENTRY ConfigListEntry;
@@ -62,6 +136,9 @@ BlGetConfigValue(IN CONST PWCHAR ConfigName)
EFI_STATUS Status;
PWCHAR Value;
/* Assume the option will not be found */
*ConfigValue = NULL;
/* Get config entry name length */
KeyLength = RtlWideStringLength(ConfigName, 0);
@@ -84,13 +161,14 @@ BlGetConfigValue(IN CONST PWCHAR ConfigName)
{
/* Memory allocation failure, return NULL */
BlDebugPrint(L"ERROR: Memory allocation failure (Status Code: 0x%zX)\n", Status);
return NULL;
return Status;
}
/* Copy value and return it */
RtlCopyMemory(Value, ConfigEntry->Value, ValueLength * sizeof(WCHAR));
Value[ValueLength] = L'\0';
return Value;
*ConfigValue = Value;
return STATUS_EFI_SUCCESS;
}
/* Move to the next config entry */
@@ -98,7 +176,157 @@ BlGetConfigValue(IN CONST PWCHAR ConfigName)
}
/* Config entry not found, return NULL */
return NULL;
return STATUS_EFI_NOT_FOUND;
}
/**
* Retrieves the list of user-editable boot options.
*
* @param OptionsArray
* A pointer to a variable that will receive the pointer to the array of editable option names.
*
* @param OptionsCount
* A pointer to a variable that will be updated with the number of elements in the OptionsArray.
*
* @return This routine does not return any value.
*
* @since XT 1.0
*/
XTCDECL
VOID
BlGetEditableOptions(OUT CONST PWCHAR **OptionsArray,
OUT PULONG OptionsCount)
{
ULONG Count = 0;
/* Return a pointer to the global array of editable options */
*OptionsArray = BlpEditableConfigOptions;
/* Calculate the number of elements in the array */
while(BlpEditableConfigOptions[Count])
{
Count++;
}
/* Return the number of elements */
*OptionsCount = Count;
}
/**
* Sets the value of a specific OS boot option in a list, or adds it if it doesn't exist.
*
* @param Options
* A pointer to the head of a list of XTBL_CONFIG_ENTRY structures.
*
* @param OptionName
* A pointer to a wide string that contains the name of the boot option to set.
*
* @param OptionValue
* A pointer to a wide string that contains the new value for the boot option.
*
* @return This routine returns a status code.
*
* @since XT 1.0
*/
XTCDECL
EFI_STATUS
BlSetBootOptionValue(IN PLIST_ENTRY Options,
IN CONST PWCHAR OptionName,
IN CONST PWCHAR OptionValue)
{
PXTBL_CONFIG_ENTRY ConfigEntry;
PLIST_ENTRY ConfigList;
ULONG Length;
EFI_STATUS Status;
/* Get the length of the option name we are looking for */
Length = RtlWideStringLength(OptionName, 0);
/* Start iterating from the first entry in the options list */
ConfigList = Options->Flink;
while(ConfigList != Options)
{
/* Get the container record for the current config entry */
ConfigEntry = CONTAIN_RECORD(ConfigList, XTBL_CONFIG_ENTRY, Flink);
/* Compare the current entry's name with the requested option name */
if(RtlCompareWideStringInsensitive(ConfigEntry->Name, OptionName, Length) == 0)
{
/* Found the option, get its length */
Length = RtlWideStringLength(OptionValue, 0);
/* Reallocate memory for the new value */
Status = BlFreeMemoryPool(ConfigEntry->Value);
if(Status != STATUS_EFI_SUCCESS)
{
/* Failed to free memory, return status code */
return Status;
}
/* Allocate new memory for the updated value */
Status = BlAllocateMemoryPool((Length + 1) * sizeof(WCHAR), (PVOID *)&ConfigEntry->Value);
if(Status != STATUS_EFI_SUCCESS)
{
/* Memory allocation failure, print debug message and return status code */
BlDebugPrint(L"ERROR: Memory allocation failure (Status Code: 0x%zX)\\n", Status);
return Status;
}
/* Copy the value and NULL-terminate the new string */
RtlCopyMemory(ConfigEntry->Value, OptionValue, Length * sizeof(WCHAR));
ConfigEntry->Value[Length] = L'\0';
return STATUS_EFI_SUCCESS;
}
/* Move to the next entry in the list */
ConfigList = ConfigList->Flink;
}
/* Option not found, allocate memory for the new one */
Status = BlAllocateMemoryPool(sizeof(XTBL_CONFIG_ENTRY), (PVOID *)&ConfigEntry);
if(Status != STATUS_EFI_SUCCESS)
{
/* Memory allocation failure, print debug message and return status code */
BlDebugPrint(L"ERROR: Memory allocation failure (Status Code: 0x%zX)\\n", Status);
return Status;
}
/* Allocate memory for the option name */
Length = RtlWideStringLength(OptionName, 0);
Status = BlAllocateMemoryPool((Length + 1) * sizeof(WCHAR), (PVOID *)&ConfigEntry->Name);
if(Status != STATUS_EFI_SUCCESS)
{
/* Memory allocation failure, print debug message and return status code */
BlDebugPrint(L"ERROR: Memory allocation failure (Status Code: 0x%zX)\\n", Status);
BlFreeMemoryPool(ConfigEntry);
return Status;
}
/* Copy the option name and NULL-terminate the new string */
RtlCopyMemory(ConfigEntry->Name, OptionName, Length * sizeof(WCHAR));
ConfigEntry->Name[Length] = L'\0';
/* Allocate memory for the option value */
Length = RtlWideStringLength(OptionValue, 0);
Status = BlAllocateMemoryPool((Length + 1) * sizeof(WCHAR), (PVOID *)&ConfigEntry->Value);
if(Status != STATUS_EFI_SUCCESS)
{
/* Memory allocation failure, print debug message and return status code */
BlDebugPrint(L"ERROR: Memory allocation failure (Status Code: 0x%zX)\\n", Status);
BlFreeMemoryPool(ConfigEntry->Name);
BlFreeMemoryPool(ConfigEntry);
return Status;
}
/* Copy the value and NULL-terminate the new string */
RtlCopyMemory(ConfigEntry->Value, OptionValue, Length * sizeof(WCHAR));
ConfigEntry->Value[Length] = L'\0';
/* Insert the new config entry at the end of the options list */
RtlInsertTailList(Options, &ConfigEntry->Flink);
/* Return success */
return STATUS_EFI_SUCCESS;
}
/**
@@ -110,7 +338,7 @@ BlGetConfigValue(IN CONST PWCHAR ConfigName)
* @param ConfigValue
* Specifies the new configuration value.
*
* @return This routine returns status code.
* @return This routine returns a status code.
*
* @since XT 1.0
*/
@@ -174,7 +402,7 @@ BlSetConfigValue(IN CONST PWCHAR ConfigName,
/**
* Loads and parses XTLDR configuration file.
*
* @return This routine returns status code.
* @return This routine returns a status code.
*
* @since XT 1.0
*/
@@ -453,7 +681,7 @@ BlpParseConfigFile(IN CONST PCHAR RawConfig,
/* Initialize new section and convert its name to wide string */
RtlInitializeListHead(&Section->Options);
RtlStringToWideString(Section->SectionName, &SectionName, SectionLength);
RtlStringToWideString(Section->SectionName, (PCSTR*)&SectionName, SectionLength);
/* Ensure string is NULL-terminated and add new section to the configuration list */
Section->SectionName[SectionLength] = L'\0';
@@ -542,8 +770,8 @@ BlpParseConfigFile(IN CONST PCHAR RawConfig,
}
/* Convert key and value to wide strings */
RtlStringToWideString(Option->Name, &Key, RtlStringLength(Key, 0) + 1);
RtlStringToWideString(Option->Value, &Value, RtlStringLength(Value, 0) + 1);
RtlStringToWideString(Option->Name, (PCSTR*)&Key, RtlStringLength(Key, 0) + 1);
RtlStringToWideString(Option->Value, (PCSTR*)&Value, RtlStringLength(Value, 0) + 1);
/* Ensure strings are NULL-terminated and add new option to the list */
Option->Name[KeyLength] = L'\0';
@@ -568,7 +796,7 @@ BlpParseConfigFile(IN CONST PCHAR RawConfig,
* @param ConfigData
* Provides a buffer to store the data read from the configuration file.
*
* @return This routine returns status code.
* @return This routine returns a status code.
*
* @since XT 1.0
*/
@@ -629,6 +857,7 @@ VOID
BlpUpdateConfiguration(IN PLIST_ENTRY NewConfig)
{
PXTBL_CONFIG_ENTRY ConfigEntry;
PWCHAR ConfigValue;
PLIST_ENTRY ConfigListEntry, NextListEntry;
/* Iterate through new config entries */
@@ -642,7 +871,8 @@ BlpUpdateConfiguration(IN PLIST_ENTRY NewConfig)
NextListEntry = ConfigListEntry->Flink;
/* Make sure config entry does not exist yet */
if(BlGetConfigValue(ConfigEntry->Name) == NULL)
BlGetConfigValue(ConfigEntry->Name, &ConfigValue);
if(ConfigValue == NULL)
{
/* Remove new config entry from input list and put it into global config list */
RtlRemoveEntryList(&ConfigEntry->Flink);

View File

@@ -95,7 +95,7 @@ BlEnableConsoleCursor()
*/
XTCDECL
VOID
BlConsolePrint(IN PUSHORT Format,
BlConsolePrint(IN PCWSTR Format,
IN ...)
{
RTL_PRINT_CONTEXT ConsolePrintContext, SerialPrintContext;
@@ -138,9 +138,9 @@ BlConsolePrint(IN PUSHORT Format,
*/
XTCDECL
VOID
BlConsoleWrite(IN PUSHORT String)
BlConsoleWrite(IN PCWSTR String)
{
EfiSystemTable->ConOut->OutputString(EfiSystemTable->ConOut, String);
EfiSystemTable->ConOut->OutputString(EfiSystemTable->ConOut, (PWSTR)String);
}
/**
@@ -292,9 +292,9 @@ BlSetCursorPosition(IN ULONGLONG PosX,
*/
XTCDECL
XTSTATUS
BlpConsolePutChar(IN USHORT Character)
BlpConsolePutChar(IN WCHAR Character)
{
USHORT Buffer[2];
WCHAR Buffer[2];
/* Check if character is a newline ('\n') */
if(Character == L'\n')

View File

@@ -24,7 +24,7 @@
*/
XTCDECL
VOID
BlDebugPrint(IN PUSHORT Format,
BlDebugPrint(IN PCWSTR Format,
IN ...)
{
RTL_PRINT_CONTEXT ConsolePrintContext, SerialPrintContext;
@@ -71,17 +71,14 @@ BlDebugPrint(IN PUSHORT Format,
*/
XTCDECL
XTSTATUS
BlpDebugPutChar(IN USHORT Character)
BlpDebugPutChar(IN WCHAR Character)
{
USHORT Buffer[2];
WCHAR Buffer[2];
/* Write character to the serial console */
Buffer[0] = Character;
Buffer[1] = 0;
HlComPortPutByte(&BlpStatus.SerialPort, Buffer[0]);
/* Return success */
return STATUS_EFI_SUCCESS;
return HlComPortPutByte(&BlpStatus.SerialPort, Buffer[0]);
}
/**
@@ -105,7 +102,7 @@ BlpInitializeDebugConsole()
BaudRate = 0;
/* Get debug configuration */
DebugConfiguration = BlGetConfigValue(L"DEBUG");
BlGetConfigValue(L"DEBUG", &DebugConfiguration);
/* Make sure any debug options are provided and debug console is not initialized yet */
if(DebugConfiguration && BlpStatus.DebugPort == 0)

View File

@@ -21,6 +21,13 @@ LIST_ENTRY BlpConfig;
/* XT Boot Loader loaded configuration */
LIST_ENTRY BlpConfigSections;
/* List of user-editable boot options */
PWCHAR BlpEditableConfigOptions[] = {
L"BootModules", L"SystemType", L"SystemPath",
L"KernelFile", L"InitrdFile", L"HalFile",
L"Parameters", NULL
};
/* XT Boot Loader protocol */
XTBL_LOADER_PROTOCOL BlpLdrProtocol;
@@ -41,3 +48,4 @@ EFI_HANDLE EfiImageHandle;
/* EFI System Table */
PEFI_SYSTEM_TABLE EfiSystemTable;

View File

@@ -24,6 +24,9 @@ EXTERN LIST_ENTRY BlpConfig;
/* XT Boot Loader loaded configuration */
EXTERN LIST_ENTRY BlpConfigSections;
/* List of user-editable boot options */
EXTERN PWCHAR BlpEditableConfigOptions[];
/* XT Boot Loader protocol */
EXTERN XTBL_LOADER_PROTOCOL BlpLdrProtocol;

View File

@@ -18,7 +18,8 @@
/* XTLDR routines forward references */
XTCDECL
EFI_STATUS
BlAllocateMemoryPages(IN ULONGLONG NumberOfPages,
BlAllocateMemoryPages(IN EFI_ALLOCATE_TYPE AllocationType,
IN ULONGLONG NumberOfPages,
OUT PEFI_PHYSICAL_ADDRESS Memory);
XTCDECL
@@ -50,16 +51,16 @@ BlCloseVolume(IN PEFI_HANDLE VolumeHandle);
XTCDECL
VOID
BlConsolePrint(IN PUSHORT Format,
BlConsolePrint(IN PCWSTR Format,
IN ...);
XTCDECL
VOID
BlConsoleWrite(IN PUSHORT String);
BlConsoleWrite(IN PCWSTR String);
XTCDECL
VOID
BlDebugPrint(IN PUSHORT Format,
BlDebugPrint(IN PCWSTR Format,
IN ...);
XTCDECL
@@ -70,6 +71,10 @@ XTCDECL
VOID
BlDisplayBootMenu();
XTCDECL
VOID
BlDisplayEditMenu(IN PXTBL_BOOTMENU_ITEM MenuEntry);
XTCDECL
VOID
BlDisplayErrorDialog(IN PWCHAR Caption,
@@ -133,19 +138,31 @@ BOOLEAN
BlGetBooleanParameter(IN CONST PWCHAR Parameters,
IN CONST PWCHAR Needle);
XTCDECL
EFI_STATUS
BlGetBootOptionValue(IN PLIST_ENTRY Options,
IN CONST PWCHAR OptionName,
OUT PWCHAR *OptionValue);
XTCDECL
BOOLEAN
BlGetConfigBooleanValue(IN CONST PWCHAR ConfigName);
XTCDECL
PWCHAR
BlGetConfigValue(IN CONST PWCHAR ConfigName);
EFI_STATUS
BlGetConfigValue(IN CONST PWCHAR ConfigName,
OUT PWCHAR *ConfigValue);
XTCDECL
EFI_STATUS
BlGetConfigurationTable(IN PEFI_GUID TableGuid,
OUT PVOID *Table);
XTCDECL
VOID
BlGetEditableOptions(OUT CONST PWCHAR **OptionsArray,
OUT PULONG OptionsCount);
XTCDECL
EFI_STATUS
BlGetEfiPath(IN PWCHAR SystemPath,
@@ -196,7 +213,8 @@ BlInitializeBootLoader();
XTCDECL
EFI_STATUS
BlInitializeBootMenuList(OUT PXTBL_BOOTMENU_ITEM *MenuEntries,
BlInitializeBootMenuList(IN ULONG MaxNameLength,
OUT PXTBL_BOOTMENU_ITEM *MenuEntries,
OUT PULONG EntriesCount,
OUT PULONG DefaultId);
@@ -330,6 +348,12 @@ XTCDECL
VOID
BlResetConsoleInputBuffer();
XTCDECL
EFI_STATUS
BlSetBootOptionValue(IN PLIST_ENTRY Options,
IN CONST PWCHAR OptionName,
IN CONST PWCHAR OptionValue);
XTCDECL
EFI_STATUS
BlSetConfigValue(IN CONST PWCHAR ConfigName,
@@ -394,11 +418,11 @@ BlpActivateSerialIOController();
XTCDECL
XTSTATUS
BlpConsolePutChar(IN USHORT Character);
BlpConsolePutChar(IN WCHAR Character);
XTCDECL
XTSTATUS
BlpDebugPutChar(IN USHORT Character);
BlpDebugPutChar(IN WCHAR Character);
XTCDECL
VOID
@@ -454,6 +478,18 @@ VOID
BlpDrawDialogProgressBar(IN PXTBL_DIALOG_HANDLE Handle,
IN UCHAR Percentage);
XTCDECL
VOID
BlpDrawEditMenu(OUT PXTBL_DIALOG_HANDLE Handle);
XTCDECL
EFI_STATUS
BlpDrawEditMenuEntry(IN PXTBL_DIALOG_HANDLE Handle,
IN PWCHAR OptionName,
IN PWCHAR OptionValue,
IN UINT Position,
IN BOOLEAN Highlighted);
XTCDECL
PEFI_DEVICE_PATH_PROTOCOL
BlpDuplicateDevicePath(IN PEFI_DEVICE_PATH_PROTOCOL DevicePath);

View File

@@ -24,10 +24,11 @@
*/
XTCDECL
EFI_STATUS
BlAllocateMemoryPages(IN ULONGLONG NumberOfPages,
BlAllocateMemoryPages(IN EFI_ALLOCATE_TYPE AllocationType,
IN ULONGLONG NumberOfPages,
OUT PEFI_PHYSICAL_ADDRESS Memory)
{
return EfiSystemTable->BootServices->AllocatePages(AllocateAnyPages, EfiLoaderData, NumberOfPages, Memory);
return EfiSystemTable->BootServices->AllocatePages(AllocationType, EfiLoaderData, NumberOfPages, Memory);
}
/**

View File

@@ -196,6 +196,7 @@ XtLdrModuleMain(IN EFI_HANDLE ImageHandle,
IN PEFI_SYSTEM_TABLE SystemTable)
{
EFI_STATUS Status;
PWCHAR Tune;
/* Open the XTLDR protocol */
Status = BlGetXtLdrProtocol(SystemTable, ImageHandle, &XtLdrProtocol);
@@ -206,7 +207,8 @@ XtLdrModuleMain(IN EFI_HANDLE ImageHandle,
}
/* Play the tune set in the configuration */
BpPlayTune(XtLdrProtocol->Config.GetValue(L"TUNE"));
XtLdrProtocol->Config.GetValue(L"TUNE", &Tune);
BpPlayTune(Tune);
/* Return success */
return STATUS_EFI_SUCCESS;

View File

@@ -409,7 +409,7 @@ PeLoadImage(IN PEFI_FILE_HANDLE FileHandle,
Pages = EFI_SIZE_TO_PAGES(ImageData->FileSize);
/* Allocate pages */
Status = XtLdrProtocol->Memory.AllocatePages(Pages, &Address);
Status = XtLdrProtocol->Memory.AllocatePages(AllocateAnyPages, Pages, &Address);
if(Status != STATUS_EFI_SUCCESS)
{
/* Pages allocation failure */
@@ -472,7 +472,7 @@ PeLoadImage(IN PEFI_FILE_HANDLE FileHandle,
ImageData->ImagePages = EFI_SIZE_TO_PAGES(ImageData->ImageSize);
/* Allocate image pages */
Status = XtLdrProtocol->Memory.AllocatePages(ImageData->ImagePages, &Address);
Status = XtLdrProtocol->Memory.AllocatePages(AllocateAnyPages, ImageData->ImagePages, &Address);
if(Status != STATUS_EFI_SUCCESS)
{
/* Pages reallocation failure */

View File

@@ -70,25 +70,54 @@ XTCDECL
EFI_STATUS
XtpMapHardwareMemoryPool(IN PXTBL_PAGE_MAPPING PageMap)
{
PHARDWARE_PTE PdeBase, PpeBase, PxeBase;
PHARDWARE_PTE P5eBase, PdeBase, PpeBase, PxeBase;
EFI_PHYSICAL_ADDRESS Address;
EFI_STATUS Status;
/* Check page map level */
if(PageMap->PageMapLevel > 4)
if(PageMap->PageMapLevel == 5)
{
/* PML5 (LA57) is not supported yet */
return STATUS_EFI_UNSUPPORTED;
}
/* Get P5E (PML5) base address */
P5eBase = (PHARDWARE_PTE)PageMap->PtePointer;
/* Get PXE (PML4) base address */
PxeBase = ((PHARDWARE_PTE)(PageMap->PtePointer));
/* Check if P5E entry already exists */
if(!P5eBase[(MM_HARDWARE_VA_START >> MM_P5I_SHIFT) & 0x1FF].Valid)
{
/* No valid P5E, allocate memory */
Status = XtLdrProtocol->Memory.AllocatePages(AllocateAnyPages, 1, &Address);
if(Status != STATUS_EFI_SUCCESS)
{
/* Memory allocation failure, return error */
return Status;
}
/* Zero fill memory used by P5E */
RtlZeroMemory((PVOID)Address, EFI_PAGE_SIZE);
/* Make P5E valid */
P5eBase[(MM_HARDWARE_VA_START >> MM_P5I_SHIFT) & 0x1FF].Valid = 1;
P5eBase[(MM_HARDWARE_VA_START >> MM_P5I_SHIFT) & 0x1FF].PageFrameNumber = Address / EFI_PAGE_SIZE;
P5eBase[(MM_HARDWARE_VA_START >> MM_P5I_SHIFT) & 0x1FF].Writable = 1;
/* Set PXE base address */
PxeBase = (PHARDWARE_PTE)(UINT_PTR)Address;
}
else
{
/* Set PXE base address based on existing P5E */
PxeBase = (PHARDWARE_PTE)((P5eBase[(MM_HARDWARE_VA_START >> MM_P5I_SHIFT) & 0x1FF].PageFrameNumber) << EFI_PAGE_SHIFT);
}
}
else
{
/* Get PXE (PML4) base address */
PxeBase = (PHARDWARE_PTE)PageMap->PtePointer;
}
/* Check if PXE entry already exists */
if(!PxeBase[(MM_HARDWARE_VA_START >> MM_PXI_SHIFT) & 0x1FF].Valid)
{
/* No valid PXE, allocate memory */
Status = XtLdrProtocol->Memory.AllocatePages(1, &Address);
Status = XtLdrProtocol->Memory.AllocatePages(AllocateAnyPages, 1, &Address);
if(Status != STATUS_EFI_SUCCESS)
{
/* Memory allocation failure, return error */
@@ -116,7 +145,7 @@ XtpMapHardwareMemoryPool(IN PXTBL_PAGE_MAPPING PageMap)
if(!PpeBase[(MM_HARDWARE_VA_START >> MM_PPI_SHIFT) & 0x1FF].Valid)
{
/* No valid PPE, allocate memory */
Status = XtLdrProtocol->Memory.AllocatePages(1, &Address);
Status = XtLdrProtocol->Memory.AllocatePages(AllocateAnyPages, 1, &Address);
if(Status != STATUS_EFI_SUCCESS)
{
/* Memory allocation failure, return error */
@@ -147,7 +176,7 @@ XtpMapHardwareMemoryPool(IN PXTBL_PAGE_MAPPING PageMap)
if(!PdeBase[((MM_HARDWARE_VA_START >> MM_PDI_SHIFT) & 0x1FF) + Index].Valid)
{
/* No valid PDE, allocate memory */
Status = XtLdrProtocol->Memory.AllocatePages(1, &Address);
Status = XtLdrProtocol->Memory.AllocatePages(AllocateAnyPages, 1, &Address);
if(Status != STATUS_EFI_SUCCESS)
{
/* Memory allocation failure, return error */
@@ -183,9 +212,12 @@ EFI_STATUS
XtEnablePaging(IN PXTBL_PAGE_MAPPING PageMap)
{
EFI_STATUS Status;
EFI_PHYSICAL_ADDRESS TrampolineAddress;
PXT_TRAMPOLINE_ENTRY TrampolineEntry;
ULONG_PTR TrampolineSize;
/* Build page map */
Status = XtLdrProtocol->Memory.BuildPageMap(PageMap, 0xFFFFF6FB7DBED000);
Status = XtLdrProtocol->Memory.BuildPageMap(PageMap, (PageMap->PageMapLevel > 4) ? MM_P5E_LA57_BASE : MM_PXE_BASE);
if(Status != STATUS_EFI_SUCCESS)
{
/* Failed to build page map */
@@ -202,6 +234,29 @@ XtEnablePaging(IN PXTBL_PAGE_MAPPING PageMap)
return Status;
}
/* Check the configured page map level to set the LA57 state accordingly */
if(PageMap->PageMapLevel == 5)
{
/* Set the address of the trampoline code below 1MB */
TrampolineAddress = MM_TRAMPOLINE_ADDRESS;
/* Calculate the size of the trampoline code */
TrampolineSize = (ULONG_PTR)ArEnableExtendedPhysicalAddressingEnd - (ULONG_PTR)ArEnableExtendedPhysicalAddressing;
/* Allocate pages for the trampoline */
Status = XtLdrProtocol->Memory.AllocatePages(AllocateAddress, EFI_SIZE_TO_PAGES(TrampolineSize), &TrampolineAddress);
if(Status != STATUS_EFI_SUCCESS)
{
/* Failed to allocate memory for trampoline code */
XtLdrProtocol->Debug.Print(L"Failed to allocate memory for trampoline code (Status code: %zX)\n", Status);
return Status;
}
/* Set the trampoline entry point and copy its code into the allocated buffer */
TrampolineEntry = (PXT_TRAMPOLINE_ENTRY)(UINT_PTR)TrampolineAddress;
RtlCopyMemory(TrampolineEntry, ArEnableExtendedPhysicalAddressing, TrampolineSize);
}
/* Exit EFI Boot Services */
XtLdrProtocol->Debug.Print(L"Exiting EFI boot services\n");
Status = XtLdrProtocol->Util.ExitBootServices();
@@ -217,19 +272,20 @@ XtEnablePaging(IN PXTBL_PAGE_MAPPING PageMap)
{
/* Enable Linear Address 57-bit (LA57) extension */
XtLdrProtocol->Debug.Print(L"Enabling Linear Address 57-bit (LA57)\n");
/* Execute the trampoline to enable LA57 and write PML5 to CR3 */
TrampolineEntry((UINT64)PageMap->PtePointer);
}
else
{
/* Disable Linear Address 57-bit (LA57) extension */
XtLdrProtocol->Debug.Print(L"Disabling Linear Address 57-bit (LA57)\n");
/* Write PML4 to CR3 and enable paging */
ArWriteControlRegister(3, (UINT_PTR)PageMap->PtePointer);
ArWriteControlRegister(0, ArReadControlRegister(0) | CR0_PG);
}
/* Write PML4 to CR3 */
ArWriteControlRegister(3, (UINT_PTR)PageMap->PtePointer);
/* Enable paging */
ArWriteControlRegister(0, ArReadControlRegister(0) | CR0_PG);
/* Return success */
return STATUS_EFI_SUCCESS;
}

View File

@@ -60,11 +60,11 @@ XtpMapHardwareMemoryPool(IN PXTBL_PAGE_MAPPING PageMap)
{
EFI_PHYSICAL_ADDRESS Address;
PHARDWARE_LEGACY_PTE LegacyPdeBase;
PHARDWARE_PTE PdeBase;
PHARDWARE_MODERN_PTE PdeBase;
EFI_STATUS Status;
/* Allocate memory */
Status = XtLdrProtocol->Memory.AllocatePages(1, &Address);
Status = XtLdrProtocol->Memory.AllocatePages(AllocateAnyPages, 1, &Address);
if(Status != STATUS_EFI_SUCCESS)
{
/* Memory allocation failure, return error */
@@ -78,10 +78,10 @@ XtpMapHardwareMemoryPool(IN PXTBL_PAGE_MAPPING PageMap)
if(PageMap->PageMapLevel == 3)
{
/* Get PDE base address (PAE enabled) */
PdeBase = (PHARDWARE_PTE)(((PHARDWARE_PTE)PageMap->PtePointer)[MM_HARDWARE_VA_START >> MM_PPI_SHIFT].PageFrameNumber << MM_PAGE_SHIFT);
PdeBase = (PHARDWARE_MODERN_PTE)(((PHARDWARE_MODERN_PTE)PageMap->PtePointer)[MM_HARDWARE_VA_START >> MM_PPI_SHIFT].PageFrameNumber << MM_PAGE_SHIFT);
/* Make PDE valid */
RtlZeroMemory(&PdeBase[(MM_HARDWARE_VA_START >> MM_PDI_SHIFT) & 0x1FF], sizeof(HARDWARE_PTE));
RtlZeroMemory(&PdeBase[(MM_HARDWARE_VA_START >> MM_PDI_SHIFT) & 0x1FF], sizeof(HARDWARE_MODERN_PTE));
PdeBase[(MM_HARDWARE_VA_START >> MM_PDI_SHIFT) & 0x1FF].PageFrameNumber = Address >> MM_PAGE_SHIFT;
PdeBase[(MM_HARDWARE_VA_START >> MM_PDI_SHIFT) & 0x1FF].Valid = 1;
PdeBase[(MM_HARDWARE_VA_START >> MM_PDI_SHIFT) & 0x1FF].Writable = 1;
@@ -126,7 +126,7 @@ XtEnablePaging(IN PXTBL_PAGE_MAPPING PageMap)
EFI_STATUS Status;
/* Build page map */
Status = XtLdrProtocol->Memory.BuildPageMap(PageMap, 0xC0000000);
Status = XtLdrProtocol->Memory.BuildPageMap(PageMap, MM_PTE_BASE);
if(Status != STATUS_EFI_SUCCESS)
{
/* Failed to build page map */

View File

@@ -29,9 +29,15 @@ typedef struct _XT_FRAMEBUFFER_PROTOCOL
/* EFI XT Loader Protocol */
EXTERN PXTBL_LOADER_PROTOCOL XtLdrProtocol;
/* XTOS trampoline end address to calculate trampoline size */
EXTERN PVOID ArEnableExtendedPhysicalAddressingEnd[];
/* XTOS kernel entry point */
typedef VOID (XTAPI *PXT_ENTRY_POINT)(IN PKERNEL_INITIALIZATION_BLOCK BootParameters);
/* XTOS trampoline entry point */
typedef VOID (*PXT_TRAMPOLINE_ENTRY)(UINT64 PageMap);
/* XTOS boot protocol related routines forward references */
XTCDECL
EFI_STATUS

View File

@@ -75,7 +75,7 @@ XtGetMemoryDescriptorList(IN PXTBL_PAGE_MAPPING PageMap,
Pages = (ULONGLONG)EFI_SIZE_TO_PAGES((PageMap->MapSize + 1) * sizeof(LOADER_MEMORY_DESCRIPTOR));
Status = XtLdrProtocol->Memory.AllocatePages(Pages, &Address);
Status = XtLdrProtocol->Memory.AllocatePages(AllocateAnyPages, Pages, &Address);
if(Status != STATUS_EFI_SUCCESS)
{
return Status;
@@ -136,7 +136,7 @@ XtGetSystemResourcesList(IN PXTBL_PAGE_MAPPING PageMap,
Pages = (ULONGLONG)EFI_SIZE_TO_PAGES(sizeof(SYSTEM_RESOURCE_ACPI) + sizeof(SYSTEM_RESOURCE_FRAMEBUFFER));
Status = XtLdrProtocol->Memory.AllocatePages(Pages, &Address);
Status = XtLdrProtocol->Memory.AllocatePages(AllocateAnyPages, Pages, &Address);
if(Status != STATUS_EFI_SUCCESS)
{
return Status;
@@ -547,12 +547,16 @@ XtpInitializeLoaderBlock(IN PXTBL_PAGE_MAPPING PageMap,
// PVOID RuntimeServices;
EFI_STATUS Status;
UINT BlockPages;
UINT ParametersSize;
/* Calculate size of parameters */
ParametersSize = (RtlWideStringLength(Parameters->Parameters, 0) + 1) * sizeof(WCHAR);
/* Calculate number of pages needed for initialization block */
BlockPages = EFI_SIZE_TO_PAGES(sizeof(KERNEL_INITIALIZATION_BLOCK));
BlockPages = EFI_SIZE_TO_PAGES(sizeof(KERNEL_INITIALIZATION_BLOCK) + ParametersSize);
/* Allocate memory for kernel initialization block */
Status = XtLdrProtocol->Memory.AllocatePages(BlockPages, &Address);
Status = XtLdrProtocol->Memory.AllocatePages(AllocateAnyPages, BlockPages, &Address);
if(Status != STATUS_EFI_SUCCESS)
{
/* Memory allocation failure */
@@ -561,7 +565,7 @@ XtpInitializeLoaderBlock(IN PXTBL_PAGE_MAPPING PageMap,
/* Initialize and zero-fill kernel initialization block */
LoaderBlock = (PKERNEL_INITIALIZATION_BLOCK)(UINT_PTR)Address;
RtlZeroMemory(LoaderBlock, sizeof(KERNEL_INITIALIZATION_BLOCK));
RtlZeroMemory(LoaderBlock, sizeof(KERNEL_INITIALIZATION_BLOCK) + ParametersSize);
/* Set basic loader block properties */
LoaderBlock->BlockSize = sizeof(KERNEL_INITIALIZATION_BLOCK);
@@ -571,9 +575,6 @@ XtpInitializeLoaderBlock(IN PXTBL_PAGE_MAPPING PageMap,
/* Set LoaderInformation block properties */
LoaderBlock->LoaderInformation.DbgPrint = XtLdrProtocol->Debug.Print;
/* Store page map level */
LoaderBlock->LoaderInformation.PageMapLevel = PageMap->PageMapLevel;
/* Attempt to find virtual address of the EFI Runtime Services */
// Status = XtLdrProtocol->GetVirtualAddress(MemoryMappings, &EfiSystemTable->RuntimeServices->Hdr, &RuntimeServices);
// if(Status == STATUS_EFI_SUCCESS)
@@ -590,8 +591,10 @@ XtpInitializeLoaderBlock(IN PXTBL_PAGE_MAPPING PageMap,
// }
/* Copy parameters to kernel initialization block */
RtlCopyMemory(LoaderBlock->KernelParameters, Parameters->Parameters,
(RtlWideStringLength(Parameters->Parameters, 0) + 1) * sizeof(WCHAR));
LoaderBlock->KernelParameters = (PWCHAR)((UINT_PTR)*VirtualAddress + sizeof(KERNEL_INITIALIZATION_BLOCK));
RtlCopyMemory((PVOID)((UINT_PTR)LoaderBlock + sizeof(KERNEL_INITIALIZATION_BLOCK)),
Parameters->Parameters,
ParametersSize);
/* Map kernel initialization block */
XtLdrProtocol->Memory.MapVirtualMemory(PageMap, *VirtualAddress, (PVOID)LoaderBlock,

View File

@@ -749,100 +749,96 @@ BlpGetModuleInfoStrings(IN PWCHAR SectionData,
EFI_STATUS Status;
PWCHAR *Array;
PWCHAR String;
ULONG DataSize;
/* Check input parameters */
InfoStrings = SectionData;
if(!InfoStrings || !SectionSize)
{
/* Invalid input parameters */
*ModInfo = NULL;
*InfoCount = 0;
return STATUS_EFI_INVALID_PARAMETER;
}
/* Skip zero padding */
while(InfoStrings[0] == L'\0' && SectionSize > 1)
/* Calculate the size of the data based on the size of the section */
DataSize = SectionSize / sizeof(WCHAR);
/* Skip zero padding at the beginning */
while(DataSize > 0 && *InfoStrings == L'\0')
{
/* Get next character and decrement section size */
InfoStrings++;
SectionSize--;
DataSize--;
}
/* Make sure there is at least one string available */
if(SectionSize <= 1)
if(DataSize < 1)
{
/* No strings found */
*ModInfo = NULL;
*InfoCount = 0;
return STATUS_EFI_END_OF_FILE;
}
/* Count number of strings */
Index = 0;
Count = 0;
while(Index < SectionSize)
while(Index < DataSize)
{
/* Get to the next string */
if(InfoStrings[Index] != L'\0')
{
/* Get next character */
Index++;
continue;
}
/* Found start of a new string */
Count++;
/* Skip zero padding */
while(InfoStrings[Index] == L'\0' && Index < SectionSize)
/* Go to the end of the string */
while(Index < DataSize && InfoStrings[Index] != L'\0')
{
Index++;
}
/* Skip all null terminators */
while(Index < DataSize && InfoStrings[Index] == L'\0')
{
/* Get next character */
Index++;
}
/* New string found, increment counter */
Count++;
}
/* Make sure there is no missing string */
if(InfoStrings[Index - 1] != L'\0')
{
/* One more string available */
Count++;
}
/* Allocate memory for array of strings */
Status = BlAllocateMemoryPool(SectionSize + 1 + sizeof(PWCHAR) * (Count + 1), (PVOID *)&Array);
/* Allocate memory for the pointer array and the string data */
Status = BlAllocateMemoryPool(sizeof(PWCHAR) * (Count + 1) + (DataSize + 1) * sizeof(WCHAR), (PVOID *)&Array);
if(Status != STATUS_EFI_SUCCESS)
{
/* Failed to allocate memory */
return STATUS_EFI_OUT_OF_RESOURCES;
}
/* Allocate memory and copy strings read from '.modinfo' section */
BlAllocateMemoryPool(SectionSize, (PVOID*)&String);
RtlCopyMemory(String, InfoStrings, SectionSize);
/* The string buffer is located right after the pointer array */
String = (PWCHAR)(Array + Count + 1);
/* Make sure last string is NULL-terminated */
/* Copy the raw string data */
RtlCopyMemory(String, InfoStrings, DataSize * sizeof(WCHAR));
/* Ensure the entire buffer is null-terminated for safety */
String[DataSize] = L'\0';
/* Set the last element of the pointer array to NULL */
Array[Count] = NULL;
Array[0] = String;
/* Parse strings into array */
/* Populate the array with pointers to the strings within the buffer */
Index = 0;
ArrayIndex = 1;
while(Index < SectionSize && ArrayIndex < Count)
ArrayIndex = 0;
while(Index < DataSize && ArrayIndex < Count)
{
/* Get to the next string */
if(String[Index] != L'\0')
{
/* Get next character */
Index++;
continue;
}
/* Set pointer to the beginning of the string */
Array[ArrayIndex++] = &String[Index];
/* Skip zero padding */
while(InfoStrings[Index] == L'\0' && Index < SectionSize)
/* Find the end of the current string */
while(Index < DataSize && String[Index] != L'\0')
{
/* Get next character */
Index++;
}
/* Push string into array */
Array[ArrayIndex] = &String[Index];
ArrayIndex++;
/* Skip all null terminators to find the beginning of the next string */
while(Index < DataSize && String[Index] == L'\0')
{
Index++;
}
}
/* Return array of strings and its size */
@@ -874,7 +870,10 @@ BlpInstallXtLoaderProtocol()
BlpLdrProtocol.Boot.RegisterProtocol = BlRegisterBootProtocol;
BlpLdrProtocol.BootUtil.GetBooleanParameter = BlGetBooleanParameter;
BlpLdrProtocol.Config.GetBooleanValue = BlGetConfigBooleanValue;
BlpLdrProtocol.Config.GetBootOptionValue = BlGetBootOptionValue;
BlpLdrProtocol.Config.GetEditableOptions = BlGetEditableOptions;
BlpLdrProtocol.Config.GetValue = BlGetConfigValue;
BlpLdrProtocol.Config.SetBootOptionValue = BlSetBootOptionValue;
BlpLdrProtocol.Console.ClearLine = BlClearConsoleLine;
BlpLdrProtocol.Console.ClearScreen = BlClearConsoleScreen;
BlpLdrProtocol.Console.DisableCursor = BlDisableConsoleCursor;

View File

@@ -24,7 +24,8 @@ BlDisplayBootMenu()
XTBL_DIALOG_HANDLE Handle;
PXTBL_BOOTMENU_ITEM MenuEntries = NULL;
ULONG Index;
ULONG HighligtedEntryId, NumberOfEntries, TopVisibleEntry, VisibleEntries;
ULONG HighligtedEntryId, OldHighligtedEntryId, NumberOfEntries, TopVisibleEntry, VisibleEntries;
BOOLEAN RedrawBootMenu, RedrawEntries;
UINT_PTR EventIndex;
EFI_EVENT Events[2];
EFI_INPUT_KEY Key;
@@ -33,18 +34,18 @@ BlDisplayBootMenu()
LONG TimeOut;
PWCHAR TimeOutString;
/* Draw boot menu */
BlpDrawBootMenu(&Handle);
/* Initialize boot menu list */
TopVisibleEntry = 0;
Status = BlInitializeBootMenuList(&MenuEntries, &NumberOfEntries, &HighligtedEntryId);
Status = BlInitializeBootMenuList(Handle.Width - 4, &MenuEntries, &NumberOfEntries, &HighligtedEntryId);
if(Status != STATUS_EFI_SUCCESS)
{
/* Failed to initialize boot menu list, exit into XTLDR shell */
return;
}
/* Draw boot menu */
BlpDrawBootMenu(&Handle);
/* Calculate how many entries can be visible in the menu box */
VisibleEntries = Handle.Height - 2;
@@ -56,7 +57,7 @@ BlDisplayBootMenu()
}
/* Get timeout from the configuration */
TimeOutString = BlGetConfigValue(L"TIMEOUT");
BlGetConfigValue(L"TIMEOUT", &TimeOutString);
TimeOut = -1;
/* Check if timeout is specified */
@@ -72,14 +73,23 @@ BlDisplayBootMenu()
}
}
/* Set redraw flags to not redraw the menu itself, but fill it with entries */
RedrawBootMenu = FALSE;
RedrawEntries = TRUE;
/* Infinite boot menu loop */
while(TRUE)
{
/* Redraw boot menu */
BlpDrawBootMenu(&Handle);
/* Redraw boot menu frame if requested */
if(RedrawBootMenu)
{
BlpDrawBootMenu(&Handle);
RedrawBootMenu = FALSE;
RedrawEntries = TRUE;
}
/* Sanity check to ensure we do not display more entries than possible */
if (VisibleEntries > NumberOfEntries)
if(VisibleEntries > NumberOfEntries)
{
VisibleEntries = NumberOfEntries;
}
@@ -87,12 +97,19 @@ BlDisplayBootMenu()
/* Check if there is anything to show in the boot menu */
if(NumberOfEntries > 0)
{
/* Iterate through all menu entries */
for(Index = 0; Index < VisibleEntries; Index++)
/* Check if we need to redraw boot menu entries */
if(RedrawEntries)
{
/* Draw menu entry */
BlpDrawBootMenuEntry(&Handle, MenuEntries[TopVisibleEntry + Index].EntryName,
Index, (TopVisibleEntry + Index) == HighligtedEntryId);
/* Iterate through all menu entries */
for(Index = 0; Index < VisibleEntries; Index++)
{
/* Draw menu entry */
BlpDrawBootMenuEntry(&Handle, MenuEntries[TopVisibleEntry + Index].EntryName,
Index, (TopVisibleEntry + Index) == HighligtedEntryId);
}
/* Clear redraw entries flag */
RedrawEntries = FALSE;
}
}
else
@@ -126,6 +143,9 @@ BlDisplayBootMenu()
/* Flush keyboard buffer out of any keystrokes */
EfiSystemTable->ConIn->Reset(EfiSystemTable->ConIn, FALSE);
/* Store old highlighted entry */
OldHighligtedEntryId = HighligtedEntryId;
/* Infinite boot menu event loop */
while(TRUE)
{
@@ -157,7 +177,7 @@ BlDisplayBootMenu()
BlSetConsoleAttributes(Handle.DialogColor | Handle.TextColor);
BlClearConsoleLine(Handle.PosY + Handle.Height + 4);
BlSetCursorPosition(4, Handle.PosY + Handle.Height + 4);
BlConsolePrint(L"Booting '%S' now...\n", MenuEntries[HighligtedEntryId].EntryName);
BlConsolePrint(L"Booting '%S' now...\n", MenuEntries[HighligtedEntryId].FullName);
/* Boot the highlighted (chosen) OS */
Status = BlInvokeBootProtocol(MenuEntries[HighligtedEntryId].ShortName,
@@ -166,8 +186,9 @@ BlDisplayBootMenu()
{
/* Failed to boot OS */
BlDebugPrint(L"ERROR: Failed to boot '%S' (Status Code: 0x%zX)\n",
MenuEntries[HighligtedEntryId].EntryName, Status);
MenuEntries[HighligtedEntryId].FullName, Status);
BlDisplayErrorDialog(L"XTLDR", L"Failed to startup the selected Operating System.");
RedrawBootMenu = TRUE;
}
/* Break from boot menu event loop to redraw whole boot menu */
@@ -176,14 +197,26 @@ BlDisplayBootMenu()
else if(Key.ScanCode == 0x01)
{
/* UpArrow key pressed, go to previous entry if possible */
if (HighligtedEntryId > 0)
if(HighligtedEntryId > 0)
{
/* Highlight previous entry */
OldHighligtedEntryId = HighligtedEntryId;
HighligtedEntryId--;
if (HighligtedEntryId < TopVisibleEntry)
/* Check if we need to scroll the view */
if(HighligtedEntryId < TopVisibleEntry)
{
/* Scroll the view */
TopVisibleEntry = HighligtedEntryId;
RedrawEntries = TRUE;
break;
}
break;
/* Redraw new highlighted entry and the old one */
BlpDrawBootMenuEntry(&Handle, MenuEntries[OldHighligtedEntryId].EntryName,
OldHighligtedEntryId - TopVisibleEntry, FALSE);
BlpDrawBootMenuEntry(&Handle, MenuEntries[HighligtedEntryId].EntryName,
HighligtedEntryId - TopVisibleEntry, TRUE);
}
}
else if(Key.ScanCode == 0x02)
@@ -191,12 +224,24 @@ BlDisplayBootMenu()
/* DownArrow key pressed, go to next entry if possible */
if(HighligtedEntryId < NumberOfEntries - 1)
{
/* Highlight next entry */
OldHighligtedEntryId = HighligtedEntryId;
HighligtedEntryId++;
if (HighligtedEntryId >= TopVisibleEntry + VisibleEntries)
/* Check if we need to scroll the view */
if(HighligtedEntryId >= TopVisibleEntry + VisibleEntries)
{
/* Scroll the view */
TopVisibleEntry = HighligtedEntryId - VisibleEntries + 1;
RedrawEntries = TRUE;
break;
}
break;
/* Redraw new highlighted entry and the old one */
BlpDrawBootMenuEntry(&Handle, MenuEntries[OldHighligtedEntryId].EntryName,
OldHighligtedEntryId - TopVisibleEntry, FALSE);
BlpDrawBootMenuEntry(&Handle, MenuEntries[HighligtedEntryId].EntryName,
HighligtedEntryId - TopVisibleEntry, TRUE);
}
}
else if(Key.ScanCode == 0x09)
@@ -207,6 +252,7 @@ BlDisplayBootMenu()
/* Highlight first entry */
HighligtedEntryId = 0;
TopVisibleEntry = 0;
RedrawEntries = TRUE;
break;
}
}
@@ -218,6 +264,7 @@ BlDisplayBootMenu()
/* Highlight last entry */
HighligtedEntryId = NumberOfEntries - 1;
TopVisibleEntry = (NumberOfEntries > VisibleEntries) ? (NumberOfEntries - VisibleEntries) : 0;
RedrawEntries = TRUE;
break;
}
}
@@ -241,6 +288,7 @@ BlDisplayBootMenu()
L"Visit https://exectos.eu.org/ for more information.");
/* Break from boot menu event loop to redraw whole boot menu */
RedrawBootMenu = TRUE;
break;
}
else if(Key.ScanCode == 0x14)
@@ -248,6 +296,7 @@ BlDisplayBootMenu()
/* F10 key pressed, reboot into UEFI setup interface */
BlEnterFirmwareSetup();
BlDisplayErrorDialog(L"XTLDR", L"Reboot into firmware setup interface not supported!");
RedrawBootMenu = TRUE;
/* Break from boot menu event loop to redraw whole boot menu */
break;
@@ -257,6 +306,7 @@ BlDisplayBootMenu()
/* F11 key pressed, reboot the machine */
BlRebootSystem();
BlDisplayErrorDialog(L"XTLDR", L"Failed to reboot the machine!");
RedrawBootMenu = TRUE;
/* Break from boot menu event loop to redraw whole boot menu */
break;
@@ -266,6 +316,7 @@ BlDisplayBootMenu()
/* F12 key pressed, shutdown the machine */
BlShutdownSystem();
BlDisplayErrorDialog(L"XTLDR", L"Failed to shutdown the machine!");
RedrawBootMenu = TRUE;
/* Break from boot menu event loop to redraw whole boot menu */
break;
@@ -273,7 +324,8 @@ BlDisplayBootMenu()
else if(Key.UnicodeChar == 0x65)
{
/* 'e' key pressed, edit the highlighted entry */
BlDisplayErrorDialog(L"XTLDR", L"Editing boot menu entries is not implemented yet!");
BlDisplayEditMenu(&MenuEntries[HighligtedEntryId]);
RedrawBootMenu = TRUE;
/* Break from boot menu event loop to redraw whole boot menu */
break;
@@ -302,7 +354,7 @@ BlDisplayBootMenu()
BlSetConsoleAttributes(Handle.DialogColor | Handle.TextColor);
BlClearConsoleLine(Handle.PosY + Handle.Height + 4);
BlSetCursorPosition(4, Handle.PosY + Handle.Height + 4);
BlConsolePrint(L"Booting '%S' now...\n", MenuEntries[HighligtedEntryId].EntryName);
BlConsolePrint(L"Booting '%S' now...\n", MenuEntries[HighligtedEntryId].FullName);
/* Disable the timer just in case booting OS fails */
TimeOut = -1;
@@ -314,8 +366,9 @@ BlDisplayBootMenu()
{
/* Failed to boot OS */
BlDebugPrint(L"ERROR: Failed to boot '%S' (Status Code: 0x%zX)\n",
MenuEntries[HighligtedEntryId].EntryName, Status);
MenuEntries[HighligtedEntryId].FullName, Status);
BlDisplayErrorDialog(L"XTLDR", L"Failed to startup the selected Operating System.");
RedrawBootMenu = TRUE;
}
break;
}
@@ -324,6 +377,254 @@ BlDisplayBootMenu()
}
}
/**
* Displays a simple TUI-based edit menu.
*
* @return This routine does not return any value.
*
* @since XT 1.0
*/
XTCDECL
VOID
BlDisplayEditMenu(IN PXTBL_BOOTMENU_ITEM MenuEntry)
{
ULONG HighligtedOptionId, Index, NumberOfOptions, OldHighligtedOptionId, TopVisibleEntry, VisibleEntries;
XTBL_DIALOG_HANDLE Handle;
BOOLEAN RedrawEditMenu, RedrawEntries;
EFI_INPUT_KEY Key;
UINT_PTR EventIndex;
PWCHAR NewValue, OptionName, OriginalValue, Value, ValueToEdit;
CONST PWCHAR *EditableOptions;
EFI_STATUS Status;
/* Draw edit menu */
BlpDrawEditMenu(&Handle);
/* Get the list of user editable options */
BlGetEditableOptions(&EditableOptions, &NumberOfOptions);
/* Calculate how many entries can be visible in the menu box */
VisibleEntries = Handle.Height - 2;
/* Assume the first option is highlighted by default */
HighligtedOptionId = 0;
OldHighligtedOptionId = 0;
TopVisibleEntry = 0;
/* Set redraw flags to not redraw the menu itself, but fill it with entries */
RedrawEditMenu = FALSE;
RedrawEntries = TRUE;
/* Infinite edit menu loop */
while(TRUE)
{
/* Redraw edit menu frame if requested */
if(RedrawEditMenu)
{
BlpDrawEditMenu(&Handle);
RedrawEditMenu = FALSE;
RedrawEntries = TRUE;
}
/* Sanity check to ensure we do not display more entries than possible */
if(VisibleEntries > NumberOfOptions)
{
VisibleEntries = NumberOfOptions;
}
/* Check if we need to redraw boot menu entries */
if(RedrawEntries)
{
/* Iterate through all menu entries */
for(Index = 0; Index < VisibleEntries; Index++)
{
/* Draw menu entry */
BlGetBootOptionValue(MenuEntry->Options, EditableOptions[TopVisibleEntry + Index], &Value);
BlpDrawEditMenuEntry(&Handle, EditableOptions[TopVisibleEntry + Index], Value, Index,
(TopVisibleEntry + Index) == HighligtedOptionId);
/* Free allocated value string if needed */
if(Value != NULL)
{
BlFreeMemoryPool(Value);
}
}
/* Clear redraw entries flag */
RedrawEntries = FALSE;
}
/* Wait for EFI event and read key stroke */
BlWaitForEfiEvent(1, &EfiSystemTable->ConIn->WaitForKey, &EventIndex);
BlReadKeyStroke(&Key);
/* Check key press scan code */
if(Key.UnicodeChar == 0x0D || Key.UnicodeChar == 0x65)
{
/* ENTER or 'e' key pressed, edit the highlighted option */
OptionName = EditableOptions[HighligtedOptionId];
BlGetBootOptionValue(MenuEntry->Options, OptionName, &OriginalValue);
/* If the original value is NULL, use an empty string for editing */
if(OriginalValue == NULL)
{
ValueToEdit = L"";
}
else
{
ValueToEdit = OriginalValue;
}
/* Display input dialog to edit the option value */
NewValue = ValueToEdit;
BlDisplayInputDialog(OptionName, L"Enter new value:", &NewValue);
/* Check if the value was changed */
if(NewValue != ValueToEdit)
{
/* Update the boot option with the new value and free the old value */
BlSetBootOptionValue(MenuEntry->Options, OptionName, NewValue);
BlFreeMemoryPool(NewValue);
}
/* Free the original value if it was allocated */
if(OriginalValue != NULL)
{
BlFreeMemoryPool(OriginalValue);
}
/* Mark the edit menu for redraw */
RedrawEditMenu = TRUE;
}
else if(Key.ScanCode == 0x01)
{
/* UpArrow key pressed, go to previous entry if possible */
if(HighligtedOptionId > 0)
{
/* Highlight previous entry */
OldHighligtedOptionId = HighligtedOptionId;
HighligtedOptionId--;
/* Check if we need to scroll the view */
if(HighligtedOptionId < TopVisibleEntry)
{
/* Scroll the view */
TopVisibleEntry = HighligtedOptionId;
RedrawEntries = TRUE;
continue;
}
/* Redraw old highlighted entry */
BlGetBootOptionValue(MenuEntry->Options, EditableOptions[OldHighligtedOptionId], &Value);
BlpDrawEditMenuEntry(&Handle, EditableOptions[OldHighligtedOptionId], Value, OldHighligtedOptionId - TopVisibleEntry, FALSE);
/* Free allocated value string if needed */
if(Value != NULL)
{
BlFreeMemoryPool(Value);
}
/* Redraw new highlighted entry */
BlGetBootOptionValue(MenuEntry->Options, EditableOptions[HighligtedOptionId], &Value);
BlpDrawEditMenuEntry(&Handle, EditableOptions[HighligtedOptionId], Value, HighligtedOptionId - TopVisibleEntry, TRUE);
/* Free allocated value string if needed */
if(Value != NULL)
{
BlFreeMemoryPool(Value);
}
}
}
else if(Key.ScanCode == 0x02)
{
/* DownArrow key pressed, go to next entry if possible */
if(HighligtedOptionId < NumberOfOptions - 1)
{
/* Highlight next entry */
OldHighligtedOptionId = HighligtedOptionId;
HighligtedOptionId++;
/* Check if we need to scroll the view */
if(HighligtedOptionId >= TopVisibleEntry + VisibleEntries)
{
/* Scroll the view */
TopVisibleEntry = HighligtedOptionId - VisibleEntries + 1;
RedrawEntries = TRUE;
continue;
}
/* Redraw old highlighted entry */
BlGetBootOptionValue(MenuEntry->Options, EditableOptions[OldHighligtedOptionId], &Value);
BlpDrawEditMenuEntry(&Handle, EditableOptions[OldHighligtedOptionId], Value, OldHighligtedOptionId - TopVisibleEntry, FALSE);
/* Free allocated value string if needed */
if(Value != NULL)
{
BlFreeMemoryPool(Value);
}
/* Redraw new highlighted entry */
BlGetBootOptionValue(MenuEntry->Options, EditableOptions[HighligtedOptionId], &Value);
BlpDrawEditMenuEntry(&Handle, EditableOptions[HighligtedOptionId], Value, HighligtedOptionId - TopVisibleEntry, TRUE);
/* Free allocated value string if needed */
if(Value != NULL)
{
BlFreeMemoryPool(Value);
}
}
}
else if(Key.ScanCode == 0x09)
{
/* PageUp key pressed, go to top entry */
if(HighligtedOptionId != 0)
{
/* Highlight first entry */
HighligtedOptionId = 0;
TopVisibleEntry = 0;
RedrawEntries = TRUE;
}
}
else if(Key.ScanCode == 0x0A)
{
/* PageDown key pressed, go to bottom entry */
if(HighligtedOptionId != NumberOfOptions - 1)
{
/* Highlight last entry */
HighligtedOptionId = NumberOfOptions - 1;
TopVisibleEntry = (NumberOfOptions > VisibleEntries) ? (NumberOfOptions - VisibleEntries) : 0;
RedrawEntries = TRUE;
}
}
else if(Key.UnicodeChar == 0x02)
{
/* CTRL-B key pressed, boot the OS */
BlSetConsoleAttributes(Handle.DialogColor | Handle.TextColor);
BlClearConsoleLine(Handle.PosY + Handle.Height + 4);
BlSetCursorPosition(4, Handle.PosY + Handle.Height + 4);
BlConsolePrint(L"Booting '%S' now...\n", MenuEntry->FullName);
/* Boot the OS */
Status = BlInvokeBootProtocol(MenuEntry->ShortName, MenuEntry->Options);
if(Status != STATUS_SUCCESS)
{
/* Failed to boot OS */
BlDebugPrint(L"ERROR: Failed to boot '%S' (Status Code: 0x%zX)\n", MenuEntry->FullName, Status);
BlDisplayErrorDialog(L"XTLDR", L"Failed to startup the selected Operating System.");
RedrawEditMenu = TRUE;
}
/* Return to the edit menu */
continue;
}
else if(Key.ScanCode == 0x17)
{
/* ESC key pressed, exit edit menu */
break;
}
}
}
/**
* Displays a red error dialog box with the specified caption and message.
*
@@ -450,12 +751,11 @@ XTCDECL
VOID
BlDisplayInputDialog(IN PWCHAR Caption,
IN PWCHAR Message,
IN PWCHAR *InputFieldText)
IN OUT PWCHAR *InputFieldText)
{
SIZE_T InputFieldLength, TextCursorPosition, TextIndex, TextPosition;
XTBL_DIALOG_HANDLE Handle;
PWCHAR InputFieldBuffer;
SIZE_T BufferLength;
EFI_INPUT_KEY Key;
EFI_STATUS Status;
UINT_PTR Index;
@@ -480,9 +780,11 @@ BlDisplayInputDialog(IN PWCHAR Caption,
Key.ScanCode = 0;
Key.UnicodeChar = 0;
/* Get initial input text length and allocate a buffer */
BufferLength = RtlWideStringLength(*InputFieldText, 0);
Status = BlAllocateMemoryPool(BufferLength * sizeof(WCHAR), (PVOID *)&InputFieldBuffer);
/* Determine input field length */
InputFieldLength = RtlWideStringLength(*InputFieldText, 0);
/* Allocate a buffer for storing the input field text */
Status = BlAllocateMemoryPool(2048 * sizeof(WCHAR), (PVOID *)&InputFieldBuffer);
if(Status != STATUS_EFI_SUCCESS)
{
/* Memory allocation failure, print error message and return */
@@ -492,15 +794,8 @@ BlDisplayInputDialog(IN PWCHAR Caption,
}
/* Copy input text into edit buffer */
RtlCopyMemory(InputFieldBuffer, *InputFieldText, BufferLength * sizeof(WCHAR));
InputFieldBuffer[BufferLength] = L'\0';
/* Determine input field length */
InputFieldLength = BufferLength;
if(InputFieldLength > Handle.Width - 8)
{
InputFieldLength = Handle.Width - 8;
}
RtlCopyMemory(InputFieldBuffer, *InputFieldText, InputFieldLength * sizeof(WCHAR));
InputFieldBuffer[InputFieldLength] = L'\0';
/* Start at first character */
TextPosition = 0;
@@ -512,7 +807,6 @@ BlDisplayInputDialog(IN PWCHAR Caption,
/* Wait for key press and read key stroke */
BlWaitForEfiEvent(1, &EfiSystemTable->ConIn->WaitForKey, &Index);
BlReadKeyStroke(&Key);
BlResetConsoleInputBuffer();
/* Check key press scan code */
if(Key.ScanCode == 0x17)
@@ -563,12 +857,16 @@ BlDisplayInputDialog(IN PWCHAR Caption,
/* DELETE key pressed, delete character */
if(Handle.Attributes & XTBL_TUI_DIALOG_ACTIVE_INPUT)
{
/* Check if buffer is not empty */
if(InputFieldLength > 0 && TextPosition < InputFieldLength)
{
/* Delete character */
RtlMoveMemory(InputFieldBuffer + TextPosition, InputFieldBuffer + TextPosition + 1,
(InputFieldLength - TextPosition) * sizeof(WCHAR));
/* Decrement length and null terminate string */
InputFieldLength--;
InputFieldBuffer[InputFieldLength] = 0;
InputFieldBuffer[InputFieldLength] = L'\0';
}
}
}
@@ -577,13 +875,17 @@ BlDisplayInputDialog(IN PWCHAR Caption,
/* BACKSPACE key pressed, delete character */
if(Handle.Attributes & XTBL_TUI_DIALOG_ACTIVE_INPUT)
{
/* Check if buffer is not empty */
if(InputFieldLength > 0 && TextPosition > 0 && TextPosition <= InputFieldLength)
{
/* Move memory to overwrite the character to the left of the cursor */
RtlMoveMemory(InputFieldBuffer + TextPosition - 1, InputFieldBuffer + TextPosition,
(InputFieldLength - TextPosition + 1) * sizeof(WCHAR));
/* Decrement length, position and null terminate string */
TextPosition--;
RtlMoveMemory(InputFieldBuffer + TextPosition, InputFieldBuffer + TextPosition + 1,
(InputFieldLength - TextPosition) * sizeof(WCHAR));
InputFieldLength--;
InputFieldBuffer[InputFieldLength] = 0;
InputFieldBuffer[InputFieldLength] = L'\0';
}
}
}
@@ -598,15 +900,23 @@ BlDisplayInputDialog(IN PWCHAR Caption,
/* Other key pressed, add character to the buffer */
if(Handle.Attributes & XTBL_TUI_DIALOG_ACTIVE_INPUT && Key.UnicodeChar != 0)
{
RtlMoveMemory(InputFieldBuffer + TextPosition + 1, InputFieldBuffer + TextPosition,
(InputFieldLength - TextPosition) * sizeof(WCHAR));
InputFieldBuffer[TextPosition] = Key.UnicodeChar;
TextPosition++;
InputFieldLength++;
InputFieldBuffer[InputFieldLength] = 0;
/* Check if buffer is full */
if(InputFieldLength < 2047)
{
/* Insert character at current position */
RtlMoveMemory(InputFieldBuffer + TextPosition + 1, InputFieldBuffer + TextPosition,
(InputFieldLength - TextPosition) * sizeof(WCHAR));
InputFieldBuffer[TextPosition] = Key.UnicodeChar;
/* Increment length, position and null terminate string */
TextPosition++;
InputFieldLength++;
InputFieldBuffer[InputFieldLength] = L'\0';
}
}
}
/* Calculate text index and cursor position */
if(TextPosition > (Handle.Width - 9))
{
TextIndex = TextPosition - (Handle.Width - 9);
@@ -622,6 +932,7 @@ BlDisplayInputDialog(IN PWCHAR Caption,
BlpDrawDialogButton(&Handle);
BlpDrawDialogInputField(&Handle, &InputFieldBuffer[TextIndex]);
/* Set cursor position if input field is active */
if(Handle.Attributes & XTBL_TUI_DIALOG_ACTIVE_INPUT)
{
BlSetCursorPosition(Handle.PosX + 4 + TextCursorPosition, Handle.PosY + Handle.Height - 4);
@@ -1340,3 +1651,164 @@ BlpDrawDialogProgressBar(IN PXTBL_DIALOG_HANDLE Handle,
BlDisableConsoleCursor();
BlConsoleWrite(ProgressBar);
}
/**
* Draws a text-based boot edition menu.
*
* @param Handle
* Supplies a pointer to the edition menu handle.
*
* @return This function does not return any value.
*
* @since XT 1.0
*/
XTCDECL
VOID
BlpDrawEditMenu(OUT PXTBL_DIALOG_HANDLE Handle)
{
/* Query console screen resolution */
BlQueryConsoleMode(&Handle->ResX, &Handle->ResY);
/* Set boot menu parameters */
Handle->Attributes = 0;
Handle->DialogColor = EFI_TEXT_BGCOLOR_BLACK;
Handle->TextColor = EFI_TEXT_FGCOLOR_LIGHTGRAY;
Handle->PosX = 3;
Handle->PosY = 3;
Handle->Width = Handle->ResX - 6;
Handle->Height = Handle->ResY - 10;
/* Clear screen and disable cursor */
BlSetConsoleAttributes(Handle->DialogColor | Handle->TextColor);
BlClearConsoleScreen();
BlDisableConsoleCursor();
/* Check if debugging enabled */
if(DEBUG)
{
/* Print debug version of XTLDR banner */
BlSetCursorPosition((Handle->ResX - 44) / 2, 1);
BlConsolePrint(L"XTLDR Boot Loader v%d.%d (%s-%s)\n",
XTLDR_VERSION_MAJOR, XTLDR_VERSION_MINOR, XTOS_VERSION_DATE, XTOS_VERSION_HASH);
}
else
{
/* Print standard XTLDR banner */
BlSetCursorPosition((Handle->ResX - 22) / 2, 1);
BlConsolePrint(L"XTLDR Boot Loader v%d.%d\n", XTLDR_VERSION_MAJOR, XTLDR_VERSION_MINOR);
}
/* Draw empty dialog box for boot menu */
BlpDrawDialogBox(Handle, L"Edit Options", NULL);
/* Print help message below the edit menu */
BlSetCursorPosition(0, Handle->PosY + Handle->Height);
BlSetConsoleAttributes(EFI_TEXT_BGCOLOR_BLACK | EFI_TEXT_FGCOLOR_LIGHTGRAY);
BlConsolePrint(L" Use cursors to change the selection. Press ENTER key to edit the chosen\n"
L" option, ESC to return to the main boot menu or CTRL-B to boot.\n");
}
/**
* Draws edit menu entry at the specified position.
*
* @param Handle
* Supplies a pointer to the boot menu handle.
*
* @param OptionName
* Supplies a pointer to the buffer containing a part of the menu entry name (an option name).
*
* @param OptionValue
* Supplies a pointer to the buffer containing a part of the menu entry name (an option value).
*
* @param Position
* Specifies entry position on the list in the boot menu.
*
* @param Highlighted
* Specifies whether this entry should be highlighted or not.
*
* @return This routine does not return any value.
*
* @since XT 1.0
*/
XTCDECL
EFI_STATUS
BlpDrawEditMenuEntry(IN PXTBL_DIALOG_HANDLE Handle,
IN PWCHAR OptionName,
IN PWCHAR OptionValue,
IN UINT Position,
IN BOOLEAN Highlighted)
{
BOOLEAN Allocation;
PWCHAR DisplayValue, ShortValue;
UINT Index;
ULONG OptionNameLength, OptionValueLength, OptionWidth;
EFI_STATUS Status;
/* Assume no allocation was made */
Allocation = FALSE;
/* Set display value depending on input */
DisplayValue = (OptionValue != NULL) ? OptionValue : L"";
/* Determine lengths */
OptionNameLength = RtlWideStringLength(OptionName, 0);
OptionValueLength = RtlWideStringLength(DisplayValue, 0);
OptionWidth = Handle->Width - 4 - (OptionNameLength + 2);
/* Check if value needs to be truncated */
if(OptionValueLength > OptionWidth)
{
/* Allocate buffer for new, shortened value */
Status = BlAllocateMemoryPool((OptionWidth + 1) * sizeof(WCHAR), (PVOID *)&ShortValue);
if(Status != STATUS_EFI_SUCCESS)
{
/* Memory allocation failure, print debug message and return */
BlDebugPrint(L"ERROR: Memory allocation failure (Status Code: 0x%zX)\n", Status);
return Status;
}
/* Copy a desired value length into the allocated buffer and append "..." */
RtlCopyMemory(ShortValue, DisplayValue, (OptionWidth - 3) * sizeof(WCHAR));
RtlCopyMemory(ShortValue + OptionWidth - 3, L"...", 3 * sizeof(WCHAR));
ShortValue[OptionWidth] = L'\0';
/* Mark that allocation was made and set new display value */
Allocation = TRUE;
DisplayValue = ShortValue;
}
/* Move cursor to the right position */
BlSetCursorPosition(5, 4 + Position);
/* Check whether this entry should be highlighted */
if(Highlighted)
{
/* Highlight this entry */
BlSetConsoleAttributes(EFI_TEXT_BGCOLOR_LIGHTGRAY | EFI_TEXT_FGCOLOR_BLACK);
}
else
{
/* Set default colors */
BlSetConsoleAttributes(EFI_TEXT_BGCOLOR_BLACK | EFI_TEXT_FGCOLOR_LIGHTGRAY);
}
/* Clear menu entry */
for(Index = 0; Index < Handle->Width - 4; Index++)
{
BlConsolePrint(L" ");
}
/* Print menu entry */
BlSetCursorPosition(5, 4 + Position);
BlConsolePrint(L"%S: %S", OptionName, DisplayValue);
/* Check if allocation was made */
if(Allocation)
{
/* Free allocated memory */
BlFreeMemoryPool(DisplayValue);
}
/* Return success */
return STATUS_EFI_SUCCESS;
}

View File

@@ -48,7 +48,11 @@ XTCDECL
EFI_STATUS
BlEnumerateBlockDevices()
{
PEFI_DEVICE_PATH_PROTOCOL LastNode = NULL;
EFI_GUID LoadedImageProtocolGuid = EFI_LOADED_IMAGE_PROTOCOL_GUID;
EFI_GUID BlockIoGuid = EFI_BLOCK_IO_PROTOCOL_GUID;
EFI_HANDLE BootDeviceHandle = NULL, DeviceHandle = NULL;
EFI_LOADED_IMAGE_PROTOCOL* LoadedImage;
PEFI_DEVICE_PATH_PROTOCOL DevicePath = NULL, LastNode = NULL;
PEFI_BLOCK_DEVICE_DATA ParentNode = NULL;
PEFI_BLOCK_DEVICE_DATA BlockDeviceData;
PEFI_BLOCK_DEVICE BlockDevice;
@@ -63,6 +67,18 @@ BlEnumerateBlockDevices()
USHORT DriveType;
ULONG CDCount = 0, FDCount = 0, HDCount = 0, RDCount = 0;
/* Get the device handle of the image that is running */
Status = EfiSystemTable->BootServices->HandleProtocol(EfiImageHandle, &LoadedImageProtocolGuid, (VOID**)&LoadedImage);
if(Status != STATUS_EFI_SUCCESS)
{
/* Failed to get boot device handle */
BlDebugPrint(L"ERROR: Failed to get boot device handle (Status Code: 0x%zX)\n", Status);
return Status;
}
/* Save the boot device handle */
BootDeviceHandle = LoadedImage->DeviceHandle;
/* Initialize list entries */
RtlInitializeListHead(&BlockDevices);
RtlInitializeListHead(&EfiBlockDevices);
@@ -81,6 +97,7 @@ BlEnumerateBlockDevices()
{
/* Get data for the next discovered device. */
BlockDeviceData = CONTAIN_RECORD(ListEntry, EFI_BLOCK_DEVICE_DATA, ListEntry);
PartitionGuid = NULL;
/* Find last node */
Status = BlpFindLastBlockDeviceNode(BlockDeviceData->DevicePath, &LastNode);
@@ -154,11 +171,30 @@ BlEnumerateBlockDevices()
PartitionNumber = HDPath->PartitionNumber;
PartitionGuid = (PEFI_GUID)HDPath->Signature;
/* Check if this is the EFI System Partition (ESP) */
if(BootDeviceHandle != NULL)
{
/* Allocate memory for device path */
DevicePath = BlpDuplicateDevicePath(BlockDeviceData->DevicePath);
if(DevicePath != NULL)
{
/* Check if this is the boot device */
Status = EfiSystemTable->BootServices->LocateDevicePath(&BlockIoGuid, &DevicePath,
&DeviceHandle);
if(Status == STATUS_EFI_SUCCESS && DeviceHandle == BootDeviceHandle)
{
/* Mark partition as ESP */
DriveType |= XTBL_BOOT_DEVICE_ESP;
}
}
}
/* Print debug message */
BlDebugPrint(L"Found Hard Disk partition (DiskNumber: %lu, PartNumber: %lu, "
L"MBRType: %u, GUID: {%V}, PartSize: %uB)\n",
L"MBRType: %u, GUID: {%V}, PartSize: %lluB) %S\n",
DriveNumber, PartitionNumber, HDPath->MBRType,
PartitionGuid, HDPath->PartitionSize * Media->BlockSize);
PartitionGuid, HDPath->PartitionSize * Media->BlockSize,
(DriveType & XTBL_BOOT_DEVICE_ESP) ? L"(ESP)" : L"");
}
else if(LastNode->Type == EFI_MEDIA_DEVICE_PATH && LastNode->SubType == EFI_MEDIA_RAMDISK_DP)
{
@@ -428,12 +464,26 @@ BlGetVolumeDevicePath(IN PWCHAR SystemPath,
{
/* Check if this is the volume we are looking for */
Device = CONTAIN_RECORD(ListEntry, EFI_BLOCK_DEVICE, ListEntry);
if((Device->DriveType == DriveType && Device->DriveNumber == DriveNumber &&
Device->PartitionNumber == PartNumber))
if(DriveType == XTBL_BOOT_DEVICE_ESP)
{
/* Found volume */
*DevicePath = Device->DevicePath;
break;
/* ESP requested, verify if flag is set for this device */
if((Device->DriveType & XTBL_BOOT_DEVICE_ESP) != 0)
{
/* Found volume */
*DevicePath = Device->DevicePath;
break;
}
}
else
{
if(((Device->DriveType & DriveType) == DriveType) &&
(Device->DriveNumber == DriveNumber) &&
(Device->PartitionNumber == PartNumber))
{
/* Found volume */
*DevicePath = Device->DevicePath;
break;
}
}
ListEntry = ListEntry->Flink;
}
@@ -441,9 +491,9 @@ BlGetVolumeDevicePath(IN PWCHAR SystemPath,
/* Check if volume was found */
if(*DevicePath == NULL)
{
/* Failed to find volume */
/* Volume not found */
BlDebugPrint(L"ERROR: Volume (DriveType: %u, DriveNumber: %lu, PartNumber: %lu) not found\n",
DriveType, DriveNumber, PartNumber);
DriveType, DriveNumber, PartNumber);
return STATUS_EFI_NOT_FOUND;
}
@@ -616,7 +666,7 @@ BlReadFile(IN PEFI_FILE_HANDLE DirHandle,
Pages = EFI_SIZE_TO_PAGES(FileInfo->FileSize);
/* Allocate pages */
Status = BlAllocateMemoryPages(Pages, &Address);
Status = BlAllocateMemoryPages(AllocateAnyPages, Pages, &Address);
if(Status != STATUS_EFI_SUCCESS)
{
/* Pages allocation failure */
@@ -786,6 +836,12 @@ BlpDissectVolumeArcPath(IN PWCHAR SystemPath,
ArcLength = 10;
*DriveType = XTBL_BOOT_DEVICE_RAMDISK;
}
else if(RtlCompareWideStringInsensitive(SystemPath, L"multi(0)esp(0)", 0) == 0)
{
/* This is ESP */
ArcLength = 14;
*DriveType = XTBL_BOOT_DEVICE_ESP;
}
else if(RtlCompareWideStringInsensitive(SystemPath, L"multi(0)disk(0)", 0) == 0)
{
/* This is a multi-disk port */
@@ -1047,6 +1103,14 @@ BlpFindParentBlockDevice(IN PLIST_ENTRY BlockDevices,
/* Take block device from the list */
BlockDeviceData = CONTAIN_RECORD(ListEntry, EFI_BLOCK_DEVICE_DATA, ListEntry);
/* A device cannot be its own parent */
if (BlockDeviceData == ChildNode)
{
/* Move to the next device */
ListEntry = ListEntry->Flink;
continue;
}
ChildDevicePath = ChildNode->DevicePath;
ParentDevicePath = BlockDeviceData->DevicePath;
@@ -1065,10 +1129,11 @@ BlpFindParentBlockDevice(IN PLIST_ENTRY BlockDevices,
ChildLength = *(PUSHORT)ChildDevicePath->Length;
ParentLength = *(PUSHORT)ParentDevicePath->Length;
/* Check if lengths match */
if(ChildLength != ParentLength)
/* Check if nodes match */
if((ChildLength != ParentLength) ||
(RtlCompareMemory(ChildDevicePath, ParentDevicePath, ParentLength) != ParentLength))
{
/* Lengths do not match, this is not a valid parent */
/* Nodes do not match, this is not a valid parent */
break;
}

View File

@@ -90,16 +90,17 @@ BlInitializeBootLoader()
*/
XTCDECL
EFI_STATUS
BlInitializeBootMenuList(OUT PXTBL_BOOTMENU_ITEM *MenuEntries,
BlInitializeBootMenuList(IN ULONG MaxNameLength,
OUT PXTBL_BOOTMENU_ITEM *MenuEntries,
OUT PULONG EntriesCount,
OUT PULONG DefaultId)
{
EFI_GUID VendorGuid = XT_BOOT_LOADER_PROTOCOL_GUID;
PWCHAR DefaultMenuEntry, LastBooted, MenuEntryName;
PWCHAR DefaultMenuEntry, LastBooted, MenuEntryName, VisibleName;
PLIST_ENTRY MenuEntrySectionList, MenuEntryList;
PXTBL_CONFIG_SECTION MenuEntrySection;
PXTBL_CONFIG_ENTRY MenuEntryOption;
ULONG DefaultOS, NumberOfEntries;
ULONG DefaultOS, NameLength,NumberOfEntries;
PXTBL_BOOTMENU_ITEM OsList;
EFI_STATUS Status;
@@ -108,7 +109,7 @@ BlInitializeBootMenuList(OUT PXTBL_BOOTMENU_ITEM *MenuEntries,
NumberOfEntries = 0;
/* Get default menu entry from configuration */
DefaultMenuEntry = BlGetConfigValue(L"DEFAULT");
BlGetConfigValue(L"DEFAULT", &DefaultMenuEntry);
/* Check if configuration allows to use last booted OS */
if(BlGetConfigBooleanValue(L"KEEPLASTBOOT"))
@@ -177,10 +178,36 @@ BlInitializeBootMenuList(OUT PXTBL_BOOTMENU_ITEM *MenuEntries,
}
/* Add OS to the boot menu list */
OsList[NumberOfEntries].EntryName = MenuEntryName;
OsList[NumberOfEntries].FullName = MenuEntryName;
OsList[NumberOfEntries].ShortName = MenuEntrySection->SectionName;
OsList[NumberOfEntries].Options = &MenuEntrySection->Options;
/* Check if the menu entry name fits the maximum length */
NameLength = RtlWideStringLength(MenuEntryName, 0);
if(NameLength > MaxNameLength)
{
/* Menu entry name is too long, allocate memory for shorter name visible in the boot menu */
Status = BlAllocateMemoryPool((MaxNameLength + 1) * sizeof(WCHAR), (PVOID*)&VisibleName);
if(Status != STATUS_EFI_SUCCESS)
{
/* Memory allocation failure */
return STATUS_EFI_OUT_OF_RESOURCES;
}
/* Copy shorter name and append "..." at the end */
RtlCopyMemory(VisibleName, MenuEntryName, (MaxNameLength - 3) * sizeof(WCHAR));
RtlCopyMemory(VisibleName + MaxNameLength - 3, L"...", 3 * sizeof(WCHAR));
VisibleName[MaxNameLength] = L'\0';
/* Set visible menu entry name */
OsList[NumberOfEntries].EntryName = VisibleName;
}
else
{
/* Menu entry name fits the maximum length, use it as is */
OsList[NumberOfEntries].EntryName = MenuEntryName;
}
/* Get next menu entry */
MenuEntrySectionList = MenuEntrySectionList->Flink;
NumberOfEntries++;
@@ -364,6 +391,7 @@ EFI_STATUS
BlStartXtLoader(IN EFI_HANDLE ImageHandle,
IN PEFI_SYSTEM_TABLE SystemTable)
{
PWCHAR Modules;
EFI_STATUS Status;
/* Set the system table and image handle */
@@ -428,8 +456,9 @@ BlStartXtLoader(IN EFI_HANDLE ImageHandle,
return Status;
}
/* Load boot loader modules */
Status = BlLoadModules(BlGetConfigValue(L"MODULES"));
/* Load all necessary modules */
BlGetConfigValue(L"MODULES", &Modules);
Status = BlLoadModules(Modules);
if(Status != STATUS_EFI_SUCCESS)
{
/* Failed to load modules */

View File

@@ -9,6 +9,7 @@ include_directories(
# Specify list of library source code files
list(APPEND LIBXTOS_SOURCE
${XTOSKRNL_SOURCE_DIR}/ar/${ARCH}/boot.S
${XTOSKRNL_SOURCE_DIR}/ar/${ARCH}/cpufunc.c
${XTOSKRNL_SOURCE_DIR}/hl/cport.c
${XTOSKRNL_SOURCE_DIR}/hl/${ARCH}/ioport.c
@@ -23,6 +24,7 @@ list(APPEND LIBXTOS_SOURCE
# Specify list of kernel source code files
list(APPEND XTOSKRNL_SOURCE
${XTOSKRNL_SOURCE_DIR}/ar/${ARCH}/archsup.S
${XTOSKRNL_SOURCE_DIR}/ar/${ARCH}/boot.S
${XTOSKRNL_SOURCE_DIR}/ar/${ARCH}/cpufunc.c
${XTOSKRNL_SOURCE_DIR}/ar/${ARCH}/globals.c
${XTOSKRNL_SOURCE_DIR}/ar/${ARCH}/procsup.c
@@ -37,10 +39,14 @@ list(APPEND XTOSKRNL_SOURCE
${XTOSKRNL_SOURCE_DIR}/hl/${ARCH}/pic.c
${XTOSKRNL_SOURCE_DIR}/hl/${ARCH}/ioport.c
${XTOSKRNL_SOURCE_DIR}/hl/${ARCH}/runlevel.c
${XTOSKRNL_SOURCE_DIR}/kd/dbginit.c
${XTOSKRNL_SOURCE_DIR}/kd/dbgio.c
${XTOSKRNL_SOURCE_DIR}/kd/globals.c
${XTOSKRNL_SOURCE_DIR}/ke/apc.c
${XTOSKRNL_SOURCE_DIR}/ke/dpc.c
${XTOSKRNL_SOURCE_DIR}/ke/event.c
${XTOSKRNL_SOURCE_DIR}/ke/globals.c
${XTOSKRNL_SOURCE_DIR}/ke/info.c
${XTOSKRNL_SOURCE_DIR}/ke/kprocess.c
${XTOSKRNL_SOURCE_DIR}/ke/krnlinit.c
${XTOSKRNL_SOURCE_DIR}/ke/kthread.c
@@ -60,8 +66,10 @@ list(APPEND XTOSKRNL_SOURCE
${XTOSKRNL_SOURCE_DIR}/mm/init.c
${XTOSKRNL_SOURCE_DIR}/mm/kpools.c
${XTOSKRNL_SOURCE_DIR}/mm/pages.c
${XTOSKRNL_SOURCE_DIR}/mm/${ARCH}/globals.c
${XTOSKRNL_SOURCE_DIR}/mm/${ARCH}/init.c
${XTOSKRNL_SOURCE_DIR}/mm/${ARCH}/pages.c
${XTOSKRNL_SOURCE_DIR}/mm/${ARCH}/pmap.c
${XTOSKRNL_SOURCE_DIR}/po/idle.c
${XTOSKRNL_SOURCE_DIR}/rtl/atomic.c
${XTOSKRNL_SOURCE_DIR}/rtl/bitmap.c

View File

@@ -1,58 +1,68 @@
## XTOSKRNL
XTOSKRNL is an XT system kernel executable, providing the kernel and executive layers for XTOS kernel space. It is
a fundamental part of ExectOS, responsible for various core services like hardware abstraction or memory management.
This kernel, contains the scheduler (called sometimes as Dispatcher), cache, object and memory managers, security
manager and other kernel executives described below.
XTOSKRNL is the core kernel executable for ExectOS, providing the fundamental kernel and executive layers that operate
within the XTOS kernel space. It is responsible for various core services, such as hardware abstraction, memory
management, and process scheduling. The kernel contains the scheduler (sometimes referred to as the Dispatcher), the
cache, object, and memory managers, the security manager, and other executive components described below.
All routines in kernel are prefixed to indicate the kernel subsystem they belong and put inside separate directory.
This is a list of them:
All routines in the kernel are prefixed to indicate the subsystem they belong to, and their source code is organized
into corresponding directories. These subsystems include:
* Ar - Architecture library
* Ar - Architecture-specific Library
* Ex - Kernel Executive
* Hl - Hardware Layer
* Ke - Core kernel library
* Mm - Memory manager
* Kd - Kernel Debugger
* Ke - Core Kernel Library
* Mm - Memory Manager
* Po - Plug&Play and Power Manager
* Rtl - Runtime library
### AR: Architecture Library
This module contains processor architecture specific functions. This includes enabling and disabling interrupts at
the processor, getting the address of a page fault, getting CPUID information, and performing very early processor
initialization. This module does not contain any manufacturer or board-specific code, only CPU architecture specific
code.
This module contains functions specific to the processor architecture. These include routines for enabling and disabling
interrupts, retrieving the faulting address on a page fault, querying CPUID information, and performing very early
processor initialization. This module contains only CPU architecture-specific code, with no manufacturer or
board-specific implementations.
### EX: Kernel Executive
The kernel executive supplies heap management, including support for allocating system memory from paged/non-paged
pools, as well as synchronization primitives like push locks and fast mutexes, interlocked memory access, and worker
threads.
The Kernel Executive provides services for allocating system memory from paged and non-paged pools. It also supplies
synchronization primitives such as pushlocks and fast mutexes, routines for interlocked memory access, and support for
worker threads.
### HL: Hardware Layer
Hardware Layer, is a layer between the physical hardware of the computer and the rest of the operating system. It was
designed to hide differences in hardware and therefore it provides a consistent platform on which the system and
applications may run.
The Hardware Layer is an abstraction layer between the physical hardware and the rest of the operating system. It is
designed to abstract away hardware differences, providing a consistent platform on which the kernel and applications
can run.
### KD: Kernel Debugger
The Kernel Debugger (KD) subsystem provides debugging support for the kernel. The KD is initialized early in the boot
process to facilitate debugging from the very beginning of the kernel's execution.
### KE: Kernel Library
The kernel implements its core functionality that everything else in the system depends upon. This includes basic
low-level operations such as routing hardware interrupts.
The Core Kernel Library implements the core functionality upon which the rest of the system depends. This includes
fundamental low-level operations, such as routing hardware interrupts and managing dispatcher objects.
### MM: Memory Manager
Memory Manager is one of core subsystems. It manages virtual memory, controls memory protection and the paging of memory
in and out of physical memory to secondary storage. It also implements a general-purpose allocator of physical memory.
The Memory Manager is one of the core subsystems. It manages virtual memory, controls memory protection, and
handles paging memory between physical RAM and secondary storage. It also implements a general-purpose allocator for
physical memory.
### PO: Plug&Play and Power Manager
This subsystem deals with power events, such as power-off, stand-by, or hibernate. It also handles Plug&Play and
supports device detection and installation at boot time. It is responsible for starting and stopping devices on demand.
This subsystem handles power management events, such as shutdown or standby. It also manages Plug and Play (PnP),
supporting device detection and installation at boot time. Furthermore, it is responsible for starting and stopping
devices on demand.
### RTL: Runtime Library
This is a required static copy of C runtime objects. It includes many utility functions that can be used by native
applications.
The Runtime Library provides a kernel-mode implementation of common C library functions. It includes many utility
routines, for use by other kernel components.
## Functions Naming Convention
When naming a kernel functions, certain conventions are used. The function name is usually structured with
&lt;Prefix&gt;&lt;Operation&gt;&lt;Object&gt;. The prefix denotes the module to which it belongs, thus module
can be identified simply by the name of the function. Additionally, the prefix identifies the function visibility
as well. Thus all private functions, that should not be used from outside of the module has added "p" suffix to
the prefix. For example, KepInitializeStack() routine:
* Kep - prefix meaning this is private routine belonging to Kernel library (Ke) module,
* Initialize - operation this function does with the object,
* Stack - the object is stack.
## Function Naming Convention
All kernel functions adhere to a strict naming convention to enhance code readability and maintainability. The structure
of a function name is generally composed of three parts: &lt;Prefix&gt;&lt;Operation&gt;&lt;Object&gt;
The prefix identifies the component to which the function belongs. Additionally, the prefix indicates the function's
visibility. Private functions, which should not be called from outside their own module, have a 'p' appended to their
prefix.
For example, consider the **KepInitializeStack()** routine:
* **Kep** - The prefix indicates a private (p) routine belonging to the Core Kernel Library (Ke).
* **Initialize** - The operation performed by the function.
* **Stack** - The object on which the operation is performed.

View File

@@ -13,7 +13,7 @@
/**
* This macro creates a trap handler for the specified vector.
* Creates a trap handler for the specified vector.
*
* @param Vector
* Supplies a trap vector number.

133
xtoskrnl/ar/amd64/boot.S Normal file
View File

@@ -0,0 +1,133 @@
/**
* PROJECT: ExectOS
* COPYRIGHT: See COPYING.md in the top level directory
* FILE: xtoskrnl/ar/amd64/boot.S
* DESCRIPTION: AMD64-specific boot code for setting up the low-level CPU environment
* DEVELOPERS: Aiken Harris <harraiken91@gmail.com>
*/
#include <amd64/asmsup.h>
.altmacro
.text
/**
* Enables eXtended Physical Addressing (XPA).
*
* @param PageMap
* Supplies a pointer to the page map to be used.
*
* @return This routine does not return any value.
*
* @since XT 1.0
*/
.global ArEnableExtendedPhysicalAddressing
ArEnableExtendedPhysicalAddressing:
/* Save the original CR4 register */
movq %cr4, %rax
/* Save the state of stack pointer and non-volatile registers */
movq %rsp, XpaRegisterSaveArea(%rip)
movq %rbp, XpaRegisterSaveArea+0x08(%rip)
movq %rax, XpaRegisterSaveArea+0x10(%rip)
movq %rbx, XpaRegisterSaveArea+0x18(%rip)
/* Save the original CR0 register */
movq %cr0, %rbp
/* Load temporary GDT required for mode transitions */
leaq XpaTemporaryGdtDesc(%rip), %rax
movq %rax, XpaTemporaryGdtBase(%rip)
lgdtq XpaTemporaryGdtSize(%rip)
/* Load addresses for entering compatibility mode and re-entering long mode */
leaq XpaEnterCompatMode(%rip), %rax
leaq XpaEnterLongMode(%rip), %rbx
/* Push the 32-bit code segment selector and the target address for a far jump */
pushq $GDT_R0_CMCODE
pushq %rax
/* Perform a far return to switch to 32-bit compatibility mode */
lretq
XpaEnterCompatMode:
/* Enter 32-bit compatibility mode */
.code32
/* Store the PageMap pointer on the stack for future use */
pushl %ecx
/* Set the stack segment to the 32-bit data segment selector */
movl $GDT_R0_DATA, %eax
movl %eax, %ss
/* Disable PGE and PCIDE to ensure all TLB entries will be flushed */
movl %cr4, %eax
andl $~(CR4_PGE | CR4_PCIDE), %eax
movl %eax, %cr4
/* Temporarily disable paging */
movl %ebp, %eax
andl $~CR0_PG, %eax
movl %eax, %cr0
/* Disable Long Mode as prerequisite for enabling 5-level paging */
movl $X86_MSR_EFER, %ecx
rdmsr
andl $~X86_MSR_EFER_LME, %eax
wrmsr
/* Transition to 5-level paging (PML5/LA57) */
movl %cr4, %eax
orl $CR4_LA57, %eax
movl %eax, %cr4
/* Restore the PageMap pointer from the stack and load it into CR3 */
popl %ecx
movl %ecx, %cr3
/* Re-enable Long Mode */
movl $X86_MSR_EFER, %ecx
rdmsr
orl $X86_MSR_EFER_LME, %eax
wrmsr
/* Restore CR0 with paging enabled and flush the instruction pipeline */
movl %ebp, %cr0
call XpaFlushInstructions
XpaFlushInstructions:
/* Push the 64-bit code segment selector and the target address for a far jump */
pushl $GDT_R0_CODE
pushl %ebx
/* Perform a far return to switch to 64-bit long mode */
lretl
XpaEnterLongMode:
/* Enter 64-bit long mode */
.code64
/* Restore the stack pointer and non-volatile registers */
movq XpaRegisterSaveArea(%rip), %rsp
movq XpaRegisterSaveArea+8(%rip), %rbp
movq XpaRegisterSaveArea+0x10(%rip), %rax
movq XpaRegisterSaveArea+0x18(%rip), %rbx
/* Restore the original CR4 register with LA57 bit set */
orq $CR4_LA57, %rax
movq %rax, %cr4
/* Return to the caller */
retq
/* Data section for saving registers and temporary GDT */
XpaRegisterSaveArea: .quad 0x0000000000000000, 0x0000000000000000, 0x0000000000000000, 0x0000000000000000
XpaTemporaryGdtSize: .short ArEnableExtendedPhysicalAddressingEnd - XpaTemporaryGdtDesc - 1
XpaTemporaryGdtBase: .quad 0x0000000000000000
XpaTemporaryGdtDesc: .quad 0x0000000000000000, 0x00CF9A000000FFFF, 0x00AF9A000000FFFF, 0x00CF92000000FFFF
.global ArEnableExtendedPhysicalAddressingEnd
ArEnableExtendedPhysicalAddressingEnd:

14
xtoskrnl/ar/i686/boot.S Normal file
View File

@@ -0,0 +1,14 @@
/**
* PROJECT: ExectOS
* COPYRIGHT: See COPYING.md in the top level directory
* FILE: xtoskrnl/ar/i686/boot.S
* DESCRIPTION: i686-specific boot code for setting up the low-level CPU environment
* DEVELOPERS: Aiken Harris <harraiken91@gmail.com>
*/
#include <amd64/asmsup.h>
.altmacro
.text

View File

@@ -4,6 +4,7 @@
* FILE: xtoskrnl/hl/fbdev.c
* DESCRIPTION: FrameBuffer support
* DEVELOPERS: Rafal Kupiec <belliash@codingworkshop.eu.org>
* Aiken Harris <harraiken91@gmail.com>
*/
#include <xtos.h>
@@ -24,9 +25,10 @@ XTAPI
VOID
HlClearScreen(IN ULONG Color)
{
SIZE_T Line, PositionX, PositionY;
ULONG PositionX, PositionY;
ULONG BackgroundColor;
PULONG FrameBuf;
PCHAR CurrentLine;
PULONG Pixel;
/* Make sure frame buffer is already initialized */
if(HlpFrameBufferData.Initialized == FALSE)
@@ -35,34 +37,102 @@ HlClearScreen(IN ULONG Color)
return;
}
/* Get pointer to frame buffer */
FrameBuf = HlpFrameBufferData.Address;
/* Convert background color */
/* Convert background color and get pointer to frame buffer */
BackgroundColor = HlpRGBColor(Color);
CurrentLine = HlpFrameBufferData.Address;
/* Fill the screen with a black box */
for(PositionY = 0; PositionY < HlpFrameBufferData.Height; PositionY++)
/* Fill the screen with the specified color */
for(PositionY = 0; PositionY < HlpFrameBufferData.Height; PositionY++, CurrentLine += HlpFrameBufferData.Pitch)
{
Line = PositionY * HlpFrameBufferData.PixelsPerScanLine;
/* Fill the current line with the specified color */
Pixel = (PULONG)CurrentLine;
for(PositionX = 0; PositionX < HlpFrameBufferData.Width; PositionX++)
{
FrameBuf[Line + PositionX] = BackgroundColor;
/* Set the color of the pixel */
Pixel[PositionX] = BackgroundColor;
}
}
}
/**
* Draw a pixel on the screen at the given position and color.
* Displays a single character at the current cursor position inside the scroll region.
*
* @param PositionX
* Supplies the X coordinate of the pixel.
* @param Character
* Supplies the character to be displayed.
*
* @param PositionY
* Supplies the Y coordinate of the pixel.
* @return This routine does not return any value.
*
* @param Color
* Specifies the color of the pixel in (A)RGB format.
* @since XT 1.0
*/
XTCDECL
XTSTATUS
HlDisplayCharacter(IN WCHAR Character)
{
PSSFN_FONT_HEADER FbFont;
/* Make sure frame buffer is already initialized */
if(HlpFrameBufferData.Initialized == FALSE)
{
/* Unable to operate on non-initialized frame buffer */
return STATUS_DEVICE_NOT_READY;
}
/* Get font information */
FbFont = (PSSFN_FONT_HEADER)HlpFrameBufferData.Font;
/* Handle special characters */
switch(Character)
{
case L'\n':
/* Move cursor to the beginning of the next line */
HlpScrollRegionData.CursorX = HlpScrollRegionData.Left;
HlpScrollRegionData.CursorY += FbFont->Height;
break;
case L'\t':
/* Move cursor to the next tab stop */
HlpScrollRegionData.CursorX += (8 - (HlpScrollRegionData.CursorX - HlpScrollRegionData.Left) / FbFont->Width % 8) * FbFont->Width;
if (HlpScrollRegionData.CursorX >= HlpScrollRegionData.Right)
{
HlpScrollRegionData.CursorX = HlpScrollRegionData.Left;
HlpScrollRegionData.CursorY += FbFont->Height;
}
break;
default:
/* Draw the character */
HlpDrawCharacter(HlpScrollRegionData.CursorX, HlpScrollRegionData.CursorY, HlpScrollRegionData.TextColor, Character);
/* Advance cursor */
HlpScrollRegionData.CursorX += FbFont->Width;
/* Check if cursor reached end of line */
if(HlpScrollRegionData.CursorX >= HlpScrollRegionData.Right)
{
HlpScrollRegionData.CursorX = HlpScrollRegionData.Left;
HlpScrollRegionData.CursorY += FbFont->Height;
}
break;
}
/* Check if cursor reached end of scroll region */
if(HlpScrollRegionData.CursorY >= HlpScrollRegionData.Bottom)
{
/* Scroll one line up */
HlpScrollRegion();
HlpScrollRegionData.CursorY = HlpScrollRegionData.Bottom - FbFont->Height;
}
/* Return success */
return STATUS_SUCCESS;
}
/**
* Returns the current resolution of the frame buffer display.
*
* @param Width
* A pointer to memory area where the screen width will be stored.
*
* @param Height
* A pointer to memory area where the screen height will be stored.
*
* @return This routine does not return any value.
*
@@ -70,31 +140,10 @@ HlClearScreen(IN ULONG Color)
*/
XTAPI
VOID
HlDrawPixel(IN ULONG PositionX,
IN ULONG PositionY,
IN ULONG Color)
HlGetFrameBufferResolution(OUT PULONG Width, OUT PULONG Height)
{
SIZE_T FrameBufferIndex;
/* Make sure frame buffer is already initialized */
if(HlpFrameBufferData.Initialized == FALSE)
{
/* Unable to operate on non-initialized frame buffer */
return;
}
/* Make sure point is not offscreen */
if(PositionX >= HlpFrameBufferData.Width || PositionY >= HlpFrameBufferData.Height || Color > 0xFFFFFFFF)
{
/* Invalid pixel position or color given */
return;
}
/* Calculate the index of the pixel in the frame buffer memory using the provided x and y coordinates */
FrameBufferIndex = 4 * HlpFrameBufferData.PixelsPerScanLine * PositionY + 4 * PositionX;
/* Set the color of the pixel by writing to the corresponding memory location */
*((PULONG)(HlpFrameBufferData.Address + FrameBufferIndex)) = HlpRGBColor(Color);
*Width = HlpFrameBufferData.Width;
*Height = HlpFrameBufferData.Height;
}
/**
@@ -153,7 +202,7 @@ HlInitializeFrameBuffer(VOID)
HlpFrameBufferData.Address = FrameBufferResource->Header.VirtualAddress;
HlpFrameBufferData.Width = FrameBufferResource->Width;
HlpFrameBufferData.Height = FrameBufferResource->Height;
HlpFrameBufferData.BitsPerPixel = FrameBufferResource->BitsPerPixel;
HlpFrameBufferData.BytesPerPixel = FrameBufferResource->BitsPerPixel / 8;
HlpFrameBufferData.PixelsPerScanLine = FrameBufferResource->PixelsPerScanLine;
HlpFrameBufferData.Pitch = FrameBufferResource->Pitch;
HlpFrameBufferData.Pixels.BlueShift = FrameBufferResource->Pixels.BlueShift;
@@ -174,7 +223,81 @@ HlInitializeFrameBuffer(VOID)
}
/**
* Puts a wide character on the framebuffer at the given position and color using the SSFN font.
* Sets the scrollable region of the screen and calculates character dimensions.
*
* @param Left
* Supplies the left pixel coordinate of the scroll region.
*
* @param Top
* Supplies the top pixel coordinate of the scroll region.
*
* @param Right
* Supplies the right pixel coordinate of the scroll region.
*
* @param Bottom
* Supplies the bottom pixel coordinate of the scroll region.
*
* @return This routine does not return any value.
*
* @since XT 1.0
*/
XTAPI
VOID
HlInitializeScrollRegion(IN ULONG Left,
IN ULONG Top,
IN ULONG Right,
IN ULONG Bottom,
IN ULONG FontColor)
{
PSSFN_FONT_HEADER FbFont;
PCHAR PixelAddress;
/* Make sure frame buffer is already initialized */
if(HlpFrameBufferData.Initialized == FALSE)
{
/* Unable to operate on non-initialized frame buffer */
return;
}
/* Store pixel coordinates of the scroll region */
HlpScrollRegionData.Left = Left;
HlpScrollRegionData.Top = Top;
HlpScrollRegionData.Right = Right;
HlpScrollRegionData.Bottom = Bottom;
/* Get font information */
FbFont = (PSSFN_FONT_HEADER)HlpFrameBufferData.Font;
/* Validate font information */
if(FbFont && FbFont->Width > 0 && FbFont->Height > 0)
{
/* Calculate character dimensions */
HlpScrollRegionData.WidthInChars = (Right - Left) / FbFont->Width;
HlpScrollRegionData.HeightInChars = (Bottom - Top) / FbFont->Height;
/* Ensure the bottom of the scroll region is an exact multiple of the font height */
HlpScrollRegionData.Bottom = HlpScrollRegionData.Top + (HlpScrollRegionData.HeightInChars * FbFont->Height);
}
else
{
/* Fallback to 0 if font info is not available or invalid */
HlpScrollRegionData.WidthInChars = 0;
HlpScrollRegionData.HeightInChars = 0;
}
/* Initialize cursor position and font color */
HlpScrollRegionData.CursorX = HlpScrollRegionData.Left;
HlpScrollRegionData.CursorY = HlpScrollRegionData.Top;
HlpScrollRegionData.TextColor = FontColor;
/* Get the background color by reading the pixel at the top-left corner of the scroll region */
PixelAddress = (PCHAR)HlpFrameBufferData.Address + (Top * HlpFrameBufferData.Pitch) +
(Left * HlpFrameBufferData.BytesPerPixel);
HlpScrollRegionData.BackgroundColor = *((PULONG)PixelAddress);
}
/**
* Draws a character on the framebuffer at the given position and color using the SSFN font.
*
* @param PositionX
* Supplies the X coordinate of the character.
@@ -194,10 +317,10 @@ HlInitializeFrameBuffer(VOID)
*/
XTAPI
VOID
HlPutCharacter(IN ULONG PositionX,
IN ULONG PositionY,
IN ULONG Color,
IN WCHAR WideCharacter)
HlpDrawCharacter(IN ULONG PositionX,
IN ULONG PositionY,
IN ULONG Color,
IN WCHAR WideCharacter)
{
UINT CurrentFragment, Glyph, GlyphLimit, Index, Line, Mapping;
PUCHAR Character, CharacterMapping, Fragment;
@@ -261,7 +384,8 @@ HlPutCharacter(IN ULONG PositionX,
}
/* Find the glyph position on the frame buffer and set font color */
GlyphPixel = (UINT_PTR)HlpFrameBufferData.Address + PositionY * HlpFrameBufferData.Pitch + PositionX * 4;
GlyphPixel = (UINT_PTR)HlpFrameBufferData.Address + PositionY * HlpFrameBufferData.Pitch +
PositionX * HlpFrameBufferData.BytesPerPixel;
FontColor = HlpRGBColor(Color);
/* Check all kerning fragments */
@@ -321,7 +445,7 @@ HlPutCharacter(IN ULONG PositionX,
}
/* Advance pixel pointer */
Pixel += 4;
Pixel += HlpFrameBufferData.BytesPerPixel;
CurrentFragment <<= 1;
}
@@ -335,6 +459,52 @@ HlPutCharacter(IN ULONG PositionX,
}
}
/**
* Draw a pixel on the screen at the given position and color.
*
* @param PositionX
* Supplies the X coordinate of the pixel.
*
* @param PositionY
* Supplies the Y coordinate of the pixel.
*
* @param Color
* Specifies the color of the pixel in (A)RGB format.
*
* @return This routine does not return any value.
*
* @since XT 1.0
*/
XTAPI
VOID
HlpDrawPixel(IN ULONG PositionX,
IN ULONG PositionY,
IN ULONG Color)
{
PCHAR PixelAddress;
/* Make sure frame buffer is already initialized */
if(HlpFrameBufferData.Initialized == FALSE)
{
/* Unable to operate on non-initialized frame buffer */
return;
}
/* Make sure point is not offscreen */
if(PositionX >= HlpFrameBufferData.Width || PositionY >= HlpFrameBufferData.Height || Color > 0xFFFFFFFF)
{
/* Invalid pixel position or color given */
return;
}
/* Calculate the address of the pixel in the frame buffer memory */
PixelAddress = (PCHAR)HlpFrameBufferData.Address + (PositionY * HlpFrameBufferData.Pitch) +
(PositionX * HlpFrameBufferData.BytesPerPixel);
/* Set the color of the pixel by writing to the corresponding memory location */
*((PULONG)PixelAddress) = HlpRGBColor(Color);
}
/**
* Converts color format from (A)RGB one expected by current FrameBuffer.
*
@@ -361,3 +531,62 @@ HlpRGBColor(IN ULONG Color)
return (ULONG)((Blue << HlpFrameBufferData.Pixels.BlueShift) | (Green << HlpFrameBufferData.Pixels.GreenShift) |
(Red << HlpFrameBufferData.Pixels.RedShift) | (Reserved << HlpFrameBufferData.Pixels.ReservedShift));
}
/**
* Scrolls the content of the scroll region up by one line.
*
* @return This routine does not return any value.
*
* @since XT 1.0
*/
XTAPI
VOID
HlpScrollRegion(VOID)
{
PCHAR Destination, Source;
PSSFN_FONT_HEADER FbFont;
ULONG Line, PositionX;
ULONG LineBytes;
PULONG Pixel;
/* Make sure frame buffer is already initialized */
if(HlpFrameBufferData.Initialized == FALSE)
{
/* Unable to operate on non-initialized frame buffer */
return;
}
/* Get font information */
FbFont = (PSSFN_FONT_HEADER)HlpFrameBufferData.Font;
/* Calculate bytes per line in the scroll region */
LineBytes = (HlpScrollRegionData.Right - HlpScrollRegionData.Left) * HlpFrameBufferData.BytesPerPixel;
/* Scroll up each scan line in the scroll region */
for(Line = HlpScrollRegionData.Top; Line < HlpScrollRegionData.Bottom - FbFont->Height; Line++)
{
Destination = (PCHAR)HlpFrameBufferData.Address + Line * HlpFrameBufferData.Pitch +
HlpScrollRegionData.Left * HlpFrameBufferData.BytesPerPixel;
/* The source is one full text line (FbFont->Height) below the destination */
Source = (PCHAR)HlpFrameBufferData.Address + (Line + FbFont->Height) * HlpFrameBufferData.Pitch +
HlpScrollRegionData.Left * HlpFrameBufferData.BytesPerPixel;
/* Move each scan line in the scroll region up */
RtlMoveMemory(Destination, Source, LineBytes);
}
/* Clear the last text line */
for(Line = HlpScrollRegionData.Bottom - FbFont->Height; Line < HlpScrollRegionData.Bottom; Line++)
{
/* Get pointer to the start of the scan line to clear */
Pixel = (PULONG)((PCHAR)HlpFrameBufferData.Address + Line * HlpFrameBufferData.Pitch +
HlpScrollRegionData.Left * HlpFrameBufferData.BytesPerPixel);
/* Clear each pixel in the scan line with the background color */
for(PositionX = 0; PositionX < (HlpScrollRegionData.Right - HlpScrollRegionData.Left); PositionX++)
{
Pixel[PositionX] = HlpScrollRegionData.BackgroundColor;
}
}
}

View File

@@ -25,7 +25,10 @@ KAFFINITY HlpActiveProcessors;
APIC_MODE HlpApicMode;
/* FrameBuffer information */
HAL_FRAMEBUFFER_DATA HlpFrameBufferData;
HL_FRAMEBUFFER_DATA HlpFrameBufferData;
/* Scroll region information */
HL_SCROLL_REGION_DATA HlpScrollRegionData;
/* System information */
ACPI_SYSTEM_INFO HlpSystemInfo;

View File

@@ -191,24 +191,23 @@ VOID
HlpInitializeApic(VOID)
{
APIC_SPURIOUS_REGISTER SpuriousRegister;
APIC_COMMAND_REGISTER CommandRegister;
APIC_BASE_REGISTER BaseRegister;
APIC_LVT_REGISTER LvtRegister;
ULONG CpuNumber;
/* Check if this is an x2APIC compatible machine */
/* Determine APIC mode (xAPIC compatibility or x2APIC) */
if(HlpCheckX2ApicSupport())
{
/* Enable x2APIC */
/* Enable x2APIC mode */
HlpApicMode = APIC_MODE_X2APIC;
}
else
{
/* Use xAPIC compatibility mode */
/* Fall back to xAPIC compatibility mode */
HlpApicMode = APIC_MODE_COMPAT;
}
/* Get processor number */
/* Get current processor number */
CpuNumber = KeGetCurrentProcessorNumber();
/* Enable the APIC */
@@ -218,82 +217,73 @@ HlpInitializeApic(VOID)
BaseRegister.BootStrapProcessor = (CpuNumber == 0) ? 1 : 0;
ArWriteModelSpecificRegister(APIC_LAPIC_MSR_BASE, BaseRegister.LongLong);
/* Raise APIC task priority (TPR) to mask off all interrupts */
/* Mask all interrupts by raising Task Priority Register (TPR) */
HlWriteApicRegister(APIC_TPR, 0xFF);
/* xAPIC compatibility mode specific initialization */
/* Perform initialization specific to xAPIC compatibility mode */
if(HlpApicMode == APIC_MODE_COMPAT)
{
/* Initialize Destination Format Register with flat model (not supported in x2APIC mode) */
/* Use Flat Model for destination format (not supported in x2APIC) */
HlWriteApicRegister(APIC_DFR, APIC_DF_FLAT);
/* Set the logical APIC ID (read-only in x2APIC mode) */
/* Set the logical APIC ID for this processor (read-only in x2APIC) */
HlWriteApicRegister(APIC_LDR, (1UL << CpuNumber) << 24);
}
/* Set the spurious interrupt vector */
/* Configure the spurious interrupt vector */
SpuriousRegister.Long = HlReadApicRegister(APIC_SIVR);
SpuriousRegister.Vector = APIC_VECTOR_SPURIOUS;
SpuriousRegister.SoftwareEnable = 1;
SpuriousRegister.CoreChecking = 0;
HlWriteApicRegister(APIC_SIVR, SpuriousRegister.Long);
/* Mask LVTR_ERROR first, to prevent local APIC error */
/* Setup the LVT Error entry to deliver APIC errors on a dedicated vector */
HlWriteApicRegister(APIC_ERRLVTR, APIC_VECTOR_ERROR);
/* Mask TMRLVTR */
/* Program the APIC timer for periodic mode */
LvtRegister.Long = 0;
LvtRegister.Mask = 1;
LvtRegister.MessageType = APIC_DM_FIXED;
LvtRegister.DeliveryMode = APIC_DM_FIXED;
LvtRegister.TimerMode = 1;
LvtRegister.TriggerMode = APIC_TGM_EDGE;
LvtRegister.Vector = APIC_VECTOR_PROFILE;
HlWriteApicRegister(APIC_TMRLVTR, LvtRegister.Long);
/* Mask PCLVTR */
/* Configure the performance counter overflow */
LvtRegister.Long = 0;
LvtRegister.Mask = 0;
LvtRegister.MessageType = APIC_DM_FIXED;
LvtRegister.DeliveryMode = APIC_DM_FIXED;
LvtRegister.TimerMode = 0;
LvtRegister.TriggerMode = APIC_TGM_EDGE;
LvtRegister.Vector = APIC_VECTOR_PERF;
HlWriteApicRegister(APIC_PCLVTR, LvtRegister.Long);
/* Mask LINT0 */
/* Configure the LINT0 pin */
LvtRegister.Long = 0;
LvtRegister.Mask = 1;
LvtRegister.MessageType = APIC_DM_FIXED;
LvtRegister.DeliveryMode = APIC_DM_FIXED;
LvtRegister.TimerMode = 0;
LvtRegister.TriggerMode = APIC_TGM_EDGE;
LvtRegister.Vector = APIC_VECTOR_SPURIOUS;
HlWriteApicRegister(APIC_LINT0, LvtRegister.Long);
/* Mask LINT1 */
/* Configure the LINT1 pin */
LvtRegister.Long = 0;
LvtRegister.Mask = 0;
LvtRegister.MessageType = APIC_DM_NMI;
LvtRegister.DeliveryMode = APIC_DM_NMI;
LvtRegister.TimerMode = 0;
LvtRegister.TriggerMode = APIC_TGM_EDGE;
LvtRegister.Vector = APIC_VECTOR_NMI;
HlWriteApicRegister(APIC_LINT1, LvtRegister.Long);
/* Mask ICR0 */
CommandRegister.Long0 = 0;
CommandRegister.DestinationShortHand = APIC_DSH_Destination;
CommandRegister.MessageType = APIC_MT_INIT;
CommandRegister.DestinationMode = 1;
CommandRegister.TriggerMode = APIC_TGM_EDGE;
CommandRegister.Vector = APIC_VECTOR_ZERO;
HlWriteApicRegister(APIC_ICR0, CommandRegister.Long0);
/* Register interrupt handlers once the APIC initialization is done */
/* Register interrupt handlers */
KeSetInterruptHandler(APIC_VECTOR_SPURIOUS, HlpHandleApicSpuriousService);
KeSetInterruptHandler(PIC1_VECTOR_SPURIOUS, HlpHandlePicSpuriousService);
/* Clear errors after enabling vectors */
/* Clear any pre-existing errors */
HlWriteApicRegister(APIC_ESR, 0);
/* Lower APIC TPR to re-enable interrupts */
/* Re-enable all interrupts by lowering the Task Priority Register */
HlWriteApicRegister(APIC_TPR, 0x00);
}

View File

@@ -10,6 +10,21 @@
#define __XTOSKRNL_AMD64_ASMSUP_H
/* Control Register bit definitions */
#define CR0_PG 0x80000000
#define CR4_PGE 0x00000080
#define CR4_LA57 0x00001000
#define CR4_PCIDE 0x00020000
/* GDT selectors */
#define GDT_R0_CMCODE 0x08
#define GDT_R0_CODE 0x10
#define GDT_R0_DATA 0x18
/* MSR registers */
#define X86_MSR_EFER 0xC0000080
#define X86_MSR_EFER_LME (1 << 8)
/* KTRAP_FRAME structure offsets */
#define TrapXmm0 0
#define TrapXmm1 16

View File

@@ -30,4 +30,10 @@ EXTERN UCHAR ArKernelBootStack[KERNEL_STACK_SIZE];
/* Kernel own fault stack */
EXTERN UCHAR ArKernelFaultStack[KERNEL_STACK_SIZE];
/* Page mapping routines for systems using 4-level paging (PML4) */
EXTERN CMMPAGEMAP_ROUTINES MmpPml4Routines;
/* Page mapping routines for systems using 5-level paging (PML5) */
EXTERN CMMPAGEMAP_ROUTINES MmpPml5Routines;
#endif /* __XTOSKRNL_AMD64_GLOBALS_H */

View File

@@ -13,17 +13,33 @@
/* AMD64 Memory Manager routines forward references */
XTAPI
VOID
MmInitializePageMapSupport(VOID);
XTFASTCALL
VOID
MmZeroPages(IN PVOID Address,
IN ULONG Size);
XTAPI
PMMPTE
VOID
MmpClearPte(PHARDWARE_PTE PtePointer);
XTAPI
BOOLEAN
MmpGetExtendedPhysicalAddressingStatus(VOID);
XTAPI
PMMP5E
MmpGetP5eAddress(PVOID Address);
XTAPI
PMMPDE
MmpGetPdeAddress(PVOID Address);
XTAPI
PMMPTE
PMMPPE
MmpGetPpeAddress(PVOID Address);
XTAPI
@@ -31,7 +47,7 @@ PMMPTE
MmpGetPteAddress(PVOID Address);
XTAPI
PMMPTE
PMMPXE
MmpGetPxeAddress(PVOID Address);
XTAPI
@@ -40,6 +56,18 @@ MmpInitializeArchitecture(VOID);
XTAPI
BOOLEAN
MmpMemoryExtensionEnabled(VOID);
MmpPteValid(PHARDWARE_PTE PtePointer);
XTAPI
VOID
MmpSetPte(PHARDWARE_PTE PtePointer,
PFN_NUMBER PageFrameNumber,
BOOLEAN Writable);
XTAPI
VOID
MmpSetPteCaching(PHARDWARE_PTE PtePointer,
BOOLEAN CacheDisable,
BOOLEAN WriteThrough);
#endif /* __XTOSKRNL_AMD64_MMI_H */

View File

@@ -28,13 +28,32 @@ EXTERN KAFFINITY HlpActiveProcessors;
EXTERN APIC_MODE HlpApicMode;
/* FrameBuffer information */
EXTERN HAL_FRAMEBUFFER_DATA HlpFrameBufferData;
EXTERN HL_FRAMEBUFFER_DATA HlpFrameBufferData;
/* Scroll region information */
EXTERN HL_SCROLL_REGION_DATA HlpScrollRegionData;
/* System information */
EXTERN ACPI_SYSTEM_INFO HlpSystemInfo;
/* Pointer to boot loader provided DbgPrint() routine */
EXTERN VOID (*KeDbgPrint)(IN PWCHAR Format, IN ...);
/* Pointer to DbgPrint() routine */
EXTERN PKD_PRINT_ROUTINE KdPrint;
/* Kernel Debugger mode */
EXTERN KD_DEBUG_MODE KdpDebugMode;
/* Debugger I/O providers initialization routines */
EXTERN PKD_INIT_ROUTINE KdpIoProvidersInitRoutines[KDBG_PROVIDERS_COUNT];
/* List of active I/O providers */
EXTERN LIST_ENTRY KdpProviders;
/* Debugger's serial port handle */
EXTERN CPPORT KdpSerialPort;
/* Pre-defined serial port addresses */
EXTERN ULONG KdpSerialPortList[COMPORT_COUNT];
/* Kernel initialization block passed by boot loader */
EXTERN PKERNEL_INITIALIZATION_BLOCK KeInitializationBlock;
@@ -75,9 +94,6 @@ EXTERN ULONG MmNumberOfPhysicalPages;
/* Old biggest free memory descriptor */
EXTERN LOADER_MEMORY_DESCRIPTOR MmOldFreeDescriptor;
/* Page Map Level */
EXTERN ULONG MmPageMapLevel;
/* Processor structures data (THIS IS A TEMPORARY HACK) */
EXTERN UCHAR MmProcessorStructuresData[MAXIMUM_PROCESSORS][KPROCESSOR_STRUCTURES_SIZE];
@@ -87,8 +103,11 @@ EXTERN LOADER_MEMORY_DESCRIPTOR MmpHardwareAllocationDescriptors[MM_HARDWARE_ALL
/* Live address of kernel's hardware heap */
EXTERN PVOID MmpHardwareHeapStart;
/* Architecture-specific memory extension */
EXTERN BOOLEAN MmpMemoryExtension;
/* Information about the current page map */
EXTERN MMPAGEMAP_INFO MmpPageMapInfo;
/* Pointers to page map routines for the current paging mode */
EXTERN PCMMPAGEMAP_ROUTINES MmpPageMapRoutines;
/* Number of used hardware allocation descriptors */
EXTERN ULONG MmpUsedHardwareAllocationDescriptors;

View File

@@ -34,11 +34,9 @@ UCHAR
HlComPortReadLsr(IN PCPPORT Port,
IN UCHAR Byte);
XTAPI
VOID
HlDrawPixel(IN ULONG PosX,
IN ULONG PosY,
IN ULONG Color);
XTCDECL
XTSTATUS
HlDisplayCharacter(IN WCHAR Character);
XTAPI
XTSTATUS
@@ -49,6 +47,10 @@ XTSTATUS
HlGetAcpiTable(IN ULONG Signature,
OUT PACPI_DESCRIPTION_HEADER *AcpiTable);
XTAPI
VOID
HlGetFrameBufferResolution(OUT PULONG Width, OUT PULONG Height);
XTFASTCALL
KRUNLEVEL
HlGetRunLevel(VOID);
@@ -68,15 +70,16 @@ VOID
HlInitializeProcessor(VOID);
XTAPI
XTSTATUS
HlInitializeSystem(VOID);
VOID
HlInitializeScrollRegion(IN ULONG Left,
IN ULONG Top,
IN ULONG Right,
IN ULONG Bottom,
IN ULONG FontColor);
XTAPI
VOID
HlPutCharacter(IN ULONG PositionX,
IN ULONG PositionY,
IN ULONG Color,
IN WCHAR WideCharacter);
XTSTATUS
HlInitializeSystem(VOID);
XTFASTCALL
VOID
@@ -86,6 +89,19 @@ XTAPI
VOID
HlpCacheAcpiTable(IN PACPI_DESCRIPTION_HEADER AcpiTable);
XTAPI
VOID
HlpDrawCharacter(IN ULONG PositionX,
IN ULONG PositionY,
IN ULONG Color,
IN WCHAR WideCharacter);
XTAPI
VOID
HlpDrawPixel(IN ULONG PosX,
IN ULONG PosY,
IN ULONG Color);
XTAPI
XTSTATUS
HlpInitializeAcpi(VOID);
@@ -124,6 +140,10 @@ XTAPI
ULONG
HlpRGBColor(IN ULONG Color);
XTAPI
VOID
HlpScrollRegion(VOID);
XTAPI
BOOLEAN
HlpValidateAcpiTable(IN PVOID Buffer,

View File

@@ -34,4 +34,10 @@ EXTERN UCHAR ArKernelBootStack[KERNEL_STACK_SIZE];
/* Kernel own fault stack */
EXTERN UCHAR ArKernelFaultStack[KERNEL_STACK_SIZE];
/* Page mapping routines for systems using 2-level paging (PML2) */
EXTERN CMMPAGEMAP_ROUTINES MmpPml2Routines;
/* Page mapping routines for systems using 3-level paging (PML3) */
EXTERN CMMPAGEMAP_ROUTINES MmpPml3Routines;
#endif /* __XTOSKRNL_I686_GLOBALS_H */

View File

@@ -13,15 +13,31 @@
/* i686 Memory Manager routines forward references */
XTAPI
VOID
MmInitializePageMapSupport(VOID);
XTFASTCALL
VOID
MmZeroPages(IN PVOID Address,
IN ULONG Size);
XTAPI
PMMPTE
VOID
MmpClearPte(PHARDWARE_PTE PtePointer);
XTAPI
BOOLEAN
MmpGetExtendedPhysicalAddressingStatus(VOID);
XTAPI
PMMPDE
MmpGetPdeAddress(PVOID Address);
XTAPI
PMMPPE
MmpGetPpeAddress(PVOID Address);
XTAPI
PMMPTE
MmpGetPteAddress(PVOID Address);
@@ -32,6 +48,34 @@ MmpInitializeArchitecture(VOID);
XTAPI
BOOLEAN
MmpMemoryExtensionEnabled(VOID);
MmpPml2PteValid(PHARDWARE_PTE PtePointer);
XTAPI
VOID
MmpSetPml2Pte(PHARDWARE_PTE PtePointer,
PFN_NUMBER PageFrameNumber,
BOOLEAN Writable);
XTAPI
VOID
MmpSetPml2PteCaching(PHARDWARE_PTE PtePointer,
BOOLEAN CacheDisable,
BOOLEAN WriteThrough);
XTAPI
BOOLEAN
MmpPml3PteValid(PHARDWARE_PTE PtePointer);
XTAPI
VOID
MmpSetPml3Pte(PHARDWARE_PTE PtePointer,
PFN_NUMBER PageFrameNumber,
BOOLEAN Writable);
XTAPI
VOID
MmpSetPml3PteCaching(PHARDWARE_PTE PtePointer,
BOOLEAN CacheDisable,
BOOLEAN WriteThrough);
#endif /* __XTOSKRNL_I686_MMI_H */

44
xtoskrnl/includes/kdi.h Normal file
View File

@@ -0,0 +1,44 @@
/**
* PROJECT: ExectOS
* COPYRIGHT: See COPYING.md in the top level directory
* FILE: xtoskrnl/includes/kdi.h
* DESCRIPTION: Kernel Debugger routines
* DEVELOPERS: Aiken Harris <harraiken91@gmail.com>
*/
#ifndef __XTOSKRNL_KDI_H
#define __XTOSKRNL_KDI_H
#include <xtos.h>
/* Kernel Debugger routines forward references */
XTAPI
XTSTATUS
KdInitializeDebugIoProviders(VOID);
XTAPI
VOID
KdSetPrintRoutine(PVOID DebugPrintRoutine);
XTCDECL
VOID
KdpDebugPrint(PCWSTR Format, ...);
XTAPI
XTSTATUS
KdpDetectDebugPorts(VOID);
XTAPI
XTSTATUS
KdpInitializeFrameBufferProvider(VOID);
XTAPI
XTSTATUS
KdpInitializeSerialPortProvider(VOID);
XTCDECL
XTSTATUS
KdpSerialWriteCharacter(WCHAR Character);
#endif /* __XTOSKRNL_KDI_H */

View File

@@ -21,6 +21,15 @@ XTAPI
VOID
KeClearTimer(IN PKTIMER Timer);
XTAPI
SYSTEM_FIRMWARE_TYPE
KeGetFirmwareType(VOID);
XTAPI
XTSTATUS
KeGetKernelParameter(IN PCWSTR ParameterName,
OUT PCWSTR *Parameter);
XTAPI
VOID
KeHaltSystem(VOID);

View File

@@ -15,6 +15,7 @@
/* Kernel specific headers */
#include "globals.h"
#include "hli.h"
#include "kdi.h"
#include "kei.h"
#include "mmi.h"
#include "poi.h"

192
xtoskrnl/kd/dbginit.c Normal file
View File

@@ -0,0 +1,192 @@
/**
* PROJECT: ExectOS
* COPYRIGHT: See COPYING.md in the top level directory
* FILE: xtoskrnl/kd/dbginit.c
* DESCRIPTION: Kernel Debugger initialization
* DEVELOPERS: Aiken Harris <harraiken91@gmail.com>
*/
#include <xtos.h>
/**
* Initializes the kernel's debugger I/O providers.
*
* @return This routine returns a status code.
*
* @since XT 1.0
*/
XTAPI
XTSTATUS
KdInitializeDebugIoProviders(VOID)
{
ULONG Index;
XTSTATUS ProviderStatus, Status;
/* Initialize debug providers list */
RtlInitializeListHead(&KdpProviders);
RtlZeroMemory(&KdpDebugMode, sizeof(KD_DEBUG_MODE));
KdpDetectDebugPorts();
/* Iterate over providers initialization routines */
for(Index = 0; Index < KDBG_PROVIDERS_COUNT; Index++)
{
/* Initialize provider */
ProviderStatus = KdpIoProvidersInitRoutines[Index]();
Status = (Status || ProviderStatus);
}
/* Initialize debug print routine */
KdSetPrintRoutine(KdpDebugPrint);
/* Return status code */
return Status;
}
/**
* Configures the kernel's debug print routine by setting a new output handler.
*
* @param DebugPrintRoutine
* Supplies a pointer to the new debug print routine.
*
* @return This routine does not return any value.
*
* @since XT 1.0
*/
XTAPI
VOID
KdSetPrintRoutine(PVOID DebugPrintRoutine)
{
/* Set debug print routine */
KdPrint = DebugPrintRoutine;
}
/**
* Detects and enables the kernel's debug ports based on the 'DEBUG' parameter passed to the kernel.
*
* @return This routine returns a status code.
*
* @since XT 1.0
*/
XTAPI
XTSTATUS
KdpDetectDebugPorts(VOID)
{
PCWSTR DebugOption;
XTSTATUS Status;
/* Get debug parameter */
Status = KeGetKernelParameter(L"DEBUG", &DebugOption);
if(Status != STATUS_SUCCESS)
{
/* Debug parameter not found, disable debugging */
KdpDebugMode.Enabled = FALSE;
return Status;
}
/* Skip parameter name and check if it is set */
DebugOption += 5;
if(*DebugOption != L'=')
{
/* Debug parameter not set, disable debugging */
KdpDebugMode.Enabled = FALSE;
return STATUS_INVALID_PARAMETER;
}
/* Skip '=' symbol */
DebugOption++;
/* Iterate over all debug ports */
while(*DebugOption != L'\0' && *DebugOption != L' ')
{
/* Check what port is set for debugging */
if(RtlCompareWideStringInsensitive(DebugOption, L"COM", 3) == 0)
{
/* Enable serial port debugging mode */
KdpDebugMode.Mode |= DEBUG_PROVIDER_COMPORT;
/* Read COM port number */
DebugOption += 3;
while(*DebugOption >= '0' && *DebugOption <= '9')
{
/* Get port number */
KdpDebugMode.ComPortNumber *= 10;
KdpDebugMode.ComPortNumber += *DebugOption - '0';
DebugOption++;
}
/* Check if custom COM port address supplied */
if(KdpDebugMode.ComPortNumber == 0 && RtlCompareWideStringInsensitive(DebugOption, L":0x", 3) == 0)
{
/* COM port address provided */
DebugOption += 3;
while((*DebugOption >= '0' && *DebugOption <= '9') ||
(*DebugOption >= 'A' && *DebugOption <= 'F') ||
(*DebugOption >= 'a' && *DebugOption <= 'f'))
{
/* Get port address */
KdpDebugMode.ComPortAddress *= 16;
if(*DebugOption >= '0' && *DebugOption <= '9')
{
KdpDebugMode.ComPortAddress += *DebugOption - '0';
}
else if(*DebugOption >= 'A' && *DebugOption <= 'F')
{
KdpDebugMode.ComPortAddress += *DebugOption - 'A' + 10;
}
else if(*DebugOption >= 'a' && *DebugOption <= 'f')
{
KdpDebugMode.ComPortAddress += *DebugOption - 'a' + 10;
}
DebugOption++;
}
}
/* Look for additional COM port parameters */
if(*DebugOption == ',')
{
/* Baud rate provided */
DebugOption++;
while(*DebugOption >= '0' && *DebugOption <= '9')
{
/* Get baud rate */
KdpDebugMode.ComPortBaudRate *= 10;
KdpDebugMode.ComPortBaudRate += *DebugOption - '0';
DebugOption++;
}
}
}
else if(RtlCompareWideStringInsensitive(DebugOption, L"SCREEN", 6) == 0)
{
/* Enable framebuffer debugging mode */
KdpDebugMode.Mode |= DEBUG_PROVIDER_FRAMEBUFFER;
DebugOption += 6;
}
else if(*DebugOption == L';')
{
/* Skip separator */
DebugOption++;
}
else
{
/* Invalid debug option, skip it */
while(*DebugOption != L'\0' && *DebugOption != L' ' && *DebugOption != L';')
{
/* Advance debug option */
DebugOption++;
}
}
}
/* Ensure at least one debug port is enabled */
if(KdpDebugMode.Mode != 0)
{
/* Enable debugging */
KdpDebugMode.Enabled = TRUE;
}
/* Return success */
return STATUS_SUCCESS;
}

175
xtoskrnl/kd/dbgio.c Normal file
View File

@@ -0,0 +1,175 @@
/**
* PROJECT: ExectOS
* COPYRIGHT: See COPYING.md in the top level directory
* FILE: xtoskrnl/kd/dbgio.c
* DESCRIPTION: Kernel Debugger I/O routines
* DEVELOPERS: Aiken Harris <harraiken91@gmail.com>
*/
#include <xtos.h>
/**
* Prints a formatted string using the configured debug output providers.
*
* @param Format
* Supplies the format string.
*
* @param ...
* Supplies the variable argument list.
*
* @return This routine does not return any value.
*
* @since XT 1.0
*/
XTCDECL
VOID
KdpDebugPrint(PCWSTR Format, ...)
{
VA_LIST Arguments;
PLIST_ENTRY DispatchTableEntry;
PKD_DISPATCH_TABLE DispatchTable;
/* Initialise the va_list */
VA_START(Arguments, Format);
DispatchTableEntry = KdpProviders.Flink;
while(DispatchTableEntry != &KdpProviders)
{
DispatchTable = CONTAIN_RECORD(DispatchTableEntry, KD_DISPATCH_TABLE, ListEntry);
RtlFormatWideString(&DispatchTable->PrintContext, (PWCHAR)Format, Arguments);
DispatchTableEntry = DispatchTableEntry->Flink;
}
/* Clean up the va_list */
VA_END(Arguments);
}
/**
* Initializes the framebuffer device provider for the kernel debugger.
*
* @return This routine returns a status code.
*
* @since XT 1.0
*/
XTAPI
XTSTATUS
KdpInitializeFrameBufferProvider(VOID)
{
STATIC KD_DISPATCH_TABLE DispatchTable;
ULONG Height, Width;
/* Check if framebuffer provider is enabled */
if(KdpDebugMode.Enabled && (KdpDebugMode.Mode & DEBUG_PROVIDER_FRAMEBUFFER) == 0)
{
/* Screen is not enabled, no need to initialize provider */
return STATUS_PORT_DISCONNECTED;
}
/* Ensure frame buffer is initialized and get FB resolution */
HlInitializeFrameBuffer();
HlGetFrameBufferResolution(&Width, &Height);
/* Print debug message */
DebugPrint(L"Initializing debug console at framebuffer device (%lu x %lu)\n", Width, Height);
/* Initialize scroll region to full screen and white font color */
HlInitializeScrollRegion(0, 0, Width - 1, Height - 1, 0xFFFFFFFF);
/* Initialize screen dispatch table */
DispatchTable.PrintContext.WriteWideCharacter = HlDisplayCharacter;
RtlInsertHeadList(&KdpProviders, &DispatchTable.ListEntry);
/* Return success */
return STATUS_SUCCESS;
}
/**
* Initializes the serial port device provider for the kernel debugger.
*
* @return This routine returns a status code.
*
* @since XT 1.0
*/
XTAPI
XTSTATUS
KdpInitializeSerialPortProvider(VOID)
{
STATIC KD_DISPATCH_TABLE DispatchTable;
XTSTATUS Status;
/* Check if serial port provider is enabled */
if(KdpDebugMode.Enabled && (KdpDebugMode.Mode & DEBUG_PROVIDER_COMPORT) == 0)
{
/* Serial port is not enabled, no need to initialize provider */
return STATUS_PORT_DISCONNECTED;
}
/* Check if custom COM port address supplied */
if(!KdpDebugMode.ComPortAddress)
{
/* We support only a pre-defined number of ports */
if(KdpDebugMode.ComPortNumber > COMPORT_COUNT)
{
/* Fail if wrong/unsupported port used */
return STATUS_INVALID_PARAMETER;
}
/* Check if serial port is set */
if(KdpDebugMode.ComPortNumber == 0)
{
/* Use COM1 by default */
KdpDebugMode.ComPortNumber = 1;
}
/* Set custom port address based on the port number and print debug message */
KdpDebugMode.ComPortAddress = KdpSerialPortList[KdpDebugMode.ComPortNumber - 1];
DebugPrint(L"Initializing debug console at serial port (COM%lu, BaudRate: %lu)\n",
KdpDebugMode.ComPortNumber, KdpDebugMode.ComPortBaudRate);
}
else
{
/* Custom port address supplied, print debug message */
DebugPrint(L"Initializing debug console at serial port (0x%lX, BaudRate: %lu)\n",
KdpDebugMode.ComPortAddress, KdpDebugMode.ComPortBaudRate);
}
/* Initialize COM port */
Status = HlInitializeComPort(&KdpSerialPort, UlongToPtr(KdpDebugMode.ComPortAddress), KdpDebugMode.ComPortBaudRate);
if(Status != STATUS_SUCCESS)
{
/* Serial port initialization failed */
return Status;
}
/* Initialize serial port dispatch table */
DispatchTable.PrintContext.WriteWideCharacter = KdpSerialWriteCharacter;
RtlInsertHeadList(&KdpProviders, &DispatchTable.ListEntry);
/* Return success */
return STATUS_SUCCESS;
}
/**
* Writes a character to the serial console.
*
* @param Character
* The integer promotion of the character to be written.
*
* @return This routine returns a status code.
*
* @since XT 1.0
*/
XTCDECL
XTSTATUS
KdpSerialWriteCharacter(WCHAR Character)
{
WCHAR Buffer[2];
/* Write character to the serial console */
Buffer[0] = Character;
Buffer[1] = 0;
return HlComPortPutByte(&KdpSerialPort, Buffer[0]);
}

31
xtoskrnl/kd/globals.c Normal file
View File

@@ -0,0 +1,31 @@
/**
* PROJECT: ExectOS
* COPYRIGHT: See COPYING.md in the top level directory
* FILE: xtoskrnl/kd/globals.c
* DESCRIPTION: Architecture independent global variables related to KD subsystem
* DEVELOPERS: Aiken Harris <harraiken91@gmail.com>
*/
#include <xtos.h>
/* Pointer to DbgPrint() routine */
PKD_PRINT_ROUTINE KdPrint = NULL;
/* Kernel Debugger mode */
KD_DEBUG_MODE KdpDebugMode;
/* Debugger I/O providers initialization routines */
PKD_INIT_ROUTINE KdpIoProvidersInitRoutines[KDBG_PROVIDERS_COUNT] = {
KdpInitializeFrameBufferProvider,
KdpInitializeSerialPortProvider
};
/* List of active I/O providers */
LIST_ENTRY KdpProviders;
/* Debugger's serial port handle */
CPPORT KdpSerialPort;
/* Pre-defined serial port addresses */
ULONG KdpSerialPortList[COMPORT_COUNT] = COMPORT_ADDRESS;

View File

@@ -52,6 +52,9 @@ KepInitializeMachine(VOID)
/* Initialize processor */
HlInitializeProcessor();
/* Initialize page map support */
MmInitializePageMapSupport();
}
/**

View File

@@ -10,7 +10,7 @@
/* Pointer to boot loader provided DbgPrint() routine */
VOID (*KeDbgPrint)(IN PWCHAR Format, IN ...) = NULL;
VOID (*KeDbgPrint)(IN PCWSTR Format, IN ...) = NULL;
/* Kernel initialization block passed by boot loader */
PKERNEL_INITIALIZATION_BLOCK KeInitializationBlock;

View File

@@ -52,6 +52,9 @@ KepInitializeMachine(VOID)
/* Initialize processor */
HlInitializeProcessor();
/* Initialize page map support */
MmInitializePageMapSupport();
}
/**

94
xtoskrnl/ke/info.c Normal file
View File

@@ -0,0 +1,94 @@
/**
* PROJECT: ExectOS
* COPYRIGHT: See COPYING.md in the top level directory
* FILE: xtoskrnl/ke/info.c
* DESCRIPTION: Generic kernel information support
* DEVELOPERS: Aiken Harris <harraiken91@gmail.com>
*/
#include <xtos.h>
/**
* Retrieves the system firmware type (BIOS or UEFI).
*
* @return This routine returns the type of the system firmware.
*
* @since XT 1.0
*/
XTAPI
SYSTEM_FIRMWARE_TYPE
KeGetFirmwareType(VOID)
{
return KeInitializationBlock->FirmwareInformation.FirmwareType;
}
/**
* Retrieves a pointer to the specified kernel parameter within the kernel parameters list.
*
* @param ParameterName
* Supplies a pointer to a null-terminated wide string specifying the name of the parameter to search for.
*
* @param Parameter
* Supplies a pointer to a variable that receives a pointer to the matching parameter, or NULL if not found.
*
* @return This routine returns a status code.
*
* @since XT 1.0
*/
XTAPI
XTSTATUS
KeGetKernelParameter(IN PCWSTR ParameterName,
OUT PCWSTR *Parameter)
{
PCWSTR KernelParameters,Match, SearchStart;
SIZE_T ParameterNameLength;
/* Get the kernel parameters */
KernelParameters = KeInitializationBlock->KernelParameters;
/* Validate input parameters */
if(!KernelParameters || !ParameterName || !Parameter)
{
/* Invalid input parameters, return error */
return STATUS_INVALID_PARAMETER;
}
/* Get the length of the parameter name we are looking for */
ParameterNameLength = RtlWideStringLength(ParameterName, 0);
if(ParameterNameLength == 0)
{
/* Do not allow empty parameter names */
return STATUS_INVALID_PARAMETER;
}
/* Assume the requested parameter is not present in the kernel parameters */
*Parameter = NULL;
/* Start searching from the beginning of the list */
SearchStart = KernelParameters;
/* Search for the parameter name */
while((Match = RtlFindWideStringInsensitive(SearchStart, ParameterName)))
{
/* Check if the match is at the start of the string or preceded by a space */
if(Match == KernelParameters || *(Match - 1) == L' ')
{
/* Check the character after the match to avoid matching prefixes */
if(Match[ParameterNameLength] == L'\0' ||
Match[ParameterNameLength] == L' ' ||
Match[ParameterNameLength] == L'=')
{
/* A valid parameter was found, return a pointer to it */
*Parameter = Match;
return STATUS_SUCCESS;
}
}
/* The match was a substring of a larger token, continue searching */
SearchStart = Match + 1;
}
/* Parameter not found */
return STATUS_NOT_FOUND;
}

View File

@@ -39,7 +39,21 @@ KeStartXtSystem(IN PKERNEL_INITIALIZATION_BLOCK Parameters)
if(DEBUG && KeInitializationBlock->LoaderInformation.DbgPrint)
{
/* Use loader's provided DbgPrint() routine for early printing to serial console */
KeDbgPrint = KeInitializationBlock->LoaderInformation.DbgPrint;
KdSetPrintRoutine(KeInitializationBlock->LoaderInformation.DbgPrint);
DebugPrint(L"Initializing ExectOS v%d.%d for %s\n", XTOS_VERSION_MAJOR, XTOS_VERSION_MINOR, _ARCH_NAME);
}
/* Initialize boot CPU */
ArInitializeProcessor(NULL);
/* Initialize system resources */
KepInitializeSystemResources();
/* Check if debugging enabled */
if(DEBUG)
{
/* Initialize debug I/O */
KdInitializeDebugIoProviders();
}
/* Announce kernel startup */
@@ -48,12 +62,6 @@ KeStartXtSystem(IN PKERNEL_INITIALIZATION_BLOCK Parameters)
XTOS_VERSION_BUILD, XTOS_VERSION_ARCH, XTOS_VERSION_HASH,
XTOS_COMPILER_NAME, XTOS_COMPILER_VERSION);
/* Initialize boot CPU */
ArInitializeProcessor(NULL);
/* Initialize system resources */
KepInitializeSystemResources();
/* Architecture specific kernel initialization */
KepInitializeMachine();

View File

@@ -76,6 +76,6 @@ KePanicEx(IN ULONG Code,
IN ULONG_PTR Parameter3,
IN ULONG_PTR Parameter4)
{
KeDbgPrint(L"Fatal System Error: 0x%08lx\nKernel Panic!\n\n", Code);
KdPrint(L"Fatal System Error: 0x%08lx\nKernel Panic!\n\n", Code);
KeHaltSystem();
}

View File

@@ -0,0 +1,26 @@
/**
* PROJECT: ExectOS
* COPYRIGHT: See COPYING.md in the top level directory
* FILE: xtoskrnl/mm/amd64/globals.c
* DESCRIPTION: AMD64-specific global variables for the Memory Manager
* DEVELOPERS: Aiken Harris <harraiken91@gmail.com>
*/
#include <xtos.h>
/* Page mapping routines for systems using 4-level paging (PML4) */
CMMPAGEMAP_ROUTINES MmpPml4Routines = {
.ClearPte = MmpClearPte,
.PteValid = MmpPteValid,
.SetPteCaching = MmpSetPteCaching,
.SetPte = MmpSetPte,
};
/* Page mapping routines for systems using 5-level paging (PML5) */
CMMPAGEMAP_ROUTINES MmpPml5Routines = {
.ClearPte = MmpClearPte,
.PteValid = MmpPteValid,
.SetPteCaching = MmpSetPteCaching,
.SetPte = MmpSetPte,
};

View File

@@ -4,89 +4,60 @@
* FILE: xtoskrnl/mm/amd64/init.c
* DESCRIPTION: Architecture specific Memory Manager initialization routines
* DEVELOPERS: Rafal Kupiec <belliash@codingworkshop.eu.org>
* Aiken Harris <harraiken91@gmail.com>
*/
#include <xtos.h>
/**
* Gets the address of the PDE (Page Directory Entry), that maps given address.
* Detects if eXtended Physical Addressing (XPA) is enabled and initializes page map support.
*
* @param Address
* Specifies the address to find the PDE for.
*
* @return This routine returns the address of the PDE.
* @return This routine does not return any value.
*
* @since XT 1.0
*/
XTAPI
PMMPTE
MmpGetPdeAddress(PVOID Address)
VOID
MmInitializePageMapSupport(VOID)
{
ULONGLONG Offset;
/* Check if XPA is enabled */
if(MmpGetExtendedPhysicalAddressingStatus())
{
/* XPA enabled, use LA57 paging (PML5) */
MmpPageMapRoutines = &MmpPml5Routines;
Offset = ((((ULONGLONG)Address & (((ULONGLONG)1 << 48) - 1)) >> MM_PDI_SHIFT) << MM_PTE_SHIFT);
return (PMMPTE)(MM_PDE_BASE + Offset);
}
/* Set PML5 page map information */
MmpPageMapInfo.Xpa = TRUE;
/**
* Gets the address of the PPE (Page Directory Pointer Table Entry), that maps given address.
*
* @param Address
* Specifies the address to find the PPE for.
*
* @return This routine returns the address of the PPE.
*
* @since XT 1.0
*/
XTAPI
PMMPTE
MmpGetPpeAddress(PVOID Address)
{
ULONGLONG Offset;
/* Set PML5 base addresses */
MmpPageMapInfo.PteBase = MM_PTE_LA57_BASE;
MmpPageMapInfo.PdeBase = MM_PDE_LA57_BASE;
MmpPageMapInfo.PpeBase = MM_PPE_LA57_BASE;
MmpPageMapInfo.PxeBase = MM_PXE_LA57_BASE;
MmpPageMapInfo.P5eBase = MM_P5E_LA57_BASE;
Offset = ((((ULONGLONG)Address & (((ULONGLONG)1 << 48) - 1)) >> MM_PPI_SHIFT) << MM_PTE_SHIFT);
return (PMMPTE)(MM_PPE_BASE + Offset);
}
/* PML5 use 57-bit virtual addresses */
MmpPageMapInfo.VaBits = 57;
}
else
{
/* XPA disabled, use LA48 paging (PML4) */
MmpPageMapRoutines = &MmpPml4Routines;
/**
* Gets the address of the PTE (Page Table Entry), that maps given address.
*
* @param Address
* Specifies the address to find the PTE for.
*
* @return This routine returns the address of the PTE.
*
* @since XT 1.0
*/
XTAPI
PMMPTE
MmpGetPteAddress(PVOID Address)
{
ULONGLONG Offset;
/* Set PML4 page map information */
MmpPageMapInfo.Xpa = FALSE;
Offset = ((((ULONGLONG)Address & (((ULONGLONG)1 << 48) - 1)) >> MM_PTI_SHIFT) << MM_PTE_SHIFT);
return (PMMPTE)(MM_PTE_BASE + Offset);
}
/* Set PML4 base addresses */
MmpPageMapInfo.PteBase = MM_PTE_BASE;
MmpPageMapInfo.PdeBase = MM_PDE_BASE;
MmpPageMapInfo.PpeBase = MM_PPE_BASE;
MmpPageMapInfo.PxeBase = MM_PXE_BASE;
MmpPageMapInfo.P5eBase = 0x0;
/**
* Gets the address of the PXE (Extended Page Entry), that maps given address.
*
* @param Address
* Specifies the address to find the PXE for.
*
* @return This routine returns the address of the PXE.
*
* @since XT 1.0
*/
XTAPI
PMMPTE
MmpGetPxeAddress(PVOID Address)
{
ULONGLONG Offset;
Offset = (((ULONGLONG)Address >> MM_PXI_SHIFT) & (MM_PXE_PER_PAGE - 1));
return (PMMPTE)(MM_PXE_BASE + Offset);
/* PML use 48-bit virtual addresses */
MmpPageMapInfo.VaBits = 48;
}
}
/**
@@ -102,18 +73,3 @@ MmpInitializeArchitecture(VOID)
{
UNIMPLEMENTED;
}
/**
* Checks if LA57 (PML5) is enabled.
*
* @return This routine returns TRUE if LA57 is enabled, or FALSE otherwise.
*
* @since XT 1.0
*/
XTAPI
BOOLEAN
MmpMemoryExtensionEnabled(VOID)
{
/* Check if LA57 (PML5) is enabled */
return ((ArReadControlRegister(4) & CR4_LA57) != 0) ? TRUE : FALSE;
}

216
xtoskrnl/mm/amd64/pmap.c Normal file
View File

@@ -0,0 +1,216 @@
/**
* PROJECT: ExectOS
* COPYRIGHT: See COPYING.md in the top level directory
* FILE: xtoskrnl/mm/amd64/pmap.c
* DESCRIPTION: Low-level support for AMD64 page map manipulation
* DEVELOPERS: Aiken Harris <harraiken91@gmail.com>
*/
#include <xtos.h>
/**
* Clears the contents of a page table entry (PTE).
*
* @param PtePointer
* Pointer to the page table entry (PTE) to be cleared.
*
* @return This routine does not return any value.
*
* @since XT 1.0
*/
XTAPI
VOID
MmpClearPte(PHARDWARE_PTE PtePointer)
{
PtePointer->CacheDisable = 0;
PtePointer->PageFrameNumber = 0;
PtePointer->Valid = 0;
PtePointer->Writable = 0;
PtePointer->WriteThrough = 0;
}
/**
* Checks if eXtended Physical Addressing (XPA) is enabled.
*
* @return This routine returns TRUE if LA57 is enabled, or FALSE otherwise.
*
* @since XT 1.0
*/
XTAPI
BOOLEAN
MmpGetExtendedPhysicalAddressingStatus(VOID)
{
/* Check if LA57 is enabled */
return ((ArReadControlRegister(4) & CR4_LA57) != 0) ? TRUE : FALSE;
}
/**
* Gets the address of the P5E (Page Map Level 5 Entry), that maps given address.
*
* @param Address
* Specifies the virtual address for which to retrieve the corresponding P5E.
*
* @return This routine returns the address of the P5E, or NULL if LA57 is not enabled.
*
* @since XT 1.0
*/
XTAPI
PMMP5E
MmpGetP5eAddress(PVOID Address)
{
ULONGLONG Offset;
Offset = ((((ULONGLONG)Address & (((ULONGLONG)1 << MmpPageMapInfo.VaBits) - 1)) >> MM_P5I_SHIFT) << MM_PTE_SHIFT);
return (PMMP5E)((MmpPageMapInfo.P5eBase + Offset) * MmpPageMapInfo.Xpa);
}
/**
* Gets the address of the PDE (Page Directory Entry), that maps given address.
*
* @param Address
* Specifies the virtual address for which to retrieve the corresponding PDE.
*
* @return This routine returns the address of the PDE.
*
* @since XT 1.0
*/
XTAPI
PMMPDE
MmpGetPdeAddress(PVOID Address)
{
ULONGLONG Offset;
Offset = ((((ULONGLONG)Address & (((ULONGLONG)1 << MmpPageMapInfo.VaBits) - 1)) >> MM_PDI_SHIFT) << MM_PTE_SHIFT);
return (PMMPDE)(MmpPageMapInfo.PdeBase + Offset);
}
/**
* Gets the address of the PPE (Page Directory Pointer Table Entry), that maps given address.
*
* @param Address
* Specifies the virtual address for which to retrieve the corresponding PPE.
*
* @return This routine returns the address of the PPE.
*
* @since XT 1.0
*/
XTAPI
PMMPPE
MmpGetPpeAddress(PVOID Address)
{
ULONGLONG Offset;
Offset = ((((ULONGLONG)Address & (((ULONGLONG)1 << MmpPageMapInfo.VaBits) - 1)) >> MM_PPI_SHIFT) << MM_PTE_SHIFT);
return (PMMPPE)(MmpPageMapInfo.PpeBase + Offset);
}
/**
* Gets the address of the PTE (Page Table Entry), that maps given address.
*
* @param Address
* Specifies the virtual address for which to retrieve the corresponding PTE.
*
* @return This routine returns the address of the PTE.
*
* @since XT 1.0
*/
XTAPI
PMMPTE
MmpGetPteAddress(PVOID Address)
{
ULONGLONG Offset;
Offset = ((((ULONGLONG)Address & (((ULONGLONG)1 << MmpPageMapInfo.VaBits) - 1)) >> MM_PTI_SHIFT) << MM_PTE_SHIFT);
return (PMMPTE)(MmpPageMapInfo.PteBase + Offset);
}
/**
* Gets the address of the PXE (Extended Page Entry), that maps given address.
*
* @param Address
* Specifies the virtual address for which to retrieve the corresponding PXE.
*
* @return This routine returns the address of the PXE.
*
* @since XT 1.0
*/
XTAPI
PMMPXE
MmpGetPxeAddress(PVOID Address)
{
ULONGLONG Offset;
Offset = ((((ULONGLONG)Address & (((ULONGLONG)1 << MmpPageMapInfo.VaBits) - 1)) >> MM_PXI_SHIFT) << MM_PTE_SHIFT);
return (PMMPXE)(MmpPageMapInfo.PxeBase + Offset);
}
/**
* Checks whether the given page table entry (PTE) is valid.
*
* @param PtePointer
* Pointer to the page table entry (PTE) to check.
*
* @return Returns TRUE if the entry is valid, FALSE otherwise.
*
* @since XT 1.0
*/
XTAPI
BOOLEAN
MmpPteValid(PHARDWARE_PTE PtePointer)
{
return (BOOLEAN)PtePointer->Valid;
}
/**
* Sets a page table entry (PTE) with the specified physical page and access flags.
*
* @param PtePointer
* Pointer to the page table entry (PTE) to set.
*
* @param PageFrameNumber
* Physical frame number to map.
*
* @param Writable
* Indicates whether the page should be writable.
*
* @return This routine does not return any value.
*
* @since XT 1.0
*/
XTAPI
VOID
MmpSetPte(PHARDWARE_PTE PtePointer,
PFN_NUMBER PageFrameNumber,
BOOLEAN Writable)
{
PtePointer->PageFrameNumber = PageFrameNumber;
PtePointer->Valid = 1;
PtePointer->Writable = Writable;
}
/**
* Sets caching attributes for a page table entry (PTE).
*
* @param PtePointer
* Pointer to the page table entry (PTE) to modify.
*
* @param CacheDisable
* Indicates whether caching should be disabled for this page.
*
* @param WriteThrough
* Indicates whether write-through caching should be enabled.
*
* @return This routine does not return any value.
*
* @since XT 1.0
*/
XTAPI
VOID
MmpSetPteCaching(PHARDWARE_PTE PtePointer,
BOOLEAN CacheDisable,
BOOLEAN WriteThrough)
{
PtePointer->CacheDisable = CacheDisable;
PtePointer->WriteThrough = WriteThrough;
}

View File

@@ -24,9 +24,6 @@ ULONG MmNumberOfPhysicalPages;
/* Old biggest free memory descriptor */
LOADER_MEMORY_DESCRIPTOR MmOldFreeDescriptor;
/* Page Map Level */
ULONG MmPageMapLevel;
/* Processor structures data (THIS IS A TEMPORARY HACK) */
UCHAR MmProcessorStructuresData[MAXIMUM_PROCESSORS][KPROCESSOR_STRUCTURES_SIZE] = {0};
@@ -36,8 +33,11 @@ LOADER_MEMORY_DESCRIPTOR MmpHardwareAllocationDescriptors[MM_HARDWARE_ALLOCATION
/* Live address of kernel's hardware heap */
PVOID MmpHardwareHeapStart = MM_HARDWARE_HEAP_START_ADDRESS;
/* Architecture-specific memory extension */
BOOLEAN MmpMemoryExtension;
/* Information about the current page map */
MMPAGEMAP_INFO MmpPageMapInfo;
/* Pointers to page map routines for the current paging mode */
PCMMPAGEMAP_ROUTINES MmpPageMapRoutines;
/* Number of used hardware allocation descriptors */
ULONG MmpUsedHardwareAllocationDescriptors = 0;

View File

@@ -190,7 +190,7 @@ MmMapHardwareMemory(IN PHYSICAL_ADDRESS PhysicalAddress,
ReturnAddress = (PVOID)(ULONG_PTR)ReturnAddress + MM_PAGE_SIZE;
/* Check if PTE is valid */
if(PtePointer->Valid)
if(MmpPageMapRoutines->PteValid(PtePointer))
{
/* PTE is not available, go to the next one */
BaseAddress = ReturnAddress;
@@ -219,9 +219,7 @@ MmMapHardwareMemory(IN PHYSICAL_ADDRESS PhysicalAddress,
PtePointer = (PHARDWARE_PTE)MmpGetPteAddress(BaseAddress);
/* Fill the PTE */
PtePointer->PageFrameNumber = (PFN_NUMBER)(PhysicalAddress.QuadPart >> MM_PAGE_SHIFT);
PtePointer->Valid = 1;
PtePointer->Writable = 1;
MmpPageMapRoutines->SetPte(PtePointer, (PFN_NUMBER)(PhysicalAddress.QuadPart >> MM_PAGE_SHIFT), TRUE);
/* Advance to the next address */
PhysicalAddress.QuadPart += MM_PAGE_SIZE;
@@ -268,8 +266,7 @@ MmMarkHardwareMemoryWriteThrough(IN PVOID VirtualAddress,
for(Page = 0; Page < PageCount; Page++)
{
/* Mark pages as CD/WT */
PtePointer->CacheDisable = 1;
PtePointer->WriteThrough = 1;
MmpPageMapRoutines->SetPteCaching(PtePointer, TRUE, TRUE);
PtePointer++;
}
}
@@ -302,9 +299,7 @@ MmRemapHardwareMemory(IN PVOID VirtualAddress,
PtePointer = (PHARDWARE_PTE)MmpGetPteAddress(VirtualAddress);
/* Remap the PTE */
PtePointer->PageFrameNumber = (PFN_NUMBER)(PhysicalAddress.QuadPart >> MM_PAGE_SHIFT);
PtePointer->Valid = 1;
PtePointer->Writable = 1;
MmpPageMapRoutines->SetPte(PtePointer, (PFN_NUMBER)(PhysicalAddress.QuadPart >> MM_PAGE_SHIFT), TRUE);
/* Check if TLB needs to be flushed */
if(FlushTlb)
@@ -356,11 +351,7 @@ MmUnmapHardwareMemory(IN PVOID VirtualAddress,
for(Page = 0; Page < PageCount; Page++)
{
/* Unmap the PTE and get the next one */
PtePointer->CacheDisable = 0;
PtePointer->Valid = 0;
PtePointer->Writable = 0;
PtePointer->WriteThrough = 0;
PtePointer->PageFrameNumber = 0;
MmpPageMapRoutines->ClearPte(PtePointer);
PtePointer++;
}

View File

@@ -0,0 +1,26 @@
/**
* PROJECT: ExectOS
* COPYRIGHT: See COPYING.md in the top level directory
* FILE: xtoskrnl/mm/i686/globals.c
* DESCRIPTION: i686-specific global variables for the Memory Manager
* DEVELOPERS: Aiken Harris <harraiken91@gmail.com>
*/
#include <xtos.h>
/* Page mapping routines for systems using 2-level paging (PML2) */
CMMPAGEMAP_ROUTINES MmpPml2Routines = {
.ClearPte = MmpClearPte,
.PteValid = MmpPml2PteValid,
.SetPteCaching = MmpSetPml2PteCaching,
.SetPte = MmpSetPml2Pte,
};
/* Page mapping routines for systems using 3-level paging (PML3) */
CMMPAGEMAP_ROUTINES MmpPml3Routines = {
.ClearPte = MmpClearPte,
.PteValid = MmpPml3PteValid,
.SetPteCaching = MmpSetPml3PteCaching,
.SetPte = MmpSetPml3Pte,
};

View File

@@ -4,51 +4,56 @@
* FILE: xtoskrnl/mm/i686/init.c
* DESCRIPTION: Architecture specific Memory Manager initialization routines
* DEVELOPERS: Rafal Kupiec <belliash@codingworkshop.eu.org>
* Aiken Harris <harraiken91@gmail.com>
*/
#include <xtos.h>
/**
* Gets the address of the PDE (Page Directory Entry), that maps given address.
* Detects if eXtended Physical Addressing (XPA) is enabled and initializes page map support.
*
* @param Address
* Specifies the address to find the PDE for.
*
* @return This routine returns the address of the PDE.
* @return This routine does not return any value.
*
* @since XT 1.0
*/
XTAPI
PMMPTE
MmpGetPdeAddress(PVOID Address)
VOID
MmInitializePageMapSupport(VOID)
{
ULONG Offset;
/* Check if XPA is enabled */
if(MmpGetExtendedPhysicalAddressingStatus())
{
/* XPA enabled, use modern PAE paging (PML3) */
MmpPageMapRoutines = &MmpPml3Routines;
/* Calculate offset and return PTE address */
Offset = ((((ULONG)(Address)) >> MM_PDI_SHIFT) << MM_PTE_SHIFT);
return (PMMPTE)(MM_PDE_BASE + Offset);
}
/* Set PML3 page map information */
MmpPageMapInfo.Xpa = TRUE;
/**
* Gets the address of the PTE (Page Table Entry), that maps given address.
*
* @param Address
* Specifies the address to find the PTE for.
*
* @return This routine returns the address of the PTE.
*
* @since XT 1.0
*/
XTAPI
PMMPTE
MmpGetPteAddress(PVOID Address)
{
ULONG Offset;
/* Set PML3 base addresses */
MmpPageMapInfo.PteBase = MM_PTE_BASE;
MmpPageMapInfo.PdeBase = MM_PDE_BASE;
/* Calculate offset and return PTE address */
Offset = ((((ULONG)(Address)) >> MM_PTI_SHIFT) << MM_PTE_SHIFT);
return (PMMPTE)(MM_PTE_BASE + Offset);
/* Set PML3 shift values */
MmpPageMapInfo.PdiShift = MM_PDI_SHIFT;
MmpPageMapInfo.PteShift = MM_PTE_SHIFT;
}
else
{
/* XPA disabled, use legacy i386 paging (PML2) */
MmpPageMapRoutines = &MmpPml2Routines;
/* Set PML2 page map information */
MmpPageMapInfo.Xpa = FALSE;
/* Set PML2 base addresses */
MmpPageMapInfo.PteBase = MM_PTE_BASE;
MmpPageMapInfo.PdeBase = MM_PDE_LEGACY_BASE;
/* Set PML2 shift values */
MmpPageMapInfo.PdiShift = MM_PDI_LEGACY_SHIFT;
MmpPageMapInfo.PteShift = MM_PTE_LEGACY_SHIFT;
}
}
/**
@@ -64,18 +69,3 @@ MmpInitializeArchitecture(VOID)
{
UNIMPLEMENTED;
}
/**
* Checks if PAE (Physical Address Extension) is enabled.
*
* @return This routine returns TRUE if PAE is enabled, or FALSE otherwise.
*
* @since XT 1.0
*/
XTAPI
BOOLEAN
MmpMemoryExtensionEnabled(VOID)
{
/* Check if PAE is enabled */
return ((ArReadControlRegister(4) & CR4_PAE) != 0) ? TRUE : FALSE;
}

242
xtoskrnl/mm/i686/pmap.c Normal file
View File

@@ -0,0 +1,242 @@
/**
* PROJECT: ExectOS
* COPYRIGHT: See COPYING.md in the top level directory
* FILE: xtoskrnl/mm/i686/pmap.c
* DESCRIPTION: Low-level support for i686 page map manipulation
* DEVELOPERS: Aiken Harris <harraiken91@gmail.com>
*/
#include <xtos.h>
/**
* Clears the contents of a page table entry (PTE).
*
* @param PtePointer
* Pointer to the page table entry (PTE) to be cleared.
*
* @return This routine does not return any value.
*
* @since XT 1.0
*/
XTAPI
VOID
MmpClearPte(PHARDWARE_PTE PtePointer)
{
PtePointer->Long = 0;
}
/**
* Checks if eXtended Physical Addressing (XPA) is enabled.
*
* @return This routine returns TRUE if PAE is enabled, or FALSE otherwise.
*
* @since XT 1.0
*/
XTAPI
BOOLEAN
MmpGetExtendedPhysicalAddressingStatus(VOID)
{
/* Check if PAE is enabled */
return ((ArReadControlRegister(4) & CR4_PAE) != 0) ? TRUE : FALSE;
}
/**
* Gets the address of the PDE (Page Directory Entry), that maps given address.
*
* @param Address
* Specifies the virtual address for which to retrieve the corresponding PDE.
*
* @return This routine returns the address of the PDE.
*
* @since XT 1.0
*/
XTAPI
PMMPDE
MmpGetPdeAddress(PVOID Address)
{
ULONG Offset;
/* Calculate offset and return PTE address */
Offset = ((((ULONG)(Address)) >> MmpPageMapInfo.PdiShift) << MmpPageMapInfo.PteShift);
return (PMMPTE)(MmpPageMapInfo.PdeBase + Offset);
}
/**
* Gets the address of the PPE (Page Directory Pointer Table Entry), that maps given address.
*
* @param Address
* Specifies the virtual address for which to retrieve the corresponding PDE.
*
* @return This routine returns the address of the PPE.
*
* @since XT 1.0
*/
XTAPI
PMMPPE
MmpGetPpeAddress(PVOID Address)
{
/* Return zero */
return 0;
}
/**
* Gets the address of the PTE (Page Table Entry), that maps given address.
*
* @param Address
* Specifies the virtual address for which to retrieve the corresponding PTE.
*
* @return This routine returns the address of the PTE.
*
* @since XT 1.0
*/
XTAPI
PMMPTE
MmpGetPteAddress(PVOID Address)
{
ULONG Offset;
/* Calculate offset and return PTE address */
Offset = ((((ULONG)(Address)) >> MM_PTI_SHIFT) << MmpPageMapInfo.PteShift);
return (PMMPTE)(MM_PTE_BASE + Offset);
}
/**
* Checks whether the given PML2 page table entry (PTE) is valid.
*
* @param PtePointer
* Pointer to the page table entry (PTE) to check.
*
* @return Returns TRUE if the entry is valid, FALSE otherwise.
*
* @since XT 1.0
*/
XTAPI
BOOLEAN
MmpPml2PteValid(PHARDWARE_PTE PtePointer)
{
return (BOOLEAN)PtePointer->Pml2.Valid;
}
/**
* Sets a PML2 page table entry (PTE) with the specified physical page and access flags.
*
* @param PtePointer
* Pointer to the page table entry (PTE) to set.
*
* @param PageFrameNumber
* Physical frame number to map.
*
* @param Writable
* Indicates whether the page should be writable.
*
* @return This routine does not return any value.
*
* @since XT 1.0
*/
XTAPI
VOID
MmpSetPml2Pte(PHARDWARE_PTE PtePointer,
PFN_NUMBER PageFrameNumber,
BOOLEAN Writable)
{
PtePointer->Pml2.PageFrameNumber = PageFrameNumber;
PtePointer->Pml2.Valid = 1;
PtePointer->Pml2.Writable = Writable;
}
/**
* Sets caching attributes for a PML2 page table entry (PTE).
*
* @param PtePointer
* Pointer to the page table entry (PTE) to modify.
*
* @param CacheDisable
* Indicates whether caching should be disabled for this page.
*
* @param WriteThrough
* Indicates whether write-through caching should be enabled.
*
* @return This routine does not return any value.
*
* @since XT 1.0
*/
XTAPI
VOID
MmpSetPml2PteCaching(PHARDWARE_PTE PtePointer,
BOOLEAN CacheDisable,
BOOLEAN WriteThrough)
{
PtePointer->Pml2.CacheDisable = CacheDisable;
PtePointer->Pml2.WriteThrough = WriteThrough;
}
/**
* Checks whether the given PML3 page table entry (PTE) is valid.
*
* @param PtePointer
* Pointer to the page table entry (PTE) to check.
*
* @return Returns TRUE if the entry is valid, FALSE otherwise.
*
* @since XT 1.0
*/
XTAPI
BOOLEAN
MmpPml3PteValid(PHARDWARE_PTE PtePointer)
{
return PtePointer->Pml3.Valid;
}
/**
* Sets a PML3 page table entry (PTE) with the specified physical page and access flags.
*
* @param PtePointer
* Pointer to the page table entry (PTE) to set.
*
* @param PageFrameNumber
* Physical frame number to map.
*
* @param Writable
* Indicates whether the page should be writable.
*
* @return This routine does not return any value.
*
* @since XT 1.0
*/
XTAPI
VOID
MmpSetPml3Pte(PHARDWARE_PTE PtePointer,
PFN_NUMBER PageFrameNumber,
BOOLEAN Writable)
{
PtePointer->Pml3.PageFrameNumber = PageFrameNumber;
PtePointer->Pml3.Valid = 1;
PtePointer->Pml3.Writable = Writable;
}
/**
* Sets caching attributes for a PML3 page table entry (PTE).
*
* @param PtePointer
* Pointer to the page table entry (PTE) to modify.
*
* @param CacheDisable
* Indicates whether caching should be disabled for this page.
*
* @param WriteThrough
* Indicates whether write-through caching should be enabled.
*
* @return This routine does not return any value.
*
* @since XT 1.0
*/
XTAPI
VOID
MmpSetPml3PteCaching(PHARDWARE_PTE PtePointer,
BOOLEAN CacheDisable,
BOOLEAN WriteThrough)
{
PtePointer->Pml3.CacheDisable = CacheDisable;
PtePointer->Pml3.WriteThrough = WriteThrough;
}

View File

@@ -31,9 +31,6 @@ MmInitializeMemoryManager(VOID)
KePanic(0);
}
/* Store Page Map Level */
MmPageMapLevel = KeInitializationBlock->LoaderInformation.PageMapLevel;
/* Proceed with architecture specific initialization */
MmpInitializeArchitecture();
}

View File

@@ -27,8 +27,8 @@
*/
XTAPI
SIZE_T
RtlCompareString(IN CONST PCHAR String1,
IN CONST PCHAR String2,
RtlCompareString(IN PCSTR String1,
IN PCSTR String2,
IN SIZE_T Length)
{
SIZE_T Index;
@@ -79,8 +79,8 @@ RtlCompareString(IN CONST PCHAR String1,
*/
XTAPI
SIZE_T
RtlCompareStringInsensitive(IN CONST PCHAR String1,
IN CONST PCHAR String2,
RtlCompareStringInsensitive(IN PCSTR String1,
IN PCSTR String2,
IN SIZE_T Length)
{
CHAR Character1;
@@ -206,7 +206,7 @@ RtlConcatenateString(OUT PCHAR Destination,
XTAPI
VOID
RtlCopyString(IN PCHAR Destination,
IN PCCHAR Source,
IN PCSTR Source,
IN ULONG Length)
{
ULONG Index;
@@ -229,6 +229,131 @@ RtlCopyString(IN PCHAR Destination,
Destination[Index] = '\0';
}
/**
* Finds the first occurrence of the search string in the source string.
*
* @param Source
* Supplies a pointer to the source string.
*
* @param Search
* Supplies a pointer to the search string.
*
* @return This routine returns a pointer to the first occurrence of the search string in the source string.
*
* @since XT 1.0
*/
XTAPI
PCSTR
RtlFindString(IN PCSTR Source,
IN PCSTR Search)
{
PCSTR CurrentSource;
PCSTR CurrentSearch;
/* Validate input parameters */
if(!Source || !Search)
{
/* Invalid input parameters, return NULL */
return NULL;
}
/* Check if search string is empty */
if(*Search == '\0')
{
/* Return the source string */
return Source;
}
/* Iterate through the source string */
for(; *Source != '\0'; Source++) {
/* Initialize pointers */
CurrentSource = Source;
CurrentSearch = Search;
/* Check if the substring matches starting at the current position */
while(*CurrentSource != '\0' && *CurrentSearch != '\0' && *CurrentSource == *CurrentSearch)
{
/* Go to the next character */
CurrentSource++;
CurrentSearch++;
}
/* If we reached the end of Search string, it is a match */
if(*CurrentSearch == '\0')
{
/* Return the source position */
return Source;
}
}
/* No match found, return NULL */
return NULL;
}
/**
* Finds the first case-insensitive occurrence of the search string in the source string.
*
* @param Source
* Supplies a pointer to the source string.
*
* @param Search
* Supplies a pointer to the search string.
*
* @return This routine returns a pointer to the first occurrence of the search string in the source string.
*
* @since XT 1.0
*/
XTAPI
PCSTR
RtlFindStringInsensitive(IN PCSTR Source,
IN PCSTR Search)
{
PCSTR CurrentSource;
PCSTR CurrentSearch;
/* Validate input parameters */
if(!Source || !Search)
{
/* Invalid input parameters, return NULL */
return NULL;
}
/* Check if search string is empty */
if(*Search == '\0')
{
/* Return the source string */
return Source;
}
/* Iterate through the source string */
for(; *Source != '\0'; Source++) {
/* Initialize pointers */
CurrentSource = Source;
CurrentSearch = Search;
/* Check if the substring matches starting at the current position */
while(*CurrentSource != '\0' && *CurrentSearch != '\0' &&
RtlToLowerCharacter(*CurrentSource) == RtlToLowerCharacter(*CurrentSearch))
{
/* Go to the next character */
CurrentSource++;
CurrentSearch++;
}
/* If we reached the end of Search string, it is a match */
if(*CurrentSearch == '\0')
{
/* Return the source position */
return Source;
}
}
/* No match found, return NULL */
return NULL;
}
/**
* Reverses a characters order in a string. It modifies the original, input variable.
*
@@ -275,7 +400,7 @@ RtlReverseString(IN OUT PCHAR String,
*/
XTAPI
SIZE_T
RtlStringLength(IN CONST PCHAR String,
RtlStringLength(IN PCSTR String,
IN SIZE_T MaxLength)
{
SIZE_T Length;
@@ -321,33 +446,44 @@ RtlStringLength(IN CONST PCHAR String,
XTAPI
SIZE_T
RtlStringToWideString(OUT PWCHAR Destination,
IN CONST PCHAR *Source,
IN PCSTR *Source,
IN SIZE_T Length)
{
PCHAR LocalSource = *Source;
PCSTR LocalSource = *Source;
SIZE_T Count = Length;
/* Check if NULL pointer passed */
if(Destination == NULL)
{
/* No wide characters written */
return 0;
}
/* Iterate through the string */
while(Count)
{
/* Copy character */
if((*Destination = *LocalSource) == 0)
{
/* End of string reached */
LocalSource = NULL;
break;
}
/* Check if character is valid */
if(*Destination >= 0x80)
{
/* Invalid character, return error */
return -1;
}
/* Advance pointers */
LocalSource++;
Destination++;
Count--;
}
/* Return number of wide characters written */
return Length - Count;
}
@@ -370,7 +506,7 @@ RtlStringToWideString(OUT PWCHAR Destination,
XTAPI
PCHAR
RtlTokenizeString(IN PCHAR String,
IN CONST PCHAR Delimiter,
IN PCSTR Delimiter,
IN OUT PCHAR *SavePtr)
{
PCHAR Span, Token;
@@ -399,14 +535,18 @@ RtlTokenizeString(IN PCHAR String,
Span = (PCHAR)Delimiter;
do
{
/* Check if delimiter found */
if((SpanChar = *Span++) == Char)
{
/* Check if end of string reached */
if(Char == '\0')
{
/* End of string reached, no more tokens */
String = NULL;
}
else
{
/* Terminate token */
String[-1] = '\0';
}
@@ -421,6 +561,56 @@ RtlTokenizeString(IN PCHAR String,
}
}
/**
* Converts a character to lowercase.
*
* @param Character
* Character to be converted.
*
* @return Converted character or original character if it was not uppercase.
*
* @since XT 1.0
*/
XTAPI
CHAR
RtlToLowerCharacter(IN CHAR Character)
{
/* Check if character is uppercase */
if(Character >= 'A' && Character <= 'Z')
{
/* Convert character to lowercase */
return (CHAR)(Character + ('a' - 'A'));
}
/* Return original character */
return Character;
}
/**
* Converts a character to uppercase.
*
* @param Character
* Character to be converted.
*
* @return Converted character or original character if it was not lowercase.
*
* @since XT 1.0
*/
XTAPI
CHAR
RtlToUpperCharacter(IN CHAR Character)
{
/* Check if character is lowercase */
if(Character >= 'a' && Character <= 'z')
{
/* Convert character to uppercase */
return (CHAR)(Character - ('a' - 'A'));
}
/* Return original character */
return Character;
}
/**
* Removes certain characters from a beginning of the string.
*
@@ -433,7 +623,7 @@ RtlTokenizeString(IN PCHAR String,
*/
XTAPI
PCHAR
RtlTrimLeftString(IN CONST PCHAR String)
RtlTrimLeftString(IN PCHAR String)
{
PCHAR Start;
@@ -463,7 +653,7 @@ RtlTrimLeftString(IN CONST PCHAR String)
*/
XTAPI
PCHAR
RtlTrimRightString(IN CONST PCHAR String)
RtlTrimRightString(IN PCHAR String)
{
PCHAR End;
@@ -496,7 +686,7 @@ RtlTrimRightString(IN CONST PCHAR String)
*/
XTAPI
PCHAR
RtlTrimString(IN CONST PCHAR String)
RtlTrimString(IN PCHAR String)
{
return RtlTrimLeftString(RtlTrimRightString(String));
}

View File

@@ -27,8 +27,8 @@
*/
XTAPI
SIZE_T
RtlCompareWideString(IN CONST PWCHAR String1,
IN CONST PWCHAR String2,
RtlCompareWideString(IN PCWSTR String1,
IN PCWSTR String2,
IN SIZE_T Length)
{
SIZE_T Index;
@@ -79,8 +79,8 @@ RtlCompareWideString(IN CONST PWCHAR String1,
*/
XTAPI
SIZE_T
RtlCompareWideStringInsensitive(IN CONST PWCHAR String1,
IN CONST PWCHAR String2,
RtlCompareWideStringInsensitive(IN PCWSTR String1,
IN PCWSTR String2,
IN SIZE_T Length)
{
WCHAR Character1;
@@ -124,7 +124,7 @@ RtlCompareWideStringInsensitive(IN CONST PWCHAR String1,
Index++;
}
/* Wide strings are equal */
/* Strings are equal */
return 0;
}
@@ -207,7 +207,7 @@ RtlConcatenateWideString(OUT PWCHAR Destination,
XTAPI
VOID
RtlCopyWideString(IN PWCHAR Destination,
IN CONST PWCHAR Source,
IN PCWSTR Source,
IN ULONG Length)
{
ULONG Index;
@@ -230,6 +230,131 @@ RtlCopyWideString(IN PWCHAR Destination,
Destination[Index] = L'\0';
}
/**
* Finds the first occurrence of the search wide string in the source wide string.
*
* @param Source
* Supplies a pointer to the source wide string.
*
* @param Search
* Supplies a pointer to the search wide string.
*
* @return This routine returns a pointer to the first occurrence of the search wide string in the source wide string.
*
* @since XT 1.0
*/
XTAPI
PCWSTR
RtlFindWideString(IN PCWSTR Source,
IN PCWSTR Search)
{
PCWSTR CurrentSource;
PCWSTR CurrentSearch;
/* Validate input parameters */
if(!Source || !Search)
{
/* Invalid input parameters, return NULL */
return NULL;
}
/* Check if search string is empty */
if(*Search == L'\0')
{
/* Return the source string */
return Source;
}
/* Iterate through the source string */
for(; *Source != L'\0'; Source++) {
/* Initialize pointers */
CurrentSource = Source;
CurrentSearch = Search;
/* Check if the substring matches starting at the current position */
while(*CurrentSource != L'\0' && *CurrentSearch != L'\0' && *CurrentSource == *CurrentSearch)
{
/* Go to the next character */
CurrentSource++;
CurrentSearch++;
}
/* If we reached the end of Search string, it is a match */
if(*CurrentSearch == L'\0')
{
/* Return the source position */
return Source;
}
}
/* No match found, return NULL */
return NULL;
}
/**
* Finds the first case-insensitive occurrence of the search wide string in the source wide string.
*
* @param Source
* Supplies a pointer to the source wide string.
*
* @param Search
* Supplies a pointer to the search wide string.
*
* @return This routine returns a pointer to the first occurrence of the search wide string in the source wide string.
*
* @since XT 1.0
*/
XTAPI
PCWSTR
RtlFindWideStringInsensitive(IN PCWSTR Source,
IN PCWSTR Search)
{
PCWSTR CurrentSource;
PCWSTR CurrentSearch;
/* Validate input parameters */
if(!Source || !Search)
{
/* Invalid input parameters, return NULL */
return NULL;
}
/* Check if search string is empty */
if(*Search == L'\0')
{
/* Return the source string */
return Source;
}
/* Iterate through the source string */
for(; *Source != L'\0'; Source++) {
/* Initialize pointers */
CurrentSource = Source;
CurrentSearch = Search;
/* Check if the substring matches starting at the current position */
while(*CurrentSource != L'\0' && *CurrentSearch != L'\0' &&
RtlToLowerWideCharacter(*CurrentSource) == RtlToLowerWideCharacter(*CurrentSearch))
{
/* Go to the next character */
CurrentSource++;
CurrentSearch++;
}
/* If we reached the end of Search string, it is a match */
if(*CurrentSearch == L'\0')
{
/* Return the source position */
return Source;
}
}
/* No match found, return NULL */
return NULL;
}
/**
* Formats a wide string according to the given printf-alike format string.
*
@@ -355,7 +480,7 @@ RtlReverseWideString(IN OUT PWCHAR String,
XTAPI
PWCHAR
RtlTokenizeWideString(IN PWCHAR String,
IN CONST PWCHAR Delimiter,
IN PCWSTR Delimiter,
IN OUT PWCHAR *SavePtr)
{
PWCHAR Span, Token;
@@ -384,14 +509,18 @@ RtlTokenizeWideString(IN PWCHAR String,
Span = (PWCHAR)Delimiter;
do
{
/* Check if delimiter found */
if((SpanChar = *Span++) == Char)
{
/* Check if end of string reached */
if(Char == L'\0')
{
/* End of string reached, no more tokens */
String = NULL;
}
else
{
/* Terminate token */
String[-1] = L'\0';
}
@@ -406,6 +535,56 @@ RtlTokenizeWideString(IN PWCHAR String,
}
}
/**
* Converts a wide character to lowercase.
*
* @param Character
* Wide character to be converted.
*
* @return Converted wide character or original character if it was not uppercase.
*
* @since XT 1.0
*/
XTAPI
WCHAR
RtlToLowerWideCharacter(IN WCHAR Character)
{
/* Check if wide character is uppercase */
if(Character >= L'A' && Character <= L'Z')
{
/* Convert wide character to lowercase */
return (WCHAR)(Character + (L'a' - L'A'));
}
/* Return original wide character */
return Character;
}
/**
* Converts a wide character to uppercase.
*
* @param Character
* Wide character to be converted.
*
* @return Converted wide character or original character if it was not lowercase.
*
* @since XT 1.0
*/
XTAPI
WCHAR
RtlToUpperWideCharacter(IN WCHAR Character)
{
/* Check if wide character is lowercase */
if(Character >= L'a' && Character <= L'z')
{
/* Convert wide character to uppercase */
return (WCHAR)(Character - (L'a' - L'A'));
}
/* Return original wide character */
return Character;
}
/**
* Removes certain characters from a beginning of the wide string.
*
@@ -418,7 +597,7 @@ RtlTokenizeWideString(IN PWCHAR String,
*/
XTAPI
PWCHAR
RtlTrimLeftWideString(IN CONST PWCHAR String)
RtlTrimLeftWideString(IN PWCHAR String)
{
PWCHAR Start;
@@ -448,7 +627,7 @@ RtlTrimLeftWideString(IN CONST PWCHAR String)
*/
XTAPI
PWCHAR
RtlTrimRightWideString(IN CONST PWCHAR String)
RtlTrimRightWideString(IN PWCHAR String)
{
PWCHAR End;
@@ -481,7 +660,7 @@ RtlTrimRightWideString(IN CONST PWCHAR String)
*/
XTAPI
PWCHAR
RtlTrimWideString(IN CONST PWCHAR String)
RtlTrimWideString(IN PWCHAR String)
{
return RtlTrimLeftWideString(RtlTrimRightWideString(String));
}
@@ -501,7 +680,7 @@ RtlTrimWideString(IN CONST PWCHAR String)
*/
XTAPI
SIZE_T
RtlWideStringLength(IN CONST PWCHAR String,
RtlWideStringLength(IN PCWSTR String,
IN SIZE_T MaxLength)
{
SIZE_T Length;

View File

@@ -55,6 +55,10 @@
@ stdcall RtlDivideLargeInteger(long long long ptr)
@ stdcall RtlFindClearBits(ptr long long)
@ stdcall RtlFindSetBits(ptr long long)
@ stdcall RtlFindString(str str)
@ stdcall RtlFindStringInsensitive(str str)
@ stdcall RtlFindWideString(wstr wstr)
@ stdcall RtlFindWideStringInsensitive(wstr wstr)
@ stdcall RtlInitializeBitMap(ptr ptr long)
@ stdcall RtlMoveMemory(ptr ptr long)
@ stdcall RtlMultiplyLargeInteger(long long long)
@@ -74,6 +78,10 @@
@ stdcall RtlTestBit(ptr long)
@ stdcall RtlTokenizeString(str str str)
@ stdcall RtlTokenizeWideString(wstr wstr wstr)
@ stdcall RtlToLowerCharacter(long)
@ stdcall RtlToLowerWideCharacter(long)
@ stdcall RtlToUpperCharacter(long)
@ stdcall RtlToUpperWideCharacter(long)
@ stdcall RtlTrimLeftString(str)
@ stdcall RtlTrimLeftWideString(wstr)
@ stdcall RtlTrimRightString(str)