Commit graph

1189 commits

Author SHA1 Message Date
Oliver Smith-Denny
2e7aa4810b MdeModulePkg: PeiCore: Add Memory Bin Support to Post-Mem PEI
This commit adds opt-in support for post-mem PEI memory bins.
See the README for full details.

MemoryBin.c is duplicated to PeiCore per request.

Signed-off-by: Oliver Smith-Denny <osde@microsoft.com>
2026-06-24 15:53:58 +00:00
Oliver Smith-Denny
eab3300622 MdeModulePkg: Dxe Core: Split Memory Bin Logic Into Separate File
This commits splits out logic currently contained in
Gcd.c and Page.c to a new file called
MemoryBin.c. This is set up in preparation to
add support to PEI for memory bins (an S4 resume stability
feature).

MemoryBin.c takes all global state in as parameters so that
DXE core can use globals and PEI core can use HOBs.

There is no logic change here, just consolidating the
functionality to share with PEI.

This was requested not to be a library.

Signed-off-by: Oliver Smith-Denny <osde@microsoft.com>
2026-06-24 15:53:58 +00:00
Oliver Smith-Denny
a196ef6db5 MdeModulePkg: Dxe Core: Add Resource Desc Hob Generation
This commit adds a parameter to the memory bin allocation function
to tell it whether it should create the Resource Descriptor HOB
owned by gMemoryTypeInformationGuid. This will be used by PEI to
tell DXE where the memory bins are.

Signed-off-by: Oliver Smith-Denny <osde@microsoft.com>
2026-06-24 15:53:58 +00:00
Oliver Smith-Denny
b33c1b9f7d MdeModulePkg: Dxe Core: Add Stats Init Helper
This adds a helper function to initialize the
memory bin statistics as the same logic is
repeated in several places.

Signed-off-by: Oliver Smith-Denny <osde@microsoft.com>
2026-06-24 15:53:58 +00:00
Oliver Smith-Denny
81bec6f0fb MdeModulePkg: Dxe Core: Prep CoreSetMemoryTypeInformationRange for PEI
Migrate CoreSetMemoryTypeInformationRange() to not use globals so
it can be used in PEI as well.

This temporarily moves the EFI_MEMORY_STATISTICS structure to
DxeMain.h so that it can be used in Gcd.c as well as Page.c.
This will migrate to a different private header once that is included.

Signed-off-by: Oliver Smith-Denny <osde@microsoft.com>
2026-06-24 15:53:58 +00:00
Oliver Smith-Denny
6b838a0d44 MdeModulePkg: Dxe Core: Add UpdateMemoryStatistics Helper Fn
In preparation for sharing logic with PEI, create a helper
function to update the memory bin statistics.

Signed-off-by: Oliver Smith-Denny <osde@microsoft.com>
2026-06-24 15:53:58 +00:00
Oliver Smith-Denny
47e73e61c6 MdeModulePkg: Dxe Core: Add AllocateMemoryBins Helper Fn
In preparation for sharing logic with PEI for memory bins,
add AllocateMemoryTypeInformationBins().

Signed-off-by: Oliver Smith-Denny <osde@microsoft.com>
2026-06-24 15:53:58 +00:00
Oliver Smith-Denny
1c8c92b7cc MdeModulePkg: DxeCore: Add GetMemoryTypeInformationResourceHob Helper
In preparation for sharing memory bin logic with PEI, create a
helper function that finds and validates a resource descriptor
HOB owned by gEfiMemoryTypeInformationGuid.

Signed-off-by: Oliver Smith-Denny <osde@microsoft.com>
2026-06-24 15:53:58 +00:00
Oliver Smith-Denny
d77628d4c1 MdeModulePkg: DxeCore: Create PopulateMemoryTypeInformation Helper
In preparation for supporting shared memory bin logic in DXE
and PEI, create a PopulateMemoryTypeInformation() helper function.
This function searches for a Memory Type Information Hob and
populates an EFI_MEMORY_TYPE_INFORMATION struct with it.

Signed-off-by: Oliver Smith-Denny <osde@microsoft.com>
2026-06-24 15:53:58 +00:00
Oliver Smith-Denny
b2c33619f7 MdeModulePkg: Dxe Core: Update Bin Size Helper Fn
In preparation for sharing memory bin logic between
PEI and DXE, update CaclulateTotalMemoryBinSizeNeeded()
to take gMemoryTypeInformation by reference.

Signed-off-by: Oliver Smith-Denny <osde@microsoft.com>
2026-06-24 15:53:58 +00:00
Sureshkumar Ponnusamy
e03fb69e9a MdeModulePkg/Core/Dxe/Gcd: make persistent override special-purpose
Fix the GCD memory type selection logic in DXE GCD initialization so persistent memory correctly takes precedence over special-purpose memory when both attributes are present.

The existing code/comment said persistent should win, but the condition order allowed special-purpose to overwrite persistent. This change swaps the checks so behavior matches the intended precedence and comment.

Signed-off-by: Sureshkumar Ponnusamy <sponnusamy@microsoft.com>
2026-06-23 14:24:18 +00:00
Oliver Smith-Denny
d417f3ec34 MdeModulePkg: Dxe: Skip FV Extraction When FV3 HOB Found
Currently, the DXE dispatcher will skip extracting an FV file
when an FV2 HOB is found for it, as that indicates pre-DXE
extracted it.

However, the dispatcher does not check for FV3 HOBs, which also
can describe extracted FVs. That can result in extracting the
same FV in DXE that is already extracted, which can be a large
performance hit.

This updates the DXE dispatcher to check for the existence of
either an FV2 or FV3 HOB for this FV and skip extracting if either
is found.

Signed-off-by: Oliver Smith-Denny <osde@microsoft.com>
2026-06-22 17:59:25 +00:00
Oliver Smith-Denny
d93ad5f525 MdeModulePkg: Dxe Core: Allocate Memory Bins Contiguously
Currently, there is no guarantee that the memory bins will be
allocated contiguously. However, there are assumptions in the
code that bins are allocated contiguously, such as the GCD
init code requiring a free memory region be large enough for
a contiguous bin range on DXE Core init.

Ensuring contiguous bins also makes a cleaner model for the
bins and keeps the memory map in a more standard configuration
between different configurations, as platforms today can
pass a resource descriptor HOB to DXE core to describe the bin
range and this only supports a contiguous range.

This also sets up reusing the memory bin logic for PEI memory
bin support which will use the aforementioned resource descriptor
HOB to pass the bin range to DXE.

This commit updates CoreAddMemoryDescriptor() to
allocate a contiguous range.

Signed-off-by: Oliver Smith-Denny <osde@microsoft.com>
2026-06-18 01:28:36 +00:00
monty.zhao
a581eb85f5 MdeModulePkg: Use EFI_NOT_FOUND when SourceBuffer and DevicePath are NULL
Update CoreLoadImageCommon to return EFI_NOT_FOUND instead of
EFI_INVALID_PARAMETER when both SourceBuffer and DevicePath are NULL.
UEFI 2.11 specification requires this change for LoadImage().

Signed-off-by: jie.fu <jie.fu@cixtech.com>
2026-06-11 04:02:08 +00:00
Mingjie Shen
45d477b22c MdeModulePkg: Replace manual alignment checks with helper macros
Replace manual alignment checks with IS_ALIGNED() and
ADDRESS_IS_ALIGNED().

Convert the following bitmask and modulo forms:

- ((E & ((PowOf2Expr) - ONE)) == ZERO)
- ((E & ((PowOf2Expr) - ONE)) != ZERO)
- ((E % (PowOf2Expr)) == ZERO)
- ((E % (PowOf2Expr)) != ZERO)

to the corresponding helper macro forms:

+ IS_ALIGNED (E, PowOf2Expr)
+ !IS_ALIGNED (E, PowOf2Expr)

PowOf2Expr is limited to known power-of-two expressions, including
SIZE_* and BASE_* macros, EFI_PAGE_SIZE, CPU_STACK_ALIGNMENT,
RUNTIME_PAGE_ALLOCATION_GRANULARITY, sizeof() of UEFI integer types
(e.g. BOOLEAN, CHAR16, UINT32, UINTN) and pointer types, and 1 << E1
expressions.

Address checks that cast the checked value to UINTN are written with
ADDRESS_IS_ALIGNED().

The change was generated with the Coccinelle semantic patch below.

```smpl
@power_of_2_expr@
expression PowOf2Expr;
expression E1;
typedef BOOLEAN, CHAR8, CHAR16, INT8, UINT8, INT16, UINT16, INT32, UINT32, INT64, UINT64, INTN, UINTN;
type ScalarType = { BOOLEAN, CHAR8, CHAR16, INT8, UINT8, INT16, UINT16, INT32, UINT32, INT64, UINT64, INTN, UINTN };
type AnyType;
type PointerType = AnyType *;
idexpression ScalarType ScalarValue;
idexpression PointerType PointerValue;
constant SizeBase =~ "^(SIZE|BASE)_(1|2|4|8|16|32|64|128|256|512)[KMGTPE]B$";
constant NamedPowerOf2 =~ "^(EFI_PAGE_SIZE|CPU_STACK_ALIGNMENT|RUNTIME_PAGE_ALLOCATION_GRANULARITY)$";
constant ONE = {1, 1U, 1u};
@@
(
(
  SizeBase
|
  NamedPowerOf2
|
  ONE << E1
|
  sizeof (ScalarType)
|
  sizeof (PointerType)
|
  sizeof (ScalarValue)
|
  sizeof (PointerValue)
)
&
PowOf2Expr
)

@aligned depends on power_of_2_expr disable is_zero,isnt_zero@
expression E;
expression power_of_2_expr.PowOf2Expr;
constant ONE = {1, 1U, 1u};
constant ZERO = {0, 0U, 0u};
@@
(
  ((E & (E - ONE)) == ZERO)
|
- ((E & ((PowOf2Expr) - ONE)) == ZERO)
+ IS_ALIGNED (E, PowOf2Expr)
|
  ((E & (E - ONE)) != ZERO)
|
- ((E & ((PowOf2Expr) - ONE)) != ZERO)
+ !IS_ALIGNED (E, PowOf2Expr)
|
- ((E % (PowOf2Expr)) == ZERO)
+ IS_ALIGNED (E, PowOf2Expr)
|
- ((E % (PowOf2Expr)) != ZERO)
+ !IS_ALIGNED (E, PowOf2Expr)
)

@address_is_aligned@
typedef UINTN;
expression *Address;
expression Alignment;
@@
- IS_ALIGNED ((UINTN) Address, Alignment)
+ ADDRESS_IS_ALIGNED (Address, Alignment)

@normalize_aligned disable paren expression@
expression E, SZ;
@@
(
- (IS_ALIGNED (E, SZ))
+ IS_ALIGNED (E, SZ)
|
- (!IS_ALIGNED (E, SZ))
+ !IS_ALIGNED (E, SZ)
)

@normalize_macro_args disable paren expression@
expression E, SZ;
@@
(
- IS_ALIGNED ((E), SZ)
+ IS_ALIGNED (E, SZ)
|
- IS_ALIGNED (E, (SZ))
+ IS_ALIGNED (E, SZ)
)
```

Signed-off-by: Mingjie Shen <shen497@purdue.edu>
2026-06-09 07:20:10 +00:00
Oliver Smith-Denny
ab3097d457 MdeModulePkg: Dxe Core: Use CalculateTotalMemoryBinSizeNeeded()
CoreSetMemoryTypeInformationRange() currently calculates the bin
size needed independently from the CalculateTotalMemoryBinSizeNeeded()
function. This commit updates to use that function and remove the
duplication.

Signed-off-by: Oliver Smith-Denny <osde@microsoft.com>
2026-06-08 16:20:28 +00:00
Oliver Smith-Denny
2be91af0cc MdeModulePkg: GCD: Use Alignment Requirement in Bin Size Calc
Currently CalculateTotalMemoryBinSizeNeeded() does not take
runtime alignment granularity considerations into account. This
means that the GCD initialization code can choose resource desc
HOBs to use for the bin region that are actually too small and
fail to initialize the bins.

This fixes CalculateTotalMemoryBinSizeNeeded() to take the
alignment requirements into consideration, both for size and for
alignment of the bin address range.

Signed-off-by: Oliver Smith-Denny <osde@microsoft.com>
2026-06-08 16:20:28 +00:00
Benjamin Doron
8add400a8b MdeModulePkg: Cleanup debug print readability
All debug prints should end in a newline character.

Signed-off-by: Benjamin Doron <benjamin.doron00@gmail.com>
2026-05-06 10:43:05 +00:00
Qihang Gao
351dfdb383 MdeModulePkg: Remove duplicate procotols guid in INF files
In PciSioSerialDxe driver, gEfiDevicePathProtocolGuid appears twice in
[Procotols] section. In PiSmmCore driver, gEfiSmmSxDispatch2ProtocolGuid
appears twice in [Procotols] section. In PiSmmIpl driver,
gEfiEventReadyToBootGuid appears twice in [Procotols] section. In
DxeCapsuleLib driver, gEfiCapsuleVendorGuid appears twice in [Guids]
section. The duplicate ones should be removed.

Signed-off-by: Qihang Gao <gaoqihang@loongson.cn>
2026-04-29 11:18:10 +02:00
Oliver Smith-Denny
0f2dc75587 MdeModulePkg: Don't Allow Guard Pages to Cross Bin Boundaries
Currently, the DXE page allocator does not ensure that guard
page allocations stay within the bin that it is attempting to
allocate within. As a result, S4 resume is jeopardized by
bins expanding due to guard pages, either into other bins or
out of bins. This is caught by a new assert in CoreGetMemoryMap()
to ensure the bins are correct.

This fixes this by changing the internal heap guard API to return
the adjusted size and start address of a proposed allocation. The
page allocator then can ensure that the adjusted allocation still
fits within the bin it is attempting to allocate within; if not,
it will search for another descriptor.

Signed-off-by: Oliver Smith-Denny <osde@microsoft.com>
2026-04-23 02:42:12 +00:00
Khalid Ali
260b91a352 MdeModulePkg/Core: Validate DXE event signature before usage
fixes: #11112

Currently, function RegisterProtocolNotify() doesn't check the validity
of event and it accepts any event pointer as long as pointer isn't NULL.
However event could be closed and freed which could lead to use after
free.

Always check event signature before usage and return
EFI_INVALID_PARAMTER for events with invalid signature.

Signed-off-by: Khalid Ali <khaliidcaliy@gmail.com>
2026-03-23 18:43:11 +00:00
Ray Ni
fc13220238 MdeModulePkg/PeiCore: Accept MemoryDiscoveredPpi from SecCore
PeiCore assumes that it runs initially from the temporary memory
and switches to physical memory after PS::InstallPeiMemory() reports
the physical memory range for PEI.
This change enables PeiCore to run initially from the physical
memory when MemoryDiscoveredPpi is passed from SEC.

Signed-off-by: Ray Ni <ray.ni@intel.com>
2026-03-19 02:02:47 +00:00
Sherry Fan
03e7c8c44f MdeModulePkg: Update performance measurements to use new perf macros
Updates BmBoot and dispatcher to use new perf macros.

Signed-off-by: Sherry Fan <sherryfan@microsoft.com>
2026-03-17 02:38:07 +00:00
Khalid Ali
8f28978843 MdeModulePkg/Core: Increment handle key outside if block
Fixes: #11113

Currently, the global handle key and key inside handle structure is
incremented only when a new handle is allocated for protocol interface
to be installed.

However, when caller already supplies a handle gHandleDatabaseKey never
get incremented.

Move handle key incremental outside if block, just below the else
statement which allows gHandleDatabaseKey to always incremented whether
handle is supplied or not.

Signed-off-by: Khalid Ali <khaliidcaliy@gmail.com>
2026-03-09 09:19:06 +00:00
Oliver Smith-Denny
4512733ac8 MdeModulePkg: DxeIpl IA32: Use 256 IDT Entries
When IA32 DxeIpl is setting up the IDT, it should populate
256 entries, the architectural size, so that exceptions are
handled in a defined way, going to the common exception handler.
This includes the stack cookie exception.

Signed-off-by: Oliver Smith-Denny <osde@microsoft.com>
2026-03-07 03:58:40 +00:00
Kun Qin
5b9430b72b MdeModulePkg: DxeMain: Check memory type overlap inside CoreGetMemoryMap
This change adds validation to CoreGetMemoryMap to ensure that special
memory bins are fully respected. Specifically, any memory map entry that
falls within a special bin must be entirely contained within that bin,
and its memory type must match the bin's designated type.

This check helps preventing unintended changes that could cause the
system memory map to cross bin boundaries unexpectedly.

Signed-off-by: Kun Qin <kun.qin@microsoft.com>
2026-02-28 04:20:00 +00:00
Khalid Ali
bd8667a7fd MdeModulePkg/Core: Move SMI depth tracker below SMI presence check
Fixes: #11764

Currently, mSmiManageCallingDepth is incremented always whether SMI
handler is present or not. However get decremented only when SMI handler
is found. This causes mSmiManageCallingDepth to grow infinitely as long
as SMI handler isn't present.

Increment mSmiManageCallingDepth only when SMI handler presence is
confirmed.

Signed-off-by: Khalid Ali <khaliidcaliy@gmail.com>
2026-02-27 06:09:41 +00:00
Michael Kubacki
7a934d0bef MdeModulePkg: Replace include guards with #pragma once
Replace traditional `#ifndef`/`#define`/`#endif` include guards with
`#pragma` once.

`#pragma once` is a widely supported preprocessor directive that
prevents header files from being included multiple times. It is
supported by all toolchains used to build edk2: GCC, Clang/LLVM, and
MSVC.

Compared to macro-based include guards, `#pragma once`:

- Eliminates the risk of macro name collisions or copy/paste errors
  where two headers inadvertently use the same guard macro.
- Eliminate inconsistency in the way include guard macros are named
  (e.g., some files use `__FILE_H__`, others use `FILE_H_`, etc.).
- Reduces boilerplate (three lines replaced by one).
- Avoids polluting the macro namespace with guard symbols.
- Can improve build times as the preprocessor can skip re-opening the
  file entirely, rather than re-reading it to find the matching
  `#endif` ("multiple-include optimization").
  - Note that some compilers may already optimize traditional include
    guards, by recognzining the idiomatic pattern.

This change is made acknowledging that overall portability of the
code will technically be reduced, as `#pragma once` is not part of the
C/C++ standards.

However, this is considered acceptable given:

1. edk2 already defines a subset of supported compilers in
   BaseTools/Conf/tools_def.template, all of which have supported
   `#pragma once` for over two decades.
2. There have been concerns raised to the project about inconsistent
   include guard naming and potential macro collisions.

Approximate compiler support dates:

- MSVC: Supported since Visual C++ 4.2 (1996)
- GCC: Supported since 3.4 (2004)
  (http://gnu.ist.utl.pt/software/gcc/gcc-3.4/changes.html)
- Clang (LLVM based): Since initial release in 2007

Signed-off-by: Michael Kubacki <michael.kubacki@microsoft.com>
2026-02-23 21:01:28 +00:00
Khalid Ali
300dada916 MdeModulePkg/Core: Make PPI services spec complaint
The documentation of InstallPpi() and NotifyPpi() in both the spec and
function comment indicate to return EFI_OUT_OF_RESOURCES if memory
allocation fails.

However, the implementation of those two services assert if memory
allocation fails. This is a mismatch between what the function expected to
return and what actually returns.

Fix this by returning EFI_OUT_OF_RESOURCES if memory allocation fails,
so the code matches the documentation and comply with the spec. It is
expected service consumers(callers of these functions) to handle
failures appriciately.

Signed-off-by: Khalid Ali <khaliidcaliy@gmail.com>
2026-01-30 02:18:50 +00:00
Michael D Kinney
d419725b23 MdeModulePkg/Core/Dxe/Mem: Fix GetMemoryMap() Alignment Issues
Fix alignment issues in memory map entries returned by
GetMemoryMap() when RUNTIME_PAGE_ALLOCATION_GRANULARITY is
larger than DEFAULT_PAGE_ALLOCATION_GRANULARITY.

There are no issues in the Page/Pool Allocation/Free services.

Logic issues issues are addressed in the memory map returned
by GetMemoryMap() due to missing cases for memory map entries
of type EfiConventionalMemory that overlap special memory bins.
Add logic to handle all possible memory map splits required to
convert internal memory map entries into an EFI Memory Map with
EFI Memory Map entries the follow alignment requirements when
the EFI Memory Map entries cover memory bins.

The four cases that must be handled are:
* Memory map entry contained within a bin.    [Already covered]
  Convert memory map entry type
* Memory map entry overlaps beginning of bin. [Added]
  Split memory map entry at beginning of bin.
* Memory map entry overlaps end of bin.       [Added]
  Split memory map entry at end of bin.
* Memory map entry overlaps entire bin.       [Added]
  Split memory map entry at both ends of bin.

Signed-off-by: Michael D Kinney <michael.d.kinney@intel.com>
2026-01-28 16:20:18 +00:00
Michael D Kinney
6834d43991 MdeModulePkg/Core/Dxe/Mem: Align initial memory map entries
Fix alignment issues in memory map entries returned by
GetMemoryMap() when RUNTIME_PAGE_ALLOCATION_GRANULARITY is
larger than DEFAULT_PAGE_ALLOCATION_GRANULARITY.

Alignment issues are addressed in the initial memory map
layout when Memory Type Information is provided with memory
bins that use RUNTIME_PAGE_ALLOCATION_GRANULARITY.

There are no issues in the Page/Pool Allocation/Free services.

* CoreSetMemoryTypeInformationRange() make sure there is room
  for all bins when accounting for alignment requirements.
  Allocate space for bins with base and length following
  alignment requirements.

* CoreSetMemoryTypeInformationRange() round up NumberOfPages in
  Memory Type Information based on alignment requirements.
  This is required so GetMemoryMap() will generate memory
  map entries that always follow alignment requirements.

* CoreAddMemoryDescriptor() round up NumberOfPages in
  Memory Type Information based on alignment requirements.
  This is required so GetMemoryMap() will generate memory
  map entries that always follow alignment requirements.

Signed-off-by: Michael D Kinney <michael.d.kinney@intel.com>
2026-01-28 16:20:18 +00:00
Damien-Chen
a2aaab4553 MdeModulePkg/Core/PiSmmCore/Page.c: Correct gMemoryMap typo
Correct function comment, gMemoryMep should be gMemoryMap.

Signed-off-by: Damien Chen <inkfan130924783@gmail.com>
2026-01-28 14:03:18 +00:00
Piotr Wejman
66346d5ede MdeModulePkg: Fix FreePages not existent memory
Commit 2d69507a4d added an attribute check to
prevent freeing memory that is read-only, read-protected, or for which
attribute retrieval fails. In such cases the code returned EFI_SUCCESS and
leaked the memory.

This introduced a regression in the System Architecture Compliance Suite
(ACS) BS.FreePages – Not Existent Memory test.
Link: https://github.com/tianocore/edk2-test/blob/edk2-test-stable202509/uefi-sct/Doc/TestCaseSpec/03_Services_Boot_Services.md#freepages
Test number: 5.1.2.2.1

GetMemoryAttributes() returns EFI_UNSUPPORTED for memory regions outside
system memory. The previous change treated all errors as a reason to leak
memory, while only the EFI_NO_MAPPING error code should trigger that
behavior. As a result, freeing non-existent memory incorrectly returned
EFI_SUCCESS instead of EFI_NOT_FOUND.

To fix this, memory is now leaked only when:
- GetMemoryAttributes() returns EFI_NO_MAPPING (inconsistent attributes),
  or
- GetMemoryAttributes() succeeds and the pages are marked RO or RP.

All other errors fall through to CoreInternalFreePages(), restoring the
previous and correct behavior.

Signed-off-by: Piotr Wejman <piotr.wejman@arm.com>
2025-12-30 01:36:38 +00:00
Ard Biesheuvel
bd4bb10d80 MdeModulePkg: Remove ambiguous negation of narrower type
Replace UINTN casts with EFI_PHYSICAL_ADDRESS in places where the result
is negated, as otherwise, the top bits may remain 0 unexpectedly.

VS2022 started warning about this, and thus breaking the IA32 CI build.

Signed-off-by: Ard Biesheuvel <ardb@kernel.org>
2025-12-03 11:50:28 +01:00
Aaron Pop
ede299f241 MdeModulePkg: Fix recently introduced uninitialized variable usage.
Address the build regressions, introduced in #11724, #11688, #11686 #11685.
These build regressions are for uninitialized variables before use.

Signed-off-by: Aaron Pop <aaronpop@microsoft.com>
2025-12-02 11:22:46 +01:00
Aaron Pop
5214f931c9 MdeModulePkg: Fix missing NULL tests.
https://github.com/github/codeql/blob/codeql-cli-2.7.3/cpp/ql/src/Critical/MissingNullTest.qhelp

For items which allocate memory, or get a pointer from another
structure, it is important to validate that the pointers
are not null before they are dereferenced.

Signed-off-by: Aaron Pop <aaronpop@microsoft.com>
2025-11-22 18:58:47 +00:00
Aaron Pop
57151d88f2 MdeModulePkg: Fix comparison with wider widths.
https://codeql.github.com/codeql-query-help/cpp/cpp-comparison-with-wider-type

If the narrow type (smaller range) is compared against a wide type
(larger range), the narrow value may overflow before reaching the wide
value. This can cause unexpected behavior, such as:

Infinite loops (loop condition never becomes false).
Incorrect logic (comparison results are misleading).

Signed-off-by: Aaron Pop <aaronpop@microsoft.com>
2025-11-22 18:58:47 +00:00
Kun Qin
feeb137d43 MdeModulePkg: DxeCore: Adding check for underflow before subtraction
During DXE core memory service initialization, the system would check
available resource descriptor hobs against the memory top from PHIT hob.
However, it is possible that a given resource descriptor hob will not be
larger than the cover the memory top, causing the Length calculation to
underflow.

This change adds a check for potential underflow before performing the
subtraction.

Signed-off-by: Kun Qin <kun.qin@microsoft.com>
2025-11-22 13:06:14 +00:00
Kun Qin
5be1bccd9c MdeModulePkg: DxeCore: Check overflow before using resource hob memory top
Current GCD logic uses plain addition calulation when iterating through
the resource descriptor hobs. However, if the resource descriptor is
incorrectly prepared, this could cause incorrect memory initialization
and other failures down the boot process.

This change adds an overflow check before using the value.

Signed-off-by: Kun Qin <kun.qin@microsoft.com>
2025-11-22 13:06:14 +00:00
Kun Qin
49d4753385 MdeModulePkg: CoreDxe: Handle multilple MemoryAllocationModules
The current implementation from Dxe/Image/Image.c does not handle the
configuration where there might be multiple MemoryAllocationModules.

Given that the `ModuleName` is included in the hob data and used for
targetting the consumer, DXE core should specify the GUID when looking up
for its own MemoryAllocationModule.

This change adds a check to ensure the located hob is targetting DXE
core.

Signed-off-by: Kun Qin <kuqin12@gmail.com>
2025-11-06 03:17:41 +00:00
Sathya Ravichandran
147e9a053e MdeModulePkg: Remove DXE_SAL_DRIVER
The DXE_SAL_DRIVER module type was introduced to support
Itanium (IPF) platforms. Since support for Itanium processors
has been dropped, the instances of DXE_SAL_DRIVER
have been removed.

Ref: [3cb0a311cb]

Cc: Sachin Ganesh <sachinganesh@ami.com>
Signed-off-by: Sathya Ravichandran <sathyar@ami.com>
2025-10-30 10:00:32 +00:00
Michael D Kinney
d145aef952 MdeModulePkg/Core/Dxe: Fix TPL inversion from DEBUG() message
PR #11443 introduced a regression by adding a DEBUG() message
when the lock for events is acquired and that lock is at
TPL_HIGH_LEVEL. If DEBUG() messages are routed through Report
Status Code, and the Report Status Code Protocol has not been
located yet, then a call to gBS->LocateProtocol() is made and
that call raises TPL to TPL_NOTIFY which causes a TPL inversion.

The event lock is used to atomically update gEventSignalQueue.
There is no need for the DEBUG() message to within the event
lock scope.

The fix is to scope the event lock to only the InsertHeadList()
call to update gEventSignalQueue.

Signed-off-by: Michael D Kinney <michael.d.kinney@intel.com>
2025-10-30 03:26:29 +00:00
Vitaly Cheptsov
64a1aca08f MdeModulePkg: Fix UEFI runtime driver loading after EndOfDxe
Memory Attributes Table needs to be updated to contain executable
permissions for UEFI runtime drivers loaded after EndOfDxe.
Fixes a regression introduced by bb248a9.

Signed-off-by: Vitaly Cheptsov <vit9696@protonmail.com>
2025-10-23 15:59:39 +02:00
Oliver Smith-Denny
cec2c6bbcc MdeModulePkg: Always Initialize Separate Exception Stacks
Following the APs now always initializing separate exception
stacks, this commit always initializes a separate exception
stack for the BSP as well. Previously, this was only enabled
when PcdCpuStackGuard was set.

However, even when a stack guard page is not present,
stack overflows can still occur and corrupt the stack; if an
exception is taken here, it is still valuable to have a separate
exception stack for sanity.

Signed-off-by: Oliver Smith-Denny <osde@microsoft.com>
2025-10-23 00:57:59 +00:00
Oliver Smith-Denny
f80a406aa9 MdeModulePkg: CoreGetMemoryMap: Account for Unaccepted Entries
Commit 43e306806e added
EFIGcdMemoryTypeUnaccepted (as it was later renamed) to be
returned in the EFI_MEMORY_MAP. However, it did not add it
to the number of entries calculation, so if any
EfiGcdMemoryTypeUnaccepted entries exist in the GCD they will
overflow the EFI_MEMORY_MAP buffer provided by the bootloader.

This resolves that by accounting for unaccepted entries in
the number of entries calculation.

Signed-off-by: Oliver Smith-Denny <osde@microsoft.com>
2025-10-17 07:31:03 +00:00
Oliver Smith-Denny
b5bab75e58 MdeModulePkg: DXE Core: Correct Usage of EFI_MEMORY_ATTRIBUTE_MASK
edk2 commit 3bd5c994c8 added usage
of EFI_MEMORY_ATTRIBUTE_MASK to edk2. However, it applied it
incorrectly to some places that should instead use
EFI_MEMORY_ACCESS_MASK. EFI_MEMORY_ACCESS_MASK contains the actual
HW page table access attributes (read protect, read only, no-execute),
whereas EFI_MEMORY_ATTRIBUTE_MASK contains the access attributes in
addition to some virtual attributes (special purpose and cpu crypto).

The GCD has a behavior where if SetMemorySpaceAttributes() is called
with only virtual attributes set, it will not call into CpuDxe to
change the attributes; 0 is a valid page table attribute set (it means
RWX). However, after the above change, this behavior was altered so
that if EFI_MEMORY_SP or EFI_MEMORY_CPU_CRYPTO is applied, in attempt
to just update these virtual attributes, the GCD will call into CpuDxe
and apply RWX instead, which is not the intention of the caller.

One other place this was done incorrectly was in CoreGetMemoryMap,
but that was fixed in f1567720b1.

SetUefiImageMemoryAttributes() is also updated here because that
logic was copied from the check the GCD has about whether to call
CpuDxe or not. Now that the GCD has been corrected, this also
needs to be corrected.

Signed-off-by: Oliver Smith-Denny <osde@microsoft.com>
2025-10-16 16:50:12 +00:00
Oliver Smith-Denny
ef79d58427 MdeModulePkg: Remove ARM32 Support
edk2 is dropping support for the ARM32 architecture. This
commit removes ARM32 support from MdeModulePkg. This also
drops irrelevant VALID_ARCHITECTURE comments from infs that
are not arch specific.

Signed-off-by: Oliver Smith-Denny <osde@microsoft.com>
2025-09-25 22:04:10 +00:00
Michael Kubacki
8a07311710 MdeModulePkg: Add PcdDelayedDispatchMaxEntries
The current fixed value of 8 for `DELAYED_DISPATCH_MAX_ENTRIES` is
not large enough to accommodate platform usage. This change replaces
the macro with a PCD that can be configured by platforms.

In the case the default PCD value is too small, an error message
explaining that the PCD should be updated will be printed followed
by an assert.

Signed-off-by: Michael Kubacki <michael.kubacki@microsoft.com>
2025-09-23 09:02:04 +08:00
Phil Noh
1780373897 MdeModulePkg/DxeMain: Add debug code for Event Group notify functions
There are a lot of notify callback events for Event Groups. Usually they
are not reported unless there is a debug code in the callback itself.
The debug message helps to check which/when the callback is registered and
executed in POST. Also helps to notice the callback sequence. It depends
on DEBUG_EVENT flag enabled by PcdFixedDebugPrintErrorLevel PCD token.

Signed-off-by: Phil Noh <Phil.Noh@amd.com>
2025-09-16 09:09:24 +08:00
Ray Ni
829e42d3a3 MdeModulePkg/PeiCore: Print GUID of FV and FvFile in debug log
When a BIOS implementation splits the PEIMs in multiple firmware volumes and
the FVs are reported to PEI Core by different PEIMs at different time,
it is hard to conclude the exact FV dispatch order.

The change updates the existing PEI dispatch logic to print the GUID of the
firmware volume and the FFS file which contains a nested FV.
It helps developers to match the FV being dispatched to the FV defined in
FDF file.

Signed-off-by: Ray Ni <ray.ni@intel.com>
Cc: Liming Gao <gaoliming@byosoft.com.cn>
2025-08-25 09:06:35 +00:00