Commit graph

1677 commits

Author SHA1 Message Date
Timo Kreuzer 26a64324e7 [NTOSKRNL/x64] Fix a bug in KeSwitchKernelStack
Don't safe anything in the callee's home space, because the callee can overwrite it. Use the functions home space instead.
2023-09-17 10:37:50 +03:00
Ratin Gao 4c8a2a8815
[KERNEL32][KERNEL32_APITEST] Implement user-mode UEFI / Firmware API (#5149)
- Implement firmware environment variable read/write APIs
- Add, fix and improve related definitions and declarations
- Add kernel32:UEFIFirmware apitest

CORE-11954
2023-09-14 22:14:07 +03:00
Timo Kreuzer 9666f00572 [WIN32K][NTOS] Fix parameter to MmMapViewOfSection
The code was passing 0 instead of SECTION_INHERIT::ViewUnmap (2). 0 isn't even a proper constant to be used here. It worked, because MmMapViewOfSection only compares against ViewShare (1) and treats everything else as ViewUnmap.
2023-09-09 12:15:24 +03:00
Timo Kreuzer 583be404dd [NTOSKRNL/x64] Fix bug in KiInitializeContextThread
The function set CtxSwitchFrame->ApcBypass to FALSE, preventing APCs (like when user mode sets the context while the thread is suspended) from being delivered as soon as the thread lowers IRQL to PASSIVE_LEVEL. This resulted in the SetContext APC to be delivered only after the user mode APC was initialized, overwriting the user mode APC context in the trap frame. This caused kernel32_winetest process to break.
2023-09-07 01:16:14 +03:00
Joachim Henze 195c491880 [NTOSKRNL] Mute some good-path log-spam, no functional change
Now that the Memory Management is a bit more under control again,
and branching releases/0.4.15 is near,
do mute some frequent log-spam that got introduced during 0.4.15-dev'ing
regarding lazy-flushes and MM balancing.
It frequently logged even while being idle.
Slightly improve the headers of the two touched files.
No rocket-science.
2023-09-06 14:53:53 +02:00
Doug Lyons 2b14056600
[NTOS:CC][NTOS:MM] Add back CcRosTrimCache and add Delay for MM to work. (#5630)
MM/CC Add back CcRosTrimCache as suggested by Thomas Faber which was removed in 0.4.15-dev-1717-g 	d8cdb89fb0
and call it once in a while also during read-operations.

fixes JIRA issue: CORE-17624 'Cannot copy files > RAMsize anymore using TotalCommander'


1st testbot results on top of 0.4.15-dev-6526-g8d35887
VBox: https://reactos.org/testman/compare.php?ids=89111,89120 (additional random reboot in winhttp:winhttp)
KVM: https://reactos.org/testman/compare.php?ids=89110,89119
We do assume that reboot to be unrelated.

2nd testbot results on top of 0.4.15-dev-6526-g8d35887
VBox: https://reactos.org/testman/compare.php?ids=89111,89232
KVM: https://reactos.org/testman/compare.php?ids=89110,89233
2023-09-06 13:34:25 +02:00
Hermès Bélusca-Maïto c66a1582ac
[NTOS:EX] Add some missing PoNotifySystemTimeSet() calls. Stub out NtSetSystemTime() with NULL parameter.
- They notify, via the "\\Callback\\SetSystemTime" callback, components
  of a change of system time (for example, Win32k).
  Note, that our Win32k currently does not handle power callouts, so
  it isn't affected by these changes (yet).

- NtSetSystemTime(NULL, ...) means "update system time using the current
  time-zone information", which is something we don't implement yet.
  (And, nothing was previously protecting this call from a NULL parameter...)
2023-09-03 17:39:39 +02:00
Hermès Bélusca-Maïto b2294b4c84
[NTOS:KD] Fix release builds. 2023-08-31 17:10:34 +02:00
Hermès Bélusca-Maïto 0d0ffb7d7d
[NTOS:KD:KDBG] Integration into KD framework (Part 2/3)
Add redirections for KdSave/KdRestore and KdD0Transition/KdD3Transition.

Both KDBG and KD(TERM) need those since they will become external
transport DLLs later.
2023-08-31 16:09:49 +02:00
Hermès Bélusca-Maïto 2046a17ef4
[NTOS:KD:KDBG] Integration into KD framework (Part 1/3)
Split KdSendPacket and KdReceivePacket into those that manipulate the
KDBG state proper (reside in kdbg/kdbg.c), and those that deal only with
debug input/output that will reside in a KDTERM "KD Terminal Driver" DLL.

Based on some previous preparatory work by Hervé Poussineau in PR #4600.
(Equivalents of commits 5162bf106 and partly e9bcf7275.)
2023-08-31 16:07:51 +02:00
Hermès Bélusca-Maïto 8c0c2e2be7
[NTOS:KDBG] Temporarily HACK-remove the duplicated kdb:> when displaying the interactive KDBG prompt. 2023-08-30 12:24:36 +02:00
Hermès Bélusca-Maïto 86e0d5e9b8
[NTOS:MM/PS] Remove code duplication between LookupEntryPoint/MiLocateExportName/MiFindExportedRoutineByName. (#4918)
As it turns out, those three functions were duplicating the same code
between each other. Reimplement these in terms of a common helper,
RtlFindExportedRoutineByName().
Indeed: MiFindExportedRoutineByName() was just MiLocateExportName()
but taking a PANSI_STRING instead of a NULL-terminated string.

A similar state of affairs also existed in Windows <= 2003, and the
MS guys also noticed it. Both routines have been then merged and renamed
to MiFindExportedRoutineByName() on Windows 8 (taking a PCSTR instead),
and finally renamed and exported as RtlFindExportedRoutineByName()
on Windows 10.
2023-08-29 17:26:57 +02:00
Hermès Bélusca-Maïto d8695eee1e
[NTOS:MM] Add missing validation of Ordinal in MiLocateExportName (#4918) 2023-08-29 17:26:57 +02:00
Hermès Bélusca-Maïto 4e55236662
[NTOS:MM/PS] De-duplicate export name-to-ordinal functionality (#4918)
It was implemented in psmgr.c but in a recursive way. That implementation
is replaced, in the NameToOrdinal() helper, by the better non-recursive one
found in the MiLocateExportName() and MiFindExportedRoutineByName() functions.

This NameToOrdinal() helper is then called in lieu of the duplicated code
in MiLocateExportName() and MiFindExportedRoutineByName(). In addition,
one block of code in MiSnapThunk() is simplified in a similar manner.
2023-08-29 17:26:56 +02:00
Hermès Bélusca-Maïto e8b048a282
[NTOS:MM] Reformat MmCallDllInitialize and MiCallDllUnloadAndUnloadDll. 2023-08-29 17:26:55 +02:00
unknown 310563aece
[NTOS:SE] Let SepGetSidFromAce figure out the ACE type
As the commit title says. Instead of having the caller figuring out what
the ACE type should be of the ACE.
2023-08-23 17:54:47 +02:00
George Bișoc 8289de6ef7
[NTOS:SE] Cast the ACE to known ACE type variants on SepGetSidFromAce
ACCESS_DENIED_ACE_TYPE, ACCESS_ALLOWED_ACE_TYPE, SYSTEM_AUDIT_ACE_TYPE and
SYSTEM_ALARM_ACE_TYPE belong to the same commonly internal ACE type, aka KNOWN_ACE,
as each of these ACEs have the same structure field offsets.

The only difference are ACCESS_DENIED_OBJECT_ACE_TYPE and ACCESS_ALLOWED_OBJECT_ACE_TYPE
as they have their own internal ACE type variant, the KNOWN_OBJECT_ACE structure.

The general guideline is that public ACE structure variants have to be used elsehwere
such as in UM whilst the kernel has to use the internal known ACE type variants when possible.
2023-08-22 17:54:18 +02:00
George Bișoc a42f642ea1
[NTOS:SE] Implement access security checks by type
- Implement SepDenyAccessObjectTypeResultList, SepAllowAccessObjectTypeResultList,
SepDenyAccessObjectTypeList and SepAllowAccessObjectTypeList. These routines will
be used to grant or deny access to sub-objects of an object in the list.

- Refactor SepAnalyzeAcesFromDacl and SepAccessCheck to accomodate the newly
implemented access check by type mechanism.

- SepAccessCheck will now be SepAccessCheckWorker, a worker helper function that further
abstracts the access check mechanism in the kernel. Whereas the SepAccessCheck name will be
used as a centralized function used by the access check NT system calls.

- Deprecate SepGetSDOwner and SepGetSDGroup in favor of SepGetOwnerFromDescriptor and
SepGetGroupFromDescriptor. The former functions were buggy as they might potentially
return garbage data if either the owner or group were passed as NULL to a security
descriptor, hence a second chance exception fault. This was caught when writing tests
for NtAccessCheckByType.

- Shorten the debug prints by removing the name of the functions, the person who reads
the debugger output has to look at the source code anyway.
2023-08-22 17:54:17 +02:00
George Bișoc e38f4c2b36
[NTOS:SE] Implement object type list utilities
This implements various private kernel routines for object type list management
needed for access check code infrastructure. In addition, update the code documentation
and add missing comments.
2023-08-22 17:54:17 +02:00
George Bișoc 5f3fab72a9
[NTOS:SE] Implement SepDumpAccessAndStatusList
This function will dump all the access status and granted access rights
of each object list of a list whenever an access check by type (or by type
result list) fails. This is for debugging purposes.
2023-08-22 17:54:17 +02:00
George Bișoc 5654ce7b9a
[NTOS:SE] Declare function prototypes & add OBJECT_TYPE_LIST_INTERNAL
OBJECT_TYPE_LIST_INTERNAL will serve as an internal kernel data structure
to hold validated object type contents that are copied from UM.

The difference between the public and the internal one is that the internal structure has
an additional member for access check rights that have been granted on each
object element in the list.
2023-08-22 17:54:17 +02:00
Hermès Bélusca-Maïto 5472c3e853
[NTOS:MM] MiResolveImageReferences: Use boolean values for GdiLink and NormalLink. 2023-08-19 19:06:20 +02:00
Doug Lyons e6ca3952e0
[NTOS:CC] Fix locking of CcRosVacbIncRefCount in CcRosCreateVacb (#5527)
CORE-17624
2023-08-12 19:10:34 +02:00
Timo Kreuzer 9bc5b8357a [NTOS:MM] Fix use-after-free error
The VAD / memory area can get deleted when calling MmUnmapViewOfSegment, so it must not be used after that.
2023-08-05 11:57:58 +03:00
Joachim Henze 53b30e3f3b [NTOSKRNL][NTGDI] Formatting addendum, no functional change
I intend to port back the combined work of Thomas Faber and Serge Gautherie in context of CORE 14271.
Both developers fixed wrong retval evaluations for SeSinglePrivilegeCheck() and RtlCreateUnicodeString().
Both functions do return a BOOLEAN, and therefore using NTSTATUS() on them is wrong.
Those bugs have been fixed at multiple places. That is long gone.

But Serge fixed his locations a bit more elegantly, without the need for additional variables.
Therefore this addendum adapts a few of Thomas locations to the improved Serge-ified style.

Yes: I intentionally used a space instead of a minus after the mentioned CORE 14271,
as I don't want that pure stylistic addendum to be linked with the initial ticket anymore.
That would be overkill.
2023-08-01 22:32:25 +02:00
Timo Kreuzer 539c316589 [NTOS:Mm] Fix some 64 bit issues 2023-07-29 14:00:44 +03:00
Jérôme Gardou 69daff72d2 NTOS:CC Free some VACBs when we're under memory pressure 2023-07-29 14:00:44 +03:00
Jérôme Gardou 470ad18825 Revert "[NTOS:CC] Wake up lazy scan after inserting elements in the list."
This reverts commit 6e4f83da70.
2023-07-29 14:00:44 +03:00
Timo Kreuzer 876769fdd5 [NTOS:Mm] Use MmRebalanceMemoryConsumersAndWait in the page fault handler 2023-07-29 14:00:44 +03:00
Timo Kreuzer 047dc9729f [NTOS:Mm] Implement MmRebalanceMemoryConsumersAndWait 2023-07-29 14:00:44 +03:00
Timo Kreuzer 7c6e4d38c7 [NTOS:Mm] Handle failure to allocate pages in the page fault handler 2023-07-29 14:00:44 +03:00
Timo Kreuzer 3ae12d5a8c [NTOS:Mm] Fail gracefully when no pages are available 2023-07-29 14:00:44 +03:00
Timo Kreuzer d7de53b6d5 [NTOS:Mm] Bail out in MmTrimUserMemory, when all LRU pages have been looped through 2023-07-29 14:00:44 +03:00
Timo Kreuzer 5f014e421b [NTOS:Mm] Handle RosMm pages in MiDecrementReferenceCount
This is required, when RosMm unmaps locked pages and they later get unlocked.
2023-07-29 14:00:44 +03:00
Timo Kreuzer 80dd9f5a90 [NTOS:Mm] Add PFN ShareCount handling to old Mm 2023-07-29 14:00:44 +03:00
Timo Kreuzer 73de609917 [NTOS:Mm] Implement MmCreatePhysicalMapping and MmDeletePhysicalMapping to handle pyhsical memory sections 2023-07-29 14:00:44 +03:00
Timo Kreuzer 918e331970 [NTOS:Mm] Fix race condition in _MmSetPageEntrySectionSegment
The function updates the entry in the section page table and updates the section association rmaps for it. In the page-in path, when the new section association is set before the entry is updated, a concurrent attempt to unmap the page would find an inconsistent entry, where there is an rmap, but the section page table entry is still an MM_WAIT_ENTRY.
2023-07-29 14:00:44 +03:00
Timo Kreuzer 54d1b39676 [NTOS:Mm] Fix locking for MmGetSectionAssociation
MmGetSectionAssociation races with _MmSetPageEntrySectionSegment without sharing a lock. So we need to hold the PFN lock, until we have referenced the section segment found in the RMAP. This prevents that a section segment, which still has associated RMAPs from being deleted behind our back.
2023-07-29 14:00:44 +03:00
Timo Kreuzer 477792856e [NTOS:Mm] Replace YieldProcessor() with KeDelayExecutionThread()
These are used in the paging path, when the page is currently in the process of being read from or written to the disk. While YieldProcessor() provides the chance to switch context to the other paging thread, it only does so, once the current thread's quantum has expired. On a single CPU system this effectively leads to busy waiting for the rest of the quantum. On SMP systems this could succeed earlier, thus reducing latency, but it would still contribute to high CPU usage, while waiting for the IO operation to complete, which is not what we want.
Using KeDelayExecutionThread() will instantly allow another thread to run, providing enough time to complete the IO operation.
2023-07-29 14:00:44 +03:00
Jérôme Gardou 57e018acf6 [NTOS:MM] Use FORCEINLINE instead of simple inline
inline implies an implementation must exist in another compilation unit
2023-07-23 23:58:42 +02:00
Stanislav Motylkov e2a587c2ef [NTOS:KE/x64] Calculate the CPU frequency on AMD64
This should be performed early enough before CM initialization,
but after the TSC has been initialized and calibrated by HAL.

Based on existing i386 kiinit code. CORE-17971 CORE-14922
2023-07-15 20:50:12 +03:00
Justin Miller dabe7fba46
[NTOS:IO] Implement IoConnectInterruptEx for fully specified interrupt types (#5416)
Implement IoConnectInterruptEx() for CONNECT_FULLY_SPECIFIED.
This gives ability to load various modern drivers that use IoConnectInterruptEx.

Various drivers work after this change, such as serial.sys MS sample driver when compiled with the reactos tree and many more KMDF drivers from later Windows versions.

Co-authored-by: Victor Perevertkin <victor@perevertkin.ru>
2023-07-14 16:17:27 -07:00
Stanislav Motylkov 5ae65ab7a7 [NTOS:KE] Add x86 CPU features reporting to AMD64
CORE-18023 CORE-14922
2023-07-02 21:00:32 +03:00
Stanislav Motylkov 6a6b383abd [NTOS:KE] Report x86 CPU features in a separate function
KiGetFeatureBits() is now being called in the early boot phase 0
when the Kernel Debugger is not yet initialized, so debug prints
are not available here. Move the debug prints into a new function
and call it at the right time. CORE-18023
2023-07-02 21:00:31 +03:00
Stanislav Motylkov 00715ccf8b [NTOS:KE] Fix magic constants for x86 CPU features
Do it the same way as in amd64 ke.h/cpu.c. CORE-18023
2023-07-02 21:00:31 +03:00
Eugen Podrug 8e01dee251 [NTOS:EX] Fix swapped values in ExGetCurrentProcessorCounts() (#4565)
The function should return the kernel time for the idle thread in the
first argument, and kernel time + user time for the current thread in
the second argument.

Also retrieve the processor number from the cached PRCB instead of
calling KeGetCurrentProcessorNumber() which retrieves the PRCB again
since the processor could switch in-between those calls.

NdisGetCurrentProcessorCounts() function follows the same prototype
which is the correct one.
2023-07-02 16:10:36 +03:00
Victor Perevertkin 8cfc4a3376
[NTOS:PNP] Complete the PlugPlayControlInitializeDevice control class
Besides creating the PDO and device node for it, it has to set up the
necessary registry keys, and register PDO at PnP root driver properly.

CORE-18989
2023-06-29 19:25:28 +03:00
Victor Perevertkin 6cac5b8c9e
[NTOS:PNP] Refactor PnpRootCreateDevice
- Remove unused "DriverObject" argument
- Make "FullInstancePath" mandatory
- Extract the PDO creation into separate function, it will be used later
2023-06-29 19:25:28 +03:00
Victor Perevertkin bbf64c0cc4
[NTOS:PNP] Do not create an extra "PDO" device inside PnP root driver
The root device object is in fact a PDO and a FDO at the same time. Thus
there is no need in creating two device objects here, one is enough.
This commit also removes the explicit device extension for the root DO,
because the only reason it existed is to distinguish the root driver's
FDO from its PDOs. This can easily be done by comparing with
IopRootDeviceNode.

Also collect some unused garbage while we are here.
2023-06-29 19:25:25 +03:00
Hermès Bélusca-Maïto 6409f97bc4
[NTOS:CONFIG] Use correct "Interface" variable type; use InterfaceTypeUndefined instead of -1. 2023-06-25 21:25:06 +02:00
George Bișoc 0972f71d9a
[NTOS:PNP] Assert the presence of a device extension when handling PnP root power IRPs
Handling PnP root driver power IRPs requires that a device object must come up
with a device extension to determine whether it is a function driver and if so,
handle the IRP accordingly.

CORE-18989
2023-06-18 20:44:13 +02:00
Hermès Bélusca-Maïto 84b4a80beb
[NTOS:IO] Fix some bugs in the IoQueryDeviceDescription helpers (#5320)
- Add missing ExAllocatePool NULL checks.

- Fix order of KeBugCheckEx parameters for PNP_DETECTED_FATAL_ERROR.

- The Controller and Peripheral numbers are zero-based, so if the caller
  wants to inspect controller (or peripheral) zero, let it be so!
  The original code was treating controller number zero for enumerating
  controllers of a given class within the different buses, which is
  wrong. See the diff'ed trace below.
  Tested with Windows' videoprt.sys VideoPortGetDeviceData().

```diff
 IoQueryDeviceDescription()
     BusType:          0xB093C224 (0)
     BusNumber:        0xB093C228 (0)
     ControllerType:   0xF9D01030 (19)
     ControllerNumber: 0xF9D01038 (0)
     PeripheralType:   0x00000000 (4294967295)
     PeripheralNumber: 0x00000000 (4294967295)
     CalloutRoutine:   0xF9CF74E4
     Context:          0xF9D5A340
 --> Query: 0xF9D5A22C

 IopQueryBusDescription(Query: 0xF9D5A22C)
     RootKey: '\REGISTRY\MACHINE\HARDWARE\DESCRIPTION\SYSTEM'
     RootKeyHandle: 0x00000598
     KeyIsRoot: TRUE
     Bus: 0xF9D5A290 (4294967295)
     Seen: 'CentralProcessor'
     Seen: 'FloatingPointProcessor'
     Seen: 'MultifunctionAdapter'
     SubRootRegName: '\REGISTRY\MACHINE\HARDWARE\DESCRIPTION\SYSTEM\MultifunctionAdapter'

 IopQueryBusDescription(Query: 0xF9D5A22C)
     RootKey: '\REGISTRY\MACHINE\HARDWARE\DESCRIPTION\SYSTEM\MultifunctionAdapter'
     RootKeyHandle: 0x00000590
     KeyIsRoot: FALSE
     Bus: 0xF9D5A290 (4294967295)
     Seen: '0'
     SubRootRegName: '\REGISTRY\MACHINE\HARDWARE\DESCRIPTION\SYSTEM\MultifunctionAdapter\0'
     Getting bus value: 'Identifier'
     Getting bus value: 'Configuration Data'
     Getting bus value: 'Component Information'
     --> Getting device on Bus #0 : '\REGISTRY\MACHINE\HARDWARE\DESCRIPTION\SYSTEM\MultifunctionAdapter\0'

 IopQueryDeviceDescription(Query: 0xF9D5A22C)
     RootKey: '\REGISTRY\MACHINE\HARDWARE\DESCRIPTION\SYSTEM\MultifunctionAdapter\0'
     RootKeyHandle: 0x00000590
     Bus: 0
-    Enumerating controllers in '\REGISTRY\MACHINE\HARDWARE\DESCRIPTION\SYSTEM\MultifunctionAdapter\0\DisplayController'...
+    Getting controller #0
+    Retrieving controller '\REGISTRY\MACHINE\HARDWARE\DESCRIPTION\SYSTEM\MultifunctionAdapter\0\DisplayController\0'
```
2023-06-14 11:20:56 +02:00
Stanislav Motylkov 7d5e159131 [NTOS:PNP] Assign correct PnP IDs to the devices detected by bootloader
Based on a commit by Vadim Galyant:
5ef5c11e7f

Also fix a minor type conversion warning. CORE-18963 CORE-17977

Co-authored-by: Vadim Galyant <vgal@rambler.ru>
2023-06-11 16:19:02 +03:00
Sophie Lemos 29a706fc5a [NTOS:PNP] Fix bug causing all devices be considered as already existing
We should compare against DeviceObject as DeviceInstance is never NULL.
Fix a resource leak as well. The bug CORE-18983 seems to lay somewhere
else though, I just stumbled upon this one while researching it.

Note there is a BSOD in the PnP manager on reboot after the driver
installation failure, but it seems it was uncovered by the fix
as opposed to caused by it.
2023-06-11 13:13:11 +03:00
George Bișoc 59e74584ac
[NTOS:SE] Refactor SeTokenCanImpersonate
- Refactor most of the code, since there's quite some stuff that don't make much sense.
For instance ImpersonationLevel is basically the requested impersonation level a
server asks for. PsImpersonateClient doesn't explicitly say that SecurityAnonymous
and SecurityIdentification are not allowed. If the server was to give such levels
it simply means it doesn't want to impersonate the client.

Another thing that doesn't make much sense is that we check if the client is
associated with an anonymous token, then avoid impersonating regular anonymous
tokens that weren't created by the system. Only system can create such tokens
and an anonymous token basically means a token with hidden security info.

- Check that the server is within the same client logon session.

- If the server is granted the SeImpersonatePrivilege privilege, allow impersonation
regardless of the conditions we want to check for.

- Update the documentation and code comments.
2023-06-09 11:53:56 +02:00
George Bișoc 8e2fe925f2
[NTOS:PS] Do not reference the copied token twice and properly assign the impersonation level in case the server can't impersonate
As it currently stands the PsImpersonateClient routine does the following approach.
If impersonation couldn't be granted to a client the routine will make a copy
of the client's access token. As it makes a copy of the said token PsImpersonateClient
will reference the copied token after impersonation info have been filled out.
In the same code path we are assigning the desired level for impersonation to thread
impersonation info.

This is wrong for two reasons:

- On a copy situation the SeCopyClientToken routine holds a reference as the object
has been created. Referencing it at the bottom of the PsImpersonateClient routine
will make it that the token is referenced twice and whenever a server stops
impersonation the token still has an extra reference count which keeps the token
still alive in object database and memory space.

- If client impersonation is not possible the thread impersonation info should
have been assigned SecurityIdentification level to further indicate that the
actual impersonation of the thread is not currently in force but instead we
are assigning the impersonation level that is supplied by the caller. For instance
if the requested level is SecurityDelegation but impersonation is not possible
the level will be assigned that of SecurityDelegation yet the token has an
impersonation level of SecurityIdentification. This could lead to erratic behaviors
as well as potential impersonation escalation.

Fix the aforementioned issues by avoiding a double reference and properly assign
the impersonation level to SecurityIdentification if the server is not able to
impersonate the target client.
2023-06-09 11:53:55 +02:00
George Bișoc f483e42f89
[NTOS:SE] Grant the SYSTEM process the missing privileges
- Add the missing privileges to the SYSTEM privileges which might be needed,
notably SeUndockPrivilege, SeManageVolumePrivilege, SeCreateGlobalPrivilege and
SeImpersonatePrivilege.

Specifically SeImpersonatePrivilege is important here because with it we
allow system components of the core OS to perform certain system tasks.

- Declare the Groups array with a maximum of 3 elements in SepCreateSystemProcessToken
and 1 element in SepCreateSystemAnonymousLogonToken respectively, because previously
this array was oversized with most of free space left as a waste.

- Avoid hardcoding the size value of the Privilege array, instead initialize it
by hand and compute the exact number of elements with RTL_NUMBER_OF.
2023-06-09 11:53:51 +02:00
Hermès Bélusca-Maïto 0b695a6f70
[NTOS:IO] iorsrce.c: Add DBG traces for bus/device enumeration functions. 2023-06-04 21:40:08 +02:00
Hermès Bélusca-Maïto 2674e26cbb
[NTOS:IO] Reformat iorsrce.c, no functional code changes.
- Fix whitespace; add SAL annotations, doxygen documentation...

- Deduplicate the array of description strings corresponding to
  IO_QUERY_DEVICE_DATA_FORMAT.

- Unhardcode the "[3]" into 'IoQueryDeviceMaxData': the maximum number
  of device data queried.
2023-06-04 21:40:07 +02:00
Hermès Bélusca-Maïto 6db0d24fb6
Fix typo "managment" -> "management" in our codebase...
... except for 3rd-party code or "official" names.
2023-06-04 21:39:56 +02:00
George Bișoc 51279c3e44
[NTOS:SE] Refactor NtOpenThreadTokenEx
- Wrap most of the code into a new private routine, SepOpenThreadToken.
And properly fail gracefully if we fail to open a thread's token instead of just keeping going.

- Do not use the same thread object that we have referenced in NtOpenThreadTokenEx
to do a copy of the access token in case we can't open it directly.
Instead we must reference a new object with full access, solely used for
the purpose to do our required operations.

- Add debug prints

CORE-18986
2023-06-04 11:09:34 +02:00
George Bișoc a389f8aa0c
[NTOS:SE] Make an access token effective after the end of token duplication
Removing any disabled privileges or groups in the middle of token dynamic
part allocation can pose problems. During the operation of making an access
token as effective, we are toying with the privileges and groups arrays
of the token.

After that we are allocating the dynamic part and set EndMem (the end tail
of the memory part) to that dynamic part, previously it was set to the
variable part. As a matter of fact we are making the token effective in
the middle where EndMem still points to VariablePart, thus DynamicPart
will end up with memory pool blocks butchered in the pool list.

Another problem, albeit not related to the DynamicPart corruption, is that
the code starts iterating over the UserAndGroups array from 0, which is
the actual user. One cannot simply remove the user from the array, so we
have to start looping right from the groups.

Move the token effective code part at the end of the SepDuplicateToken
function, which fixes the random pool corruptions caused by the butchered
DynamicPart.

CORE-18986
2023-06-04 11:09:22 +02:00
Stanislav Motylkov 85ca8afb60
[NTOS:PNP] IopEnumerateDetectedDevices(): General refactoring
CORE-18962

- Deduplicate a while-loop by adding one more recursive call.
- Add IopMapDetectedDeviceId() helper function with a structure
  in order to reduce hardcoded constants and checks.
2023-05-27 12:22:57 +02:00
Hermès Bélusca-Maïto b3c55b9e6c
[NTOS:LPC] Ensure debug-traced pointer-given user-mode data is captured. (#4399)
CORE-18098
2023-05-17 17:40:37 +02:00
Hermès Bélusca-Maïto e4d572a432
[NTOS:LPC] Turn a DPRINT1 into an LPCTRACE. (#4399)
CORE-18098
2023-05-17 17:40:29 +02:00
Timo Kreuzer 15fbcc19b9 [NTOS:KE/x64] Fix KiConvertToGuiThread
- Do not allocate a new stack, if the thread already has a large one. This prevents the function from freeing a large stack as a normal stack and subsequently leaking system PTEs.
- Fix the check for failure of PsConvertToGuiThread (test eax, not rax, for being negative, because by default rax is zero extended from eax, not sign extended). This fixes an infinite loop on failure.
2023-05-16 22:03:13 +03:00
Stanislav Motylkov 059d12a5ac
[NTOS:PNP] IopEnumerateDetectedDevices(): Fix CmResourceList leak
CORE-18962
2023-05-10 20:29:29 +02:00
Stanislav Motylkov 6e3ad0411a
[NTOS:PNP] IopEnumerateDetectedDevices(): Formatting only
CORE-18962
2023-05-08 16:07:11 +02:00
Stanislav Motylkov 484c26d99f
[NTOS:PNP] Move Firmware Mapper functions into new file
CORE-18962
2023-05-08 16:07:01 +02:00
Dmitry Borisov 8df1b53508
[NTOS:CM] Initialize the alternative system architecture field on PC-98 builds (#5136)
This is needed by some 3rd party drivers.
CORE-17977
2023-05-05 18:04:35 +02:00
Timo Kreuzer df72bcd06c [NTOS:KDBG] Only load symbols on x86
Symbol loading leads to a hang on x64 boot in 2nd stage and KDBG symbols don't work on x64 anyway.
2023-05-04 14:09:14 +03:00
George Bișoc 8e7b22a631
[NTOS:OB] Fix the SAL2 annotation of ObQueryTypeInfo
The data has to be written into ObjectTypeInfo based on the return length,
not only what is provided by the input buffer length. Fix suggested by
Hermès.
2023-04-22 17:18:57 +02:00
George Bișoc 00c69bcd15
[NTOS:OB] Properly calculate the return length in ObQueryTypeInfo
On a x86 system aligning the return length pointer to a 4-byte boundary
works best since pointers in general are 4-byte aligned for x86 systems.

However, what happens on a AMD64 system is that we still align this pointer
to 4-byte, ObjectTypeInfo is a 8-byte pointer and we might write into
the return length past the 4-byte boundary.

If one were to allocate a pool of memory with that length and query all
the object types info and free the said pool of memory thereafter, the
system will crash with BAD_POOL_HEADER because ObQueryTypeInfo overwrote
the return length past the 4-byte boundary length therefore leading up with
corrupted memory blocks in the pool header.

This symptom of BAD_POOL_HEADER happens exactly the same in Windows Server
2003 x64 Edition. Newer versions of Windows like 10 aren't affected.

But, Windows has another bug where they are using MaximumLength for the
calculation of the needed length to be returned to caller. MaximumLength
does not guarantee you that it includes the NULL-terminator in the length
and that potentially leads to a buffer overrun.

Also annotate the ObQueryTypeInfo function with SAL2.

https://processhacker.sourceforge.io/doc/object_8c_source.html (read the
comment in KphObjectTypeInformation).
2023-04-21 12:45:31 +02:00
Adam Słaboń 6eb8fe4f82
[NTOS:MM] MmCanFileBeTruncated: Check whether second (optional) parameter was passed (#5248)
Second parameter is optional, so mark it as such and check whether it was passed. Fixes a sporadic 0x24 bugcheck caused by access violation when running ReactOS on NTFS volume with WinXP ntfs.sys.
2023-04-19 23:12:11 +02:00
Timo Kreuzer cb74d9e24e [NTOS/CC] Fix broken usage of _SEH2_FINALLY
Finally handlers are - unlike except blocks - not part of the function they are in, but separate functions, which are called during unwind. PSEH implements them on GCC using nested functions. While "return" from a finally handler is allowed with native SEH, it's handled by the compiler through an extra unwinding operation using _local_unwind, WHICH IS NOT SUPPORTED BY PSEH! With PSEH, returning from a finally handler does not return from the function, instead it will only return from the finally handler and the function will continue below the finally handler as if there was no return at all. To fix this, the return is removed and an additional success check is added.
Also use _SEH_VOLATILE to make sure the variable assignment is not optimized away by the compiler and add zero out the result parameters on error.
2023-04-14 11:56:08 +03:00
Timo Kreuzer b2fcd27aaa [NTOS/CC] Fix calls to CcRosEnsureVacbResident
The function returns BOOLEAN, not NTSTATUS! Also wrap it in SEH, because it can throw an exception on failure.
2023-04-14 11:56:08 +03:00
Hermès Bélusca-Maïto 99b0e4b9a9
[NTOS:KDBG] Only use the direct KdbPrintf instead of KdbpPrint (pager) inside the exception handler (outside the debugger main loop). 2023-04-12 19:30:57 +02:00
Hermès Bélusca-Maïto 9808d32f4a
[NTOS:KDBG] Use local KdbPrintf function for DPRINT1 instead of DbgPrint...
... that would otherwise cause a debugger re-entry.

Also use KdbPuts/Printf instead of KdpDprintf that won't be available
once KDBG is moved out of it.
2023-04-12 19:30:56 +02:00
Hermès Bélusca-Maïto f620ce7705
[NTOS:KDBG] Introduce local versions of KdpPrintString, KdpDprintf and KdpPromptString...
... since the original ones are internal to the kernel and won't be
available once KDBG is moved out of it.

Use these functions in the pager/prompt support.
2023-04-12 19:30:54 +02:00
Hermès Bélusca-Maïto fdf4814ebb
[NTOS:KDBG] Correctly balance KeStackAttachProcess with KeUnstackDetachProcess, instead of KeDetachProcess. 2023-04-11 00:44:11 +02:00
Hermès Bélusca-Maïto 579eab8a31
[NTOS] Include kdbg/kdb.h only in the files that really need it. 2023-04-11 00:44:10 +02:00
Hermès Bélusca-Maïto 30369b8005
[NTOS] "Bugzilla" --> "Jira" 2023-04-05 03:33:41 +02:00
Hermès Bélusca-Maïto dfc2cc4e42
[NTOS:KD] Fix buffer overflow for the signon in KdPortInitializeEx.
The built string can be:
°°Kernel Debugger: Serial port found: COM1 (Port 0x000003F8) BaudRate 115200°°°°
(with ° representing the \r and \n in the message)
and you can verify that this is more than 80 characters in total.
2023-04-05 03:33:39 +02:00
Hermès Bélusca-Maïto 2b27d08576
Grmbl... 2023-04-05 01:53:32 +02:00
Hermès Bélusca-Maïto 143f8549a5
[NTOS:IO] ... and fix build by adding missing header. 2023-04-05 01:45:32 +02:00
Hermès Bélusca-Maïto 4c6f7c01e5
[NTOS:IO] Avoid magic value in LdrProcessDriverModule. 2023-04-05 01:39:32 +02:00
Jérôme Gardou 573d579873
[NTOSKRNL] Flush file to disk when deleting file mappings (#4302)
CORE-17627
When closing a file, fastfat zeroes it out from ValidDataLength up to the end of the file.
The ValidDataLength field is updated when the file content is actually written to disk.
There is currently a race between the file-close path and the page out path, leading to potential file corruptions when the zeroing happens after the memory has been flushed to disk.

Fix this by actually flushing the file to disk when unmapping files, with file lock acquired. This way, the FS driver cannot zero out the tail of the file while we're actually flushing it to disk.
2023-04-01 23:56:49 +09:00
Hermès Bélusca-Maïto 1bb4167211
[NTOS:KD] Fix build, addendum to commit f3dd7133.
This one was more subtle because the prompt (KdIoReadLine) functionality
makes a call-back to KDBG own command history getter function KdbGetHistoryEntry.
It is planned for this to become a registered optional callback pointer.
2023-03-29 03:36:24 +02:00
Hermès Bélusca-Maïto 3c0ba6b22c
Fix build, addendum to commit 35180b3a 2023-03-29 02:55:06 +02:00
Hermès Bélusca-Maïto 35180b3ad2
[NTOS:KDBG] Isolate terminal and input-related routines from the rest of KDBG. (#5188)
This is done in preparation for moving all this functionality in a
separate KDTERM "KD Terminal Driver" DLL.

Additionally:

- Flush the terminal input before sending ANSI escape sequences.

- In KDBG pager, always use the correct reading-key function (the
  same used also for reading keys for a line of user input), and not
  the simplistic two-call KdbpGetCharSerial + KdbpTryGetCharSerial
  that would split the \r \n across calls.

- Call KdbpGetCommandLineSettings() in KdbInitialize() at BootPhase 0,
  which is indirectly called by KdDebuggerInitialize0(). And fix its
  command-line parsing too.
2023-03-29 02:42:31 +02:00
Hermès Bélusca-Maïto f3dd713382
[NTOS:KD:KDBG] Isolate the read-line (prompt) functionality in a separate file.
Rename KdbpReadCommand as KdIoReadLine. Extract the last-command
repetition functionality out of KdIoReadLine and put it where it
belongs: only in the KDBG command main loop KdbpCliMainLoop.
2023-03-28 16:14:40 +02:00
Hermès Bélusca-Maïto 430d7ebb93
[NTOS:KDBG] Use KdbpSendCommandSerial() to send specific ANSI escape sequences.
Use this function instead of KdpDprintf(), otherwise, we send them to
**ALL** the display providers, including for example dmesg. Replaying
the listing with dmesg would then cause the terminal to misbehave later.
For example, it would send the answer of a "Query Device Attributes"
command, as the response to a query for terminal size...
2023-03-28 16:14:39 +02:00
Katayama Hirofumi MZ 3b82b8370d [NTOSKRNL] Fix build in Release; #include 'kd.h' 2023-03-28 17:20:42 +09:00
Hermès Bélusca-Maïto 412037a2e2
[NTOS:KD] Use local print-like functions for output, instead of the kernel-internal KdpDprintf.
Indeed, the latter won't be accessible once those KD IO functions
get moved out into a separate KDTERM.DLL.
2023-03-28 02:42:53 +02:00
Hermès Bélusca-Maïto 6084da8c84
[NTOS:KDBG] Move command history management in a separate file. Simplify duplicated code in KdbpReadCommand. 2023-03-27 23:31:34 +02:00
Hermès Bélusca-Maïto eb02a85214
[NTOS:KD] Split internal/kd.h into a part shared in the whole kernel and a private part only used within ntoskrnl/kd. 2023-03-27 23:31:34 +02:00
Hermès Bélusca-Maïto bfd07a02f1
[NTOS:KD] Update file headers. 2023-03-27 23:31:33 +02:00
Hermès Bélusca-Maïto 6fafe54f89
[NTOS:KD:KDBG] Move some files to a better place. 2023-03-27 23:31:28 +02:00
George Bișoc 29fc7bb33e
[NTOS:OB] Implement name information querying on ObjectBasicInformation case
Currently there is no implementation support for object name information
querying when someone queries information about an object with ObjectBasicInformation
class case. Some device drivers may take use of such information.

NameInfoSize is a size that is the sum of all name directories of an object,
including path separators. TypeInfoSize is a size that is pointed by
the size of a type object itself, therefore this size remains pretty much
fixed depending on the kind of an object.

For more information:
https://www.geoffchappell.com/studies/windows/km/ntoskrnl/inc/api/ntobapi/object_basic_information.htm
http://undocumented.ntinternals.net/index.html?page=UserMode%2FUndocumented%20Functions%2FNT%20Objects%2FType%20independed%2FNtQueryObject.html
2023-03-25 11:55:11 +01:00
Hermès Bélusca-Maïto fe81656776
[NTOS:KD] DbgKdGetStringApi implementation: Ensure the returned string is NULL-terminated.
Addendum to commit 84e32e4e.

Explain more accurately what's going on regarding the returned string
and the inaccurate claims made in the official DbgPrompt documentation
in MSDN. (Has been verified by looking through the traffic in WinDbg
debugging of Windows and ReactOS.)
2023-03-22 19:58:01 +01:00
Hermès Bélusca-Maïto 9d9536d431
[NTOS:KD64] Format string of KdpDprintf can be const. 2023-03-22 19:57:59 +01:00
Hermès Bélusca-Maïto 942b0221e8
[NTOS:KDBG] Temporarily HACK-work-around symbols loading by disabling them at BootPhase 0.
Of course, now that we **correctly** set the LoadSymbools setting,
we attempt loading symbols at BootPhase 0 and everything goes awry!
So introduce that hack to fallback to our old behaviour.

A proper fix (and removal of the hack) will be done in future commits.
2023-03-20 03:10:14 +01:00
Hermès Bélusca-Maïto 934812c4b2
[NTOS:KDBG] Fix parsing the boot command line for the (NO)LOADSYMBOLS options.
Addendum to commit de892d5b.

The boot options get stripped of their optional command switch '/'
(and replaced by whitspace separation) by the NT loader. Also, forbid
the presence of space between the optional '=' character following
(NO)LOADSYMBOLS.

In addition, fix the default initialization of LoadSymbols in KdbSymInit():
we cannot rely on MmNumberOfPhysicalPages in BootPhase 0 since at this point,
the Memory Manager hasn't been initialized and this variable is not yet set.
(We are called by KdInitSystem(0) -> KdDebuggerInitialize0 at kernel init.)
It gets initialized later on between BootPhase 0 and 1.

Also display a nice KDBG signon showing the status of symbols loading.
2023-03-20 02:44:41 +01:00
Hermès Bélusca-Maïto 422621622d
[NTOS:KD] Improve the display of the output providers' signons. 2023-03-18 03:42:32 +01:00
Hermès Bélusca-Maïto a8bcc8d7a1
[NTOS:MM] Simplify definitions of MM_SYSLDR_NO_IMPORTS and MM_SYSLDR_BOOT_LOADED. 2023-03-18 03:42:31 +01:00
Hermès Bélusca-Maïto de892d5bc7
[NTOS:KDBG] Fix the support for /(NO)LOADSYMBOLS as we didn't respect them properly.
LoadSymbols was reset to its default value whenever KdbSymInit() was
called, thus we would e.g. load symbols even if /NOLOADSYMBOLS or
/LOADSYMBOLS=NO were specified at the command line.
2023-03-14 01:17:42 +01:00
Hermès Bélusca-Maïto ab92e40317
[NTOS:KD] Remove unneeded 'extern' declaration. Addendum to commit 4ce819ca. 2023-03-12 02:17:15 +01:00
Hermès Bélusca-Maïto 372eb0c0b8
[NTOS:KDBG] Remove dead code. Addendum to baa47fa5e and fe777bb52. 2023-03-12 02:16:58 +01:00
Hermès Bélusca-Maïto 4ce819ca5a
[NTOS:KD][KDBG] Rework the BootPhase >= 2 initialization of the KD/KDBG kernel debugger. (#4892)
CORE-17470

+ KdpDebugLogInit: Add resources cleanup in failure code paths.

Fix, in an NT-compatible manner, how (and when) the KD/KDBG BootPhase >=2
initialization steps are performed.
These are necessary for any functionality KDBG needs, that would depend
on the NT I/O Manager and the storage and filesystem stacks to be running.
This includes, creating the debug log file, and for KDBG, loading its
KDBinit initialization file.

As a result, file debug logging is fixed.

The old ReactOS-specific (NT-incompatible) callback we did in the middle
of IoInitSystem() is removed, in favor of a runtime mechanism that should
work on Windows as well.

The idea for this new mechanism is loosely inspired by the TDL4 rootkit,
see http://blog.w4kfu.com/public/tdl4_article/draft_tdl4article.html
but contrary to it, a specific hook is used instead, as well as the
technique of driver reinitialization:
https://web.archive.org/web/20211021050515/https://driverentry.com.br/en/blog/?p=261

Its rationale is as follows:

We want to be able to perform I/O-related initialization (starting a
logger thread for file log debugging, loading KDBinit file for KDBG,
etc.). A good place for this would be as early as possible, once the
I/O Manager has started the storage and the boot filesystem drivers.

Here is an overview of the initialization steps of the NT Kernel and
Executive:
----
KiSystemStartup(KeLoaderBlock)
    if (Cpu == 0) KdInitSystem(0, KeLoaderBlock);
    KiSwitchToBootStack() -> KiSystemStartupBootStack()
    -> KiInitializeKernel() -> ExpInitializeExecutive(Cpu, KeLoaderBlock)

(NOTE: Any unexpected debugger break will call KdInitSystem(0, NULL); )
KdInitSystem(0, LoaderBlock) -> KdDebuggerInitialize0(LoaderBlock);

ExpInitializeExecutive(Cpu == 0):    ExpInitializationPhase = 0;
    HalInitSystem(0, KeLoaderBlock); <-- Sets HalInitPnpDriver callback.
    ...
    PsInitSystem(LoaderBlock)
        PsCreateSystemThread(Phase1Initialization)

Phase1Initialization(Discard):       ExpInitializationPhase = 1;
    HalInitSystem(1, KeLoaderBlock);
    ...
    Early initialization of Ob, Ex, Ke.
    KdInitSystem(1, KeLoaderBlock);
    ...
    KdDebuggerInitialize1(LoaderBlock);
    ...
    IoInitSystem(LoaderBlock);
    ...
----
As we can see, KdDebuggerInitialize1() is the last KD initialization
routine the kernel calls, and is called *before* the I/O Manager starts.
Thus, direct Nt/ZwCreateFile ... calls done there would fail. Also,
we want to do the I/O initialization as soon as possible. There does
not seem to be any exported way to be notified about the I/O manager
initialization steps... that is, unless we somehow become a driver and
insert ourselves in the flow!

Since we are not a regular driver, we need to invoke IoCreateDriver()
to create one. However, remember that we are currently running *before*
IoInitSystem(), the I/O subsystem is not initialized yet. Due to this,
calling IoCreateDriver(), much like any other IO functions, would lead
to a crash, because it calls
ObCreateObject(..., IoDriverObjectType, ...), and IoDriverObjectType
is non-initialized yet (it's NULL).

The chosen solution is to hook a "known" exported callback: namely, the
HalInitPnpDriver() callback (it initializes the "HAL Root Bus Driver").
It is set very early on by the HAL via the HalInitSystem(0, ...) call,
and is called early on by IoInitSystem() before any driver is loaded,
but after the I/O Manager has been minimally set up so that new drivers
can be created.
When the hook: KdpInitDriver() is called, we create our driver with
IoCreateDriver(), specifying its entrypoint KdpDriverEntry(), then
restore and call the original HalInitPnpDriver() callback.

Another possible unexplored alternative, could be to insert ourselves
in the KeLoaderBlock->LoadOrderListHead boot modules list, or in the
KeLoaderBlock->BootDriverListHead boot-driver list. (Note that while
we may be able to do this, because boot-drivers are resident in memory,
much like we are, we cannot insert ourselves in the system-driver list
however, since those drivers are expected to come from PE image files.)

Once the KdpDriverEntry() driver entrypoint is called, we register
KdpDriverReinit() for re-initialization with the I/O Manager, in order
to provide more initialization points. KdpDriverReinit() calls the KD
providers at BootPhase >= 2, and schedules further reinitializations
(at most 3 more) if any of the providers request so.
2023-03-11 01:22:19 +01:00
Hervé Poussineau bf734e5373
[NTOS:KD] Move handling of Dmesg buffer from screen provider to KDBG provider. (#5143)
CORE-10749

The dmesg command is now available even if screen output is disabled.

Co-authored-by: Hermès Bélusca-Maïto <hermes.belusca-maito@reactos.org>
2023-03-10 23:59:08 +01:00
Hermès Bélusca-Maïto dfb6996b45
[NTOS:KDBG] Split KdbInitialize into KdbSymInit and KDBG initialization proper.
- KdbSymInit() in kdb_symbols.c only initializes symbols implementation
  support.
- The rest of KdbInitialize gets moved into kdb_cli.c and initializes
  the KDBG debugger itself.
- Move KdbDebugPrint to kdb_cli.c as well.
2023-03-10 20:56:21 +01:00
Hermès Bélusca-Maïto a49732e5b6
[NTOS:KD] KdpDebugLogInit: Fix ZwCreateFile flags for appending to debug logging file.
However, ReactOS currently doesn't handle FILE_APPEND_DATA correctly,
so temporarily add a hack for fixing its support.

CORE-18789
2023-03-09 18:59:16 +01:00
Hermès Bélusca-Maïto a8b09eddc4
[NTOS:KD] Add some annotations. 2023-03-09 18:32:36 +01:00
Hermès Bélusca-Maïto cee893be99
[NTOS:KD] Simplify min-values calculations in KdpPrintToLogFile and KdpScreenPrint. 2023-03-09 18:26:53 +01:00
Hermès Bélusca-Maïto 4585372c6d
[NTOS:IO/KD/KDBG] Formatting fixes only. 2023-03-09 18:26:02 +01:00
George Bișoc 8b75dce45a
[NTOS:SE][FORMATTING] Fix the file header
This fixes the copyright file header at the top of the file, reflecting
the Coding Style rules. No code changes!
2023-03-07 18:39:46 +01:00
George Bișoc b284e82f47
[NTOS:SE] Do not allocate memory pool just for the access rights
Access check is an expensive operation, that is, whenever an access to an
object is performed an access check has to be done to ensure the access
can be allowed to the calling thread who attempts to access such object.

Currently SepAnalyzeAcesFromDacl allocates a block of pool memory for
access check rights, nagging the Memory Manager like a desperate naughty
creep. So instead initialize the access rights as a simple variable in
SepAccessCheck and pass it out as an address to SepAnalyzeAcesFromDacl so
that the function will fill it up with access rights. This helps with
performance, avoiding wasting a few bits of memory just to hold these
access rights.

In addition to that, add a few asserts and fix the copyright header on
both se.h and accesschk.c, to reflect the Coding Style rules.
2023-03-07 17:50:39 +01:00
George Bișoc a804ba3200
[NTOS:SE] Print debug output only if NDEBUG is not defined
This mutes a lot of debug spam that fills up the debugger when an access
check fails because a requestor doesn't have enough privileges to access
an object.
2023-03-06 20:03:44 +01:00
Thomas Faber c0e7eaf403
[NTOS:PNP] Avoid recursion when walking the device tree. 2023-01-22 09:42:08 -05:00
Roy Tam 0d4a8d0ea6 [NTOS:MM] Ignore sections either PointerToRawData or SizeOfRawData is zero
VC1 Linker fills BSS.SizeOfRawData with data in IMAGE_OPTIONAL_HEADER.SizeOfUninitializedData but keeps PointerToRawData to zero.

CORE-18797
2023-01-20 17:02:12 +08:00
Wu Haotian 346477fb3c [NTOS:MM] Use image prefix in MmLoadSystemImage
MmLoadSystemImage has a PUNICODE_STRING NamePrefix parameter which is
currently unused in ReactOS. When the kernel loads the crash dump
storage stack drivers, the drivers will be loaded with MmLoadSystemImage
with a "dump_" or "hiber_" (for hibernation, which uses crash dump
stack too) prefix. This change adds in the prefix support, and is
supposed to push crash dump support forward.

CORE-376
2023-01-18 02:35:19 +03:00
Thomas Faber 543d390259
[NTOS:IO] Handle missing device instance in IopInitializeBuiltinDriver. CORE-18793 2023-01-14 17:52:17 -05:00
Hermès Bélusca-Maïto 84e32e4e90
[NTOS:KD] Revisit KdSendPacket() and KdReceivePacket() for DBGKD_DEBUG_IO. (#4914)
- Use SAL2 annotations.
- KdSendPacket(): Validate DEBUG_IO API call.
- KdReceivePacket(): Take the LengthOfStringRead into account; use
  KdbpReadCommand() to read the input, so that correct line edition
  is available (backspace, etc.)
2023-01-06 18:57:32 +01:00
Hermès Bélusca-Maïto e619f89020
[NTOS:KDBG] Fix and improve KdbpReadCommand(). (#4914)
- Don't read anything and return immediately if the buffer size is zero.

- Allow the controlling keys (up/down arrows, backspace) even if the
  buffer is full! (especially backspace if too much has been written).

- Return the number of characters stored, not counting the NULL terminator.
2023-01-06 14:44:50 +01:00
Hermès Bélusca-Maïto 1b25fe161c
[KERNEL32][NTOS:PS][RTL] Cleanup some DbgPrompt() calls. 2023-01-06 14:44:49 +01:00
Timo Kreuzer 12ed9f30a7 [NTOS] Fix interrupt flag handling in KiPageFault
This fixes a crash in kmtest:ZwAllocateVirtualMemory
2023-01-04 10:32:28 +01:00
Timo Kreuzer 5b6e7eceda [NTOS] Fix KiGeneralProtectionFault 2023-01-04 10:32:28 +01:00
George Bișoc 0bdae2114a
[NTOS:CM] Cleanup the hive in case linking it to master fails (#4969)
Currently the failure code path doesn't do any kind of cleanup against
the hive that was being linked to master. The cleanup is pretty
straightforward as you just simply close the hive file handles and free
the registry kernel structures.

CORE-5772
CORE-17263
CORE-13559
2023-01-03 16:48:03 +01:00
Hermès Bélusca-Maïto 95e5f07084
🎊 🍾 🥳 Happy New Year 2023 to the ReactOS Community! 🎆 ⚛️ ☢️
.:*~*:._.:*~*:._.:*~*:._.:*~*:._.:*~*:._.:*~*:._.:*~*:._.:*~*:._.:*~*:._.:*~*:._.:
 __,  ,__)            __,  ,__)       __, ,__)        ░▄████▄░▄███▄░▄████▄░▄█▀▀█▄░
(--|__| _ ,_ ,_      (--|\ | _       (--\ | _  _ ,_   ░▀▀░▄██░██░██░▀▀░▄██░░░░▄█▀░
  _|  |(_||_)|_)(_|    _| \|(/_(_|_)     \|(/_(_||    ░░▄██▀░░██░██░░▄██▀░░▄░▀▀█▄░
 (        |  |  ,_|   (                (__|           ░██████░▀███▀░██████░▀█▄▄█▀░
.:*~*:._.:*~*:._.:*~*:._.:*~*:._.:*~*:._.:*~*:._.:*~*:._.:*~*:._.:*~*:._.:*~*:._.:
2023-01-01 00:00:00 +03:00
Justin Miller 24d124f99f [NTOS] Set SwapBusy properly for i386
Co-authored-by: Hermès BÉLUSCA - MAÏTO <hermes.belusca-maito@reactos.org>
2022-12-28 21:09:41 +01:00
Justin Miller 2a33aed7cf [NTOS] Increment ActiveProcessors accurately 2022-12-28 21:09:41 +01:00
Justin Miller fbd033df0a [NTOS] fix timer lock data and hardcod 2022-12-28 21:09:41 +01:00
Justin Miller b5c35c03b6 [NTOS] Swap MAXIMUM_PROCESSORS with NUMBER_POOL_LOOKASIDE_LISTS 2022-12-28 21:09:41 +01:00
George Bișoc 9385830b33
[NTOS:CM] Enable verbose debug output of registry lazy flushing component
Log debug output of the lazy flusher as much information as possible so that we can examine how does the lazy flusher behave, since it didn't work for almost a decade. Verbose debugging will be disabled once we're confident enough the registry implementation in ReactOS is rock solid.
2022-12-23 19:45:25 +01:00
George Bișoc 578f2fc512
[NTOS:CM] Don't lazy flush the registry during unlocking operation
Whenever ReactOS finishes its operations onto the registry and unlocks it, a lazy flush is invoked to do an eventual flushing of the registry to the backing storage of the system. Except that... lazy flushing never comes into place.

This is because whenever CmpLazyFlush is called that sets up a timer which needs to expire in order to trigger the lazy flusher engine worker. However, registry locking/unlocking is a frequent occurrence, mainly when on desktop. Therefore as a matter of fact, CmpLazyFlush keeps removing and inserting the timer and the lazy flusher will never kick in that way.

Ironically the lazy flusher actually does the flushing when on USETUP installation phase because during text-mode setup installation in ReactOS the frequency of registry operations is actually less so the timer has the opportunity to expire and fire up the flusher.

In addition to that, we must queue a lazy flush when marking cells as dirty because such dirty data has to be flushed down to the media storage of the system. Of course, the real place where lazy flushing operation is done should be in a subset helper like HvMarkDirty that marks parts of a hive as dirty but since we do not have that, we'll be lazy flushing the registry during cells dirty marking instead for now.

CORE-18303
2022-12-23 19:45:13 +01:00
Eric Kohl 5ff50741dd [NTOS:IO] Replace an outdated E-Mail Address
The old Address will be gone soon.
2022-12-16 10:34:51 +01:00
Timo Kreuzer 2e3fe5de90 [NTOS] Fix saving of XMM registers on some trap handlers 2022-12-13 07:18:24 +01:00
Victor Perevertkin 53de4fd93e
[NTOS:IO] Bring back the NDEBUG definition
Addendum to 947f60b207
2022-12-13 01:49:32 +03:00
Victor Perevertkin 947f60b207
[NTOS:IO] Allow REG_SZ type for ImagePath of a driver
Fixes the load of the Sysinternals FileMon driver.

CORE-18725
2022-12-13 01:46:20 +03:00
Oleg Dubinskiy 82cf6c2b06
[NTOS:IO] Properly zero-initialize a file object created by IopParseDevice (#4931)
Fix uninitialized kernel memory leakage for a case when a file object extension is appended.

CORE-18711
2022-12-08 01:15:42 +03:00
Timo Kreuzer e7bbbf049e [NTOS] Fix double free on allocation failure in ObCreateObject 2022-12-01 20:17:40 +02:00
Timo Kreuzer 561b71b644 [NTOS] Improve MmDeleteProcessAddressSpace 2022-12-01 20:17:40 +02:00
Timo Kreuzer 10fbefdeb0 [NTOS] Improve MmCleanProcessAddressSpace 2022-12-01 20:17:40 +02:00
Timo Kreuzer b89a4eed72 [NTOS:EX] Initialize ExpTimeRefreshLock 2022-12-01 20:17:40 +02:00
Timo Kreuzer 9658c6a220 [NTOSKRNL] Print boot cycles on x64 just like on x86 2022-11-24 21:17:58 +02:00
Timo Kreuzer 225e0c89d9 [NTOS] Fix a bug in KiPrepareUserDebugData 2022-11-24 21:17:58 +02:00
Timo Kreuzer e923912f94 [NTOS] Fix unwinding through KiThreadStartup 2022-11-24 21:17:58 +02:00
Timo Kreuzer a007f5e490 [NTOS] Fix NtContinue for x64 2022-11-24 21:17:58 +02:00
Hermès Bélusca-Maïto f7024d6c72
[PSDK][NTOS:KD64] Turns out, that even Clang in MSVC mode needs the 64-bits pointer extension hack!
Addendum to commit de81021ba.
Otherwise, we get the following build error:

 \ntoskrnl\kd64\kddata.c(532,5): error: initializer element is not a compile-time constant
      PtrToUL64(RtlpBreakWithStatusInstruction),
      ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
 \ntoskrnl\kd64\kddata.c(526,26): note: expanded from macro 'PtrToUL64'
 #define PtrToUL64(x)    ((ULPTR64)(x))
                          ^~~~~~~~~~~~
2022-11-24 13:30:43 +01:00
Hermès Bélusca-Maïto 968b264300
[NTOS:KD] Rename the private acquire/release lock functions to fix GCC compilation.
If you ask why there are two sets of functions that do the same, it's
because this file (and the kdmain.c) will very soon some day be moved to
a transport dll, outside the kernel, and it will need these functions.
2022-11-24 01:44:14 +01:00