Commit graph

1474 commits

Author SHA1 Message Date
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
Hermès Bélusca-Maïto ffb05406e6
[NTOS:KD64] Implement KdLogDbgPrint() for the WinDbg !dbgprint command.
See this command's documentation:
https://docs.microsoft.com/en-us/windows-hardware/drivers/debugger/-dbgprint
and the section "DbgPrint buffer and the debugger"
https://docs.microsoft.com/en-us/windows-hardware/drivers/debugger/reading-and-filtering-debugging-messages#dbgprint-buffer-and-the-debugger
for more details.

- Loosely implement the function, based on our existing circular printout
  buffers in kdio.c.
- Enable its usage in the KdpPrint() and KdpPrompt() functions.

Notice that this function will *only* capture the strings being sent **to**
the debugger, and not the strings the debugger itself produce. (This means
that we cannot use the KdPrintCircularBuffer as a replacement for our
KDBG dmesg one, for example...)

How to test:
Run ReactOS under WinDbg, and use the !dbgprint command to view the
buffer. You can also use the Memory Window, place yourself at the
address pointed by KdPrintCircularBuffer and KdPrintWritePointer, and
read its contents.

What you should observe:
Prior notice: The circular buffer in debug builds of ReactOS and Windows
is 0x8000 bytes large. In release builds, its size is down to 0x1000.
1- When you start e.g. the 2nd-stage GUI installation of ReactOS, going
   past the initial "devices installation" and letting it stabilize on
   the Welcome page, break into WinDbg and run the !dbgprint command. You
   should notice that the end of its output is weirdly truncated, compared
   to what has been actually emitted to the debug output. Comparing this
   with the actual contents of the circular buffer (via Memory Window),
   shows that the buffer contents is actually correct.
2- Copy all the text that has been output by the !dbgprint command and
   paste it in an editor; count the number of all characters appearing +
   newlines (only CR or LF), and observe that this number is "mysteriously"
   equal to 16384 == 0x4000.
3- Continue running ReactOS installation for a little while, breaking back
   back into WinDbg and looking at !dbgprint again. Its output seems to be
   still stopping at the same place as before (but the actual buffer memory
   contents shows otherwise). Continue running ROS installation, and break
   into the debugger when ROS is about to restart. You should now observe
   that the dbgprint buffer rolled over:
     dd nt!KdPrintRolloverCount shows 1.
   Carefully analysing the output of !dbgprint, however, you will notice
   that it looks a bit garbage-y: the first part of the output is actually
   truncated after 16384 characters, then you get a second part of the
   buffer showing what ReactOS was printing while shutting down. Then
   you get again what was shown at the top of the !dbgprint output.
   (Of course, comparing with the actual contents of the circular buffer
   in memory shows that its contents are fine...)

The reason of these strange observations, is because there is an intrinsic
bug in the !dbgprint command implementation (in kdexts.dll). Essentially,
it displays the contents of the circular buffer in two single dprintf()
calls: one for the "older" (bottom) part of the buffer:
  [WritePointer, EndOfBuffer]
and one for the "newer" (upper) part of the buffer:
  [CircularBuffer, WritePointer[ .
The first aspect of the bug (causing observation 3), is that those two
parts are not necessarily NULL-terminated strings (especially after
rollover), so for example, displaying the upper part of the buffer, will
potentially also display part of the buffer's bottom part.
The second aspect of the bug (explaining observations 1 and 2), is due
to the implementation of the dprintf() function (callback in dbgenv.dll).
There, it uses a fixed-sized buffer of size 0x4000 == 16384 characters.
Since the output of the circular buffer is not done by little chunks,
but by the two large parts, if any of those are larger than 0x4000 they
get truncated on display.
(This last observation is confirmed in a completely different context by
https://community.osr.com/discussion/112439/dprintf-s-max-string-length .)
2022-11-24 01:18:18 +01:00
Hermès Bélusca-Maïto 36335d9cee
[NTOS:KD64] Correctly initialize the KdPrint buffer data in KdDebuggerDataBlock so as to fix the WinDbg !dbgprint command.
Now, !dbgprint just shows an empty log (since we don't fill it), instead
of showing the following error:

  kd> !dbgprint
  Can't find DbgPrint buffer
2022-11-24 01:18:17 +01:00
Hermès Bélusca-Maïto de81021bab
[PSDK][NTOS:KD64] Rename GCC_ULONG64 to ULPTR64 to self-document the fact it stores a pointer as a 64-bit quantity.
But the underlying GCC stupidity is still there (15 years later).

However, enable it only in 32-bit GCC builds, not in 64-bits nor with MSVC.
See commit b9cd3f2d9 (r25845) for some details.

GCC is indeed still incapable of casting 32-bit pointers up to 64-bits,
when static-initializing arrays (**outside** a function) without emitting
the error:

  "error: initializer element is not constant"

(which might somehow indicate it actually tries to generate executable
code for casting the pointers, instead of doing it at compile-time).

Going down the rabbit hole, other stupidities show up:

Our PVOID64 type and the related POINTER_64 (in 32-bit archs), or the
PVOID32 and POINTER_32 (in 64-bit archs), are all silently broken in
GCC builds, because the pointer size attributes __ptr64 and __ptr32,
which are originally MSVC-specific, are defined to nothing in _mingw.h.
(And similarly for the __uptr and __sptr sign-extension attributes.)

Clang and other sane ompilers has since then implemented those (enabled
with -fms-extensions), but not GCC. The closest thing that could exist
for GCC is to do:

  #define __ptr64 __attribute__((mode(DI)))

in order to get a 64-bit-sized pointer type with

  typedef void* __ptr64 PVOID64;

but even this does not work, with the error:

  "error: invalid pointer mode 'DI'"
2022-11-24 01:18:16 +01:00