diff --git a/.github/scripts/GitHub.py b/.github/scripts/GitHub.py index 628cd8412a76..885975a7d784 100644 --- a/.github/scripts/GitHub.py +++ b/.github/scripts/GitHub.py @@ -243,7 +243,7 @@ def add_reviewers_to_pr( # If a comment has already been made for these non-collaborators, # do not make another comment. if ( - comment.user.login == "github-actions[bot]" + comment.user.login == "tianocore-assign-reviewers[bot]" and "WARNING: Cannot add some reviewers" in comment.body and all(u in comment.body for u in non_collaborators) ): diff --git a/.gitignore b/.gitignore index 1dd30c141066..274a66ce8088 100644 --- a/.gitignore +++ b/.gitignore @@ -5,3 +5,4 @@ Build/ __pycache__/ tags/ .vscode/ +.venv/ diff --git a/.gitmodules b/.gitmodules index 6f4b19310fad..6d29190a14a7 100644 --- a/.gitmodules +++ b/.gitmodules @@ -16,7 +16,7 @@ [submodule "BaseTools/Source/C/BrotliCompress/brotli"] path = BaseTools/Source/C/BrotliCompress/brotli url = https://github.com/google/brotli - ignore = untracked + ignore = untracked [submodule "RedfishPkg/Library/JsonLib/jansson"] path = RedfishPkg/Library/JsonLib/jansson url = https://github.com/akheron/jansson @@ -25,16 +25,16 @@ url = https://github.com/google/googletest.git [submodule "UnitTestFrameworkPkg/Library/SubhookLib/subhook"] path = UnitTestFrameworkPkg/Library/SubhookLib/subhook - url = https://github.com/Zeex/subhook.git -[submodule "MdePkg/Library/BaseFdtLib/libfdt"] - path = MdePkg/Library/BaseFdtLib/libfdt - url = https://github.com/devicetree-org/pylibfdt.git + url = https://github.com/tianocore/edk2-subhook.git +[submodule "MdePkg/Library/BaseFdtLib/libfdt"] + path = MdePkg/Library/BaseFdtLib/libfdt + url = https://github.com/devicetree-org/pylibfdt.git [submodule "MdePkg/Library/MipiSysTLib/mipisyst"] path = MdePkg/Library/MipiSysTLib/mipisyst url = https://github.com/MIPI-Alliance/public-mipi-sys-t.git [submodule "CryptoPkg/Library/MbedTlsLib/mbedtls"] path = CryptoPkg/Library/MbedTlsLib/mbedtls url = https://github.com/ARMmbed/mbedtls -[submodule "SecurityPkg/DeviceSecurity/SpdmLib/libspdm"] - path = SecurityPkg/DeviceSecurity/SpdmLib/libspdm - url = https://github.com/DMTF/libspdm.git +[submodule "SecurityPkg/DeviceSecurity/SpdmLib/libspdm"] + path = SecurityPkg/DeviceSecurity/SpdmLib/libspdm + url = https://github.com/DMTF/libspdm.git diff --git a/.pytool/Plugin/UncrustifyCheck/Readme.md b/.pytool/Plugin/UncrustifyCheck/Readme.md index efe7a573e4fa..e64bf9b7a5a0 100644 --- a/.pytool/Plugin/UncrustifyCheck/Readme.md +++ b/.pytool/Plugin/UncrustifyCheck/Readme.md @@ -104,6 +104,23 @@ plugin execution. By default, files in paths matched in a .gitignore file or a recognized git submodule are excluded. If this option is `True`, the plugin will not attempt to recognize these files and exclude them. +### `UNCRUSTIFY_IN_PLACE=TRUE` + +This command supports any uncrustify changes to be made in-place to the files in the workspace. This is useful for +formatting any failing code before submitting a PR. Since this is an option for a local developer to use that would +modify their files, it must be explicitly specified as a CLI argument or set as an environment variable. + +_NOTE:_ This is _not_ an option in the config `yaml`. It is an option passed directly into the tool based on local + developer need. + +#### Example Usage + +In this example, Uncrustify would format files in `UefiCpuPkg` without running any other plugins or building any code. + +```bash +stuart_ci_build -c .pytool/CISettings.py -p UefiCpuPkg -t NO-TARGET UNCRUSTIFY_IN_PLACE=TRUE --disable-all UncrustifyCheck=run +``` + ## High-Level Plugin Operation This plugin generates two main sets of temporary files: diff --git a/.pytool/Plugin/UncrustifyCheck/UncrustifyCheck.py b/.pytool/Plugin/UncrustifyCheck/UncrustifyCheck.py index 2bdc3e292525..b6c660f9516a 100644 --- a/.pytool/Plugin/UncrustifyCheck/UncrustifyCheck.py +++ b/.pytool/Plugin/UncrustifyCheck/UncrustifyCheck.py @@ -153,6 +153,7 @@ def RunBuildPlugin(self, package_rel_path: str, edk2_path: Edk2Path, package_con """ try: # Initialize plugin and check pre-requisites. + self._env = environment_config self._initialize_environment_info( package_rel_path, edk2_path, package_config, tc) self._initialize_configuration() @@ -270,9 +271,17 @@ def _execute_uncrustify(self) -> None: Executes Uncrustify with the initialized configuration. """ output = StringIO() + params = ['-c', self._app_config_file] + params += ['-F', self._app_input_file_path] + params += ['--if-changed'] + if self._env.GetValue("UNCRUSTIFY_IN_PLACE", "FALSE") == "TRUE": + params += ['--replace', '--no-backup'] + else: + params += ['--suffix', UncrustifyCheck.FORMATTED_FILE_EXTENSION] self._app_exit_code = RunCmd( self._app_path, - f"-c {self._app_config_file} -F {self._app_input_file_path} --if-changed --suffix {UncrustifyCheck.FORMATTED_FILE_EXTENSION}", outstream=output) + " ".join(params), + outstream=output) self._app_output = output.getvalue().strip().splitlines() def _get_files_ignored_in_config(self): @@ -373,9 +382,9 @@ def _get_template_file_contents(self) -> None: file_template_path = pathlib.Path(os.path.join(self._plugin_path, file_template_name)) self._file_template_contents = file_template_path.read_text() except KeyError: - logging.warning("A file header template is not specified in the config file.") + logging.info("A file header template is not specified in the config file.") except FileNotFoundError: - logging.warning("The specified file header template file was not found.") + logging.info("The specified file header template file was not found.") try: func_template_name = parser["dummy_section"]["cmt_insert_func_header"] @@ -385,9 +394,9 @@ def _get_template_file_contents(self) -> None: func_template_path = pathlib.Path(os.path.join(self._plugin_path, func_template_name)) self._func_template_contents = func_template_path.read_text() except KeyError: - logging.warning("A function header template is not specified in the config file.") + logging.info("A function header template is not specified in the config file.") except FileNotFoundError: - logging.warning("The specified function header template file was not found.") + logging.info("The specified function header template file was not found.") def _initialize_app_info(self) -> None: """ @@ -563,13 +572,12 @@ def _process_uncrustify_results(self) -> None: self._formatted_file_error_count = len(formatted_files) if self._formatted_file_error_count > 0: - logging.warning(f'Uncrustify found {self._formatted_file_error_count} files with formatting errors') + logging.error(f'Uncrustify found {self._formatted_file_error_count} files with formatting errors\n') self._tc.LogStdError(f"Uncrustify found {self._formatted_file_error_count} files with formatting errors:\n") - logging.critical( + logging.warning( "Visit the following instructions to learn " - "how to find the detailed formatting errors in Azure " - "DevOps CI: " - "https://github.com/tianocore/tianocore.github.io/wiki/EDK-II-Code-Formatting#how-to-find-uncrustify-formatting-errors-in-continuous-integration-ci") + "more about uncrustify setup instructions and CI:" + "https://github.com/tianocore/tianocore.github.io/wiki/EDK-II-Code-Formatting\n") if self._output_file_diffs: logging.info("Calculating file diffs. This might take a while...") @@ -577,8 +585,8 @@ def _process_uncrustify_results(self) -> None: for formatted_file in formatted_files: pre_formatted_file = formatted_file[:-len(UncrustifyCheck.FORMATTED_FILE_EXTENSION)] + logging.error(f"Formatting errors in {os.path.relpath(pre_formatted_file, self._abs_package_path)}") self._tc.LogStdError(f"Formatting errors in {os.path.relpath(pre_formatted_file, self._abs_package_path)}\n") - logging.info(f"Formatting errors in {os.path.relpath(pre_formatted_file, self._abs_package_path)}") if (self._output_file_diffs or self._file_template_contents is not None or @@ -589,10 +597,12 @@ def _process_uncrustify_results(self) -> None: if (self._file_template_contents is not None and self._file_template_contents in formatted_file_text): + logging.info(f"File header is missing in {os.path.relpath(pre_formatted_file, self._abs_package_path)}") self._tc.LogStdError(f"File header is missing in {os.path.relpath(pre_formatted_file, self._abs_package_path)}\n") if (self._func_template_contents is not None and self._func_template_contents in formatted_file_text): + logging.info(f"A function header is missing in {os.path.relpath(pre_formatted_file, self._abs_package_path)}") self._tc.LogStdError(f"A function header is missing in {os.path.relpath(pre_formatted_file, self._abs_package_path)}\n") if self._output_file_diffs: @@ -600,8 +610,10 @@ def _process_uncrustify_results(self) -> None: pre_formatted_file_text = pf.read() for line in difflib.unified_diff(pre_formatted_file_text.split('\n'), formatted_file_text.split('\n'), fromfile=pre_formatted_file, tofile=formatted_file, n=3): + logging.error(line) self._tc.LogStdError(line) + logging.error('\n') self._tc.LogStdError('\n') def _remove_tree(self, dir_path: str, ignore_errors: bool = False) -> None: diff --git a/ArmPkg/ArmPkg.ci.yaml b/ArmPkg/ArmPkg.ci.yaml index 5c2e68b53460..292a25c9eb4d 100644 --- a/ArmPkg/ArmPkg.ci.yaml +++ b/ArmPkg/ArmPkg.ci.yaml @@ -24,7 +24,6 @@ "IgnoreFiles": [ "Library/ArmSoftFloatLib/berkeley-softfloat-3", "Library/ArmSoftFloatLib/ArmSoftFloatLib.c", - "Library/CompilerIntrinsicsLib", "Universal/Smbios/SmbiosMiscDxe" ] }, diff --git a/ArmPkg/ArmPkg.dsc b/ArmPkg/ArmPkg.dsc index 5bc830cf150e..25d750e8ab9f 100644 --- a/ArmPkg/ArmPkg.dsc +++ b/ArmPkg/ArmPkg.dsc @@ -78,8 +78,6 @@ PerformanceLib|MdePkg/Library/BasePerformanceLibNull/BasePerformanceLibNull.inf SerialPortLib|MdePkg/Library/BaseSerialPortLibNull/BaseSerialPortLibNull.inf - FdtLib|EmbeddedPkg/Library/FdtLib/FdtLib.inf - ShellLib|ShellPkg/Library/UefiShellLib/UefiShellLib.inf FileHandleLib|MdePkg/Library/UefiFileHandleLib/UefiFileHandleLib.inf SortLib|MdeModulePkg/Library/UefiSortLib/UefiSortLib.inf diff --git a/ArmPkg/Drivers/ArmGic/ArmGicLib.c b/ArmPkg/Drivers/ArmGic/ArmGicLib.c index 7f4bb248fc72..f49a376b14a9 100644 --- a/ArmPkg/Drivers/ArmGic/ArmGicLib.c +++ b/ArmPkg/Drivers/ArmGic/ArmGicLib.c @@ -225,10 +225,10 @@ ArmGicEndOfInterrupt ( VOID EFIAPI ArmGicSetInterruptPriority ( - IN UINTN GicDistributorBase, - IN UINTN GicRedistributorBase, - IN UINTN Source, - IN UINTN Priority + IN UINTN GicDistributorBase, + IN UINTN GicRedistributorBase, + IN UINTN Source, + IN UINT32 Priority ) { UINT32 RegOffset; diff --git a/ArmPkg/Include/Library/ArmGicLib.h b/ArmPkg/Include/Library/ArmGicLib.h index 93ce8aeb1994..32a06485f9d3 100644 --- a/ArmPkg/Include/Library/ArmGicLib.h +++ b/ArmPkg/Include/Library/ArmGicLib.h @@ -210,10 +210,10 @@ ArmGicSetPriorityMask ( VOID EFIAPI ArmGicSetInterruptPriority ( - IN UINTN GicDistributorBase, - IN UINTN GicRedistributorBase, - IN UINTN Source, - IN UINTN Priority + IN UINTN GicDistributorBase, + IN UINTN GicRedistributorBase, + IN UINTN Source, + IN UINT32 Priority ); VOID diff --git a/ArmPkg/Library/DefaultExceptionHandlerLib/AArch64/DefaultExceptionHandler.c b/ArmPkg/Library/DefaultExceptionHandlerLib/AArch64/DefaultExceptionHandler.c index a39896d576ce..1d3ea613110b 100644 --- a/ArmPkg/Library/DefaultExceptionHandlerLib/AArch64/DefaultExceptionHandler.c +++ b/ArmPkg/Library/DefaultExceptionHandlerLib/AArch64/DefaultExceptionHandler.c @@ -157,7 +157,6 @@ DescribeExceptionSyndrome ( DEBUG ((DEBUG_ERROR, "\n %a \n", Message)); } -#ifndef MDEPKG_NDEBUG STATIC CONST CHAR8 * BaseName ( @@ -177,8 +176,6 @@ BaseName ( return Str; } -#endif - /** This is the default action to take on an unexpected exception diff --git a/ArmPlatformPkg/Drivers/LcdGraphicsOutputDxe/LcdGraphicsOutputBlt.c b/ArmPlatformPkg/Drivers/LcdGraphicsOutputDxe/LcdGraphicsOutputBlt.c index 013506976f91..3679ee93dff9 100644 --- a/ArmPlatformPkg/Drivers/LcdGraphicsOutputDxe/LcdGraphicsOutputBlt.c +++ b/ArmPlatformPkg/Drivers/LcdGraphicsOutputDxe/LcdGraphicsOutputBlt.c @@ -140,10 +140,10 @@ VideoCopyHorizontalOverlap ( UINT16 *SourcePixel16bit; UINT16 *DestinationPixel16bit; - UINT32 SourcePixelY; - UINT32 DestinationPixelY; - UINTN SizeIn32Bits; - UINTN SizeIn16Bits; + UINTN SourcePixelY; + UINTN DestinationPixelY; + UINTN SizeIn32Bits; + UINTN SizeIn16Bits; Status = EFI_SUCCESS; @@ -271,8 +271,8 @@ BltVideoFill ( VOID *DestinationAddr; UINT16 *DestinationPixel16bit; UINT16 Pixel16bit; - UINT32 DestinationPixelX; - UINT32 DestinationLine; + UINTN DestinationPixelX; + UINTN DestinationLine; UINTN WidthInBytes; Status = EFI_SUCCESS; @@ -420,11 +420,11 @@ BltVideoToBltBuffer ( VOID *DestinationAddr; UINT16 *SourcePixel16bit; UINT16 Pixel16bit; - UINT32 SourcePixelX; - UINT32 SourceLine; - UINT32 DestinationPixelX; - UINT32 DestinationLine; - UINT32 BltBufferHorizontalResolution; + UINTN SourcePixelX; + UINTN SourceLine; + UINTN DestinationPixelX; + UINTN DestinationLine; + UINTN BltBufferHorizontalResolution; UINTN WidthInBytes; Status = EFI_SUCCESS; @@ -583,11 +583,11 @@ BltBufferToVideo ( VOID *SourceAddr; VOID *DestinationAddr; UINT16 *DestinationPixel16bit; - UINT32 SourcePixelX; - UINT32 SourceLine; - UINT32 DestinationPixelX; - UINT32 DestinationLine; - UINT32 BltBufferHorizontalResolution; + UINTN SourcePixelX; + UINTN SourceLine; + UINTN DestinationPixelX; + UINTN DestinationLine; + UINTN BltBufferHorizontalResolution; UINTN WidthInBytes; Status = EFI_SUCCESS; diff --git a/ArmPlatformPkg/Drivers/PL061GpioDxe/PL061Gpio.c b/ArmPlatformPkg/Drivers/PL061GpioDxe/PL061Gpio.c index fc062204c029..9d6e8832e2e8 100644 --- a/ArmPlatformPkg/Drivers/PL061GpioDxe/PL061Gpio.c +++ b/ArmPlatformPkg/Drivers/PL061GpioDxe/PL061Gpio.c @@ -34,7 +34,7 @@ PL061Locate ( OUT UINTN *RegisterBase ) { - UINT32 Index; + UINTN Index; for (Index = 0; Index < mPL061PlatformGpio->GpioControllerCount; Index++) { if ( (Gpio >= mPL061PlatformGpio->GpioController[Index].GpioIndex) @@ -74,18 +74,18 @@ UINTN EFIAPI PL061EffectiveAddress ( IN UINTN Address, - IN UINTN Mask + IN UINT8 Mask ) { - return ((Address + PL061_GPIO_DATA_REG_OFFSET) + (Mask << 2)); + return ((Address + PL061_GPIO_DATA_REG_OFFSET) + (UINTN)(Mask << 2)); } STATIC -UINTN +UINT8 EFIAPI PL061GetPins ( IN UINTN Address, - IN UINTN Mask + IN UINT8 Mask ) { return MmioRead8 (PL061EffectiveAddress (Address, Mask)); @@ -96,8 +96,8 @@ VOID EFIAPI PL061SetPins ( IN UINTN Address, - IN UINTN Mask, - IN UINTN Value + IN UINT8 Mask, + IN UINT8 Value ) { MmioWrite8 (PL061EffectiveAddress (Address, Mask), Value); diff --git a/ArmPlatformPkg/Drivers/PL061GpioDxe/PL061Gpio.h b/ArmPlatformPkg/Drivers/PL061GpioDxe/PL061Gpio.h index 42d87a16a3dd..8db1e1f8ec86 100644 --- a/ArmPlatformPkg/Drivers/PL061GpioDxe/PL061Gpio.h +++ b/ArmPlatformPkg/Drivers/PL061GpioDxe/PL061Gpio.h @@ -37,6 +37,6 @@ #define PL061_GPIO_PINS 8 // All bits low except one bit high, native bit length -#define GPIO_PIN_MASK(Pin) (1UL << ((UINTN)(Pin))) +#define GPIO_PIN_MASK(Pin) (UINT8)(1 << (Pin & (PL061_GPIO_PINS - 1))) #endif // __PL061_GPIO_H__ diff --git a/ArmPlatformPkg/Drivers/SP805WatchdogDxe/SP805Watchdog.c b/ArmPlatformPkg/Drivers/SP805WatchdogDxe/SP805Watchdog.c index b8e7fbe38d77..c9ffb7c61240 100644 --- a/ArmPlatformPkg/Drivers/SP805WatchdogDxe/SP805Watchdog.c +++ b/ArmPlatformPkg/Drivers/SP805WatchdogDxe/SP805Watchdog.c @@ -24,7 +24,7 @@ STATIC EFI_EVENT mEfiExitBootServicesEvent; STATIC EFI_HARDWARE_INTERRUPT_PROTOCOL *mInterrupt; STATIC EFI_WATCHDOG_TIMER_NOTIFY mWatchdogNotify; -STATIC UINT32 mTimerPeriod; +STATIC UINT64 mTimerPeriod; /** Make sure the SP805 registers are unlocked for writing. @@ -101,7 +101,7 @@ SP805Stop ( { // Disable interrupts if ((MmioRead32 (SP805_WDOG_CONTROL_REG) & SP805_WDOG_CTRL_INTEN) != 0) { - MmioAnd32 (SP805_WDOG_CONTROL_REG, ~SP805_WDOG_CTRL_INTEN); + MmioAnd32 (SP805_WDOG_CONTROL_REG, (UINT32) ~SP805_WDOG_CTRL_INTEN); } } diff --git a/ArmPlatformPkg/Library/PL111Lcd/PL111Lcd.h b/ArmPlatformPkg/Library/PL111Lcd/PL111Lcd.h index 0d4fe387c54c..6b1e41796cdd 100644 --- a/ArmPlatformPkg/Library/PL111Lcd/PL111Lcd.h +++ b/ArmPlatformPkg/Library/PL111Lcd/PL111Lcd.h @@ -108,7 +108,7 @@ #define PL111_CTRL_LCD_16BPP_565 (6 << 1) #define PL111_CTRL_LCD_12BPP_444 (7 << 1) #define PL111_CTRL_LCD_BPP(Bpp) ((Bpp) << 1) -#define PL111_CTRL_LCD_EN 1 +#define PL111_CTRL_LCD_EN 1U /**********************************************************************/ diff --git a/ArmVirtPkg/ArmVirt.dsc.inc b/ArmVirtPkg/ArmVirt.dsc.inc index 890a056cd018..6dd6ce69cc07 100644 --- a/ArmVirtPkg/ArmVirt.dsc.inc +++ b/ArmVirtPkg/ArmVirt.dsc.inc @@ -381,8 +381,10 @@ # # Enable NX memory protection for all non-code regions, including OEM and OS - # reserved ones, with the exception of LoaderData regions, of which OS loaders - # (i.e., GRUB) may assume that its contents are executable. + # reserved ones. + # By passing --pcd PcdDxeNxMemoryProtectionPolicy=0xC000000000007FD1 on the + # build command line you can allow code execution in EfiLoaderData. This is + # required when using some outdated GRUB versions. # gEfiMdeModulePkgTokenSpaceGuid.PcdDxeNxMemoryProtectionPolicy|0xC000000000007FD5 diff --git a/ArmVirtPkg/ArmVirtKvmTool.dsc b/ArmVirtPkg/ArmVirtKvmTool.dsc index c5cf2a75d9f5..2c85ca3db29f 100644 --- a/ArmVirtPkg/ArmVirtKvmTool.dsc +++ b/ArmVirtPkg/ArmVirtKvmTool.dsc @@ -368,17 +368,17 @@ UefiCpuPkg/CpuMmio2Dxe/CpuMmio2Dxe.inf { NULL|OvmfPkg/Fdt/FdtPciPcdProducerLib/FdtPciPcdProducerLib.inf - NULL|OvmfPkg/Library/BaseCachingPciExpressLib/BaseCachingPciExpressLib.inf + PciExpressLib|OvmfPkg/Library/BaseCachingPciExpressLib/BaseCachingPciExpressLib.inf } MdeModulePkg/Bus/Pci/PciHostBridgeDxe/PciHostBridgeDxe.inf { NULL|OvmfPkg/Fdt/FdtPciPcdProducerLib/FdtPciPcdProducerLib.inf - NULL|OvmfPkg/Library/BaseCachingPciExpressLib/BaseCachingPciExpressLib.inf + PciExpressLib|OvmfPkg/Library/BaseCachingPciExpressLib/BaseCachingPciExpressLib.inf } MdeModulePkg/Bus/Pci/PciBusDxe/PciBusDxe.inf { NULL|OvmfPkg/Fdt/FdtPciPcdProducerLib/FdtPciPcdProducerLib.inf - NULL|OvmfPkg/Library/BaseCachingPciExpressLib/BaseCachingPciExpressLib.inf + PciExpressLib|OvmfPkg/Library/BaseCachingPciExpressLib/BaseCachingPciExpressLib.inf } OvmfPkg/VirtioPciDeviceDxe/VirtioPciDeviceDxe.inf OvmfPkg/Virtio10Dxe/Virtio10.inf diff --git a/ArmVirtPkg/ArmVirtQemu.dsc b/ArmVirtPkg/ArmVirtQemu.dsc index 4010a4176b5c..1ba63d2e1679 100644 --- a/ArmVirtPkg/ArmVirtQemu.dsc +++ b/ArmVirtPkg/ArmVirtQemu.dsc @@ -151,10 +151,6 @@ gArmVirtTokenSpaceGuid.PcdTpm2SupportEnabled|$(TPM2_ENABLE) [PcdsFixedAtBuild.common] -!if $(ARCH) == AARCH64 - gArmTokenSpaceGuid.PcdVFPEnabled|1 -!endif - gUefiOvmfPkgTokenSpaceGuid.PcdOvmfFdBaseAddress|0x00000000 gUefiOvmfPkgTokenSpaceGuid.PcdOvmfFirmwareFdSize|$(FD_SIZE) @@ -245,6 +241,8 @@ # point only, for entry point versions >= 3.0. gEfiMdeModulePkgTokenSpaceGuid.PcdSmbiosEntryPointProvideMethod|0x2 + gArmTokenSpaceGuid.PcdVFPEnabled|1 + [PcdsDynamicDefault.common] gEfiMdePkgTokenSpaceGuid.PcdPlatformBootTimeOut|3 diff --git a/ArmVirtPkg/Library/QemuVirtMemInfoLib/QemuVirtMemInfoPeiLib.inf b/ArmVirtPkg/Library/QemuVirtMemInfoLib/QemuVirtMemInfoPeiLib.inf index da957cfaffa6..091e37c90bed 100644 --- a/ArmVirtPkg/Library/QemuVirtMemInfoLib/QemuVirtMemInfoPeiLib.inf +++ b/ArmVirtPkg/Library/QemuVirtMemInfoLib/QemuVirtMemInfoPeiLib.inf @@ -30,6 +30,7 @@ [LibraryClasses] ArmLib + BaseLib BaseMemoryLib DebugLib FdtLib diff --git a/ArmVirtPkg/Library/QemuVirtMemInfoLib/QemuVirtMemInfoPeiLibConstructor.c b/ArmVirtPkg/Library/QemuVirtMemInfoLib/QemuVirtMemInfoPeiLibConstructor.c index 1bcc2e26aa60..f39df852d8d7 100644 --- a/ArmVirtPkg/Library/QemuVirtMemInfoLib/QemuVirtMemInfoPeiLibConstructor.c +++ b/ArmVirtPkg/Library/QemuVirtMemInfoLib/QemuVirtMemInfoPeiLibConstructor.c @@ -8,6 +8,7 @@ #include #include +#include #include #include #include diff --git a/BaseTools/Conf/tools_def.template b/BaseTools/Conf/tools_def.template index 0f110fbb4a16..14f3b643c43d 100755 --- a/BaseTools/Conf/tools_def.template +++ b/BaseTools/Conf/tools_def.template @@ -2017,7 +2017,7 @@ DEFINE CLANGDWARF_X64_DLINK2_FLAGS = -Wl,--defsym=PECOFF_HEADER_SIZE=0x22 DEFINE CLANGDWARF_IA32_TARGET = -target i686-pc-linux-gnu DEFINE CLANGDWARF_X64_TARGET = -target x86_64-pc-linux-gnu -DEFINE CLANGDWARF_WARNING_OVERRIDES = -Wno-parentheses-equality -Wno-empty-body -Wno-unused-const-variable -Wno-varargs -Wno-unknown-warning-option -Wno-unused-but-set-variable -Wno-unused-const-variable -Wno-unaligned-access -Wno-unneeded-internal-declaration +DEFINE CLANGDWARF_WARNING_OVERRIDES = -Wno-parentheses-equality -Wno-empty-body -Wno-unused-const-variable -Wno-varargs -Wno-unknown-warning-option -Wno-unused-but-set-variable -Wno-unused-const-variable -Wno-unaligned-access DEFINE CLANGDWARF_ALL_CC_FLAGS = DEF(GCC48_ALL_CC_FLAGS) DEF(CLANGDWARF_WARNING_OVERRIDES) -fno-stack-protector -mms-bitfields -Wno-address -Wno-shift-negative-value -Wno-unknown-pragmas -Wno-incompatible-library-redeclaration -fno-asynchronous-unwind-tables -mno-sse -mno-mmx -msoft-float -mno-implicit-float -ftrap-function=undefined_behavior_has_been_optimized_away_by_clang -funsigned-char -fno-ms-extensions -Wno-null-dereference ########################### diff --git a/BaseTools/Plugin/CodeQL/CodeQlAnalyzePlugin.py b/BaseTools/Plugin/CodeQL/CodeQlAnalyzePlugin.py index 9734478f8b78..88a533cafec8 100644 --- a/BaseTools/Plugin/CodeQL/CodeQlAnalyzePlugin.py +++ b/BaseTools/Plugin/CodeQL/CodeQlAnalyzePlugin.py @@ -3,6 +3,7 @@ # A build plugin that analyzes a CodeQL database. # # Copyright (c) Microsoft Corporation. All rights reserved. +# Copyright (C) 2024 Advanced Micro Devices, Inc. All rights reserved. # SPDX-License-Identifier: BSD-2-Clause-Patent ## @@ -78,6 +79,11 @@ def do_post_build(self, builder: UefiBuilder) -> int: # Packages are allowed to specify package-specific query specifiers # in the package CI YAML file that override the global query specifier. audit_only = False + global_audit_only = builder.env.GetValue("STUART_CODEQL_AUDIT_ONLY") + if global_audit_only: + if global_audit_only.strip().lower() == "true": + audit_only = True + query_specifiers = None package_config_file = Path(os.path.join( self.package_path, self.package + ".ci.yaml")) @@ -94,11 +100,6 @@ def do_post_build(self, builder: UefiBuilder) -> int: f"{str(package_config_file)}") query_specifiers = plugin_data["QuerySpecifiers"] - global_audit_only = builder.env.GetValue("STUART_CODEQL_AUDIT_ONLY") - if global_audit_only: - if global_audit_only.strip().lower() == "true": - audit_only = True - if audit_only: logging.info(f"CodeQL Analyze plugin is in audit only mode for " f"{self.package} ({self.target}).") diff --git a/BaseTools/Plugin/LinuxGcc5ToolChain/LinuxGcc5ToolChain_plug_in.yaml b/BaseTools/Plugin/LinuxGcc5ToolChain/LinuxGcc5ToolChain_plug_in.yaml deleted file mode 100644 index 39c378a926a9..000000000000 --- a/BaseTools/Plugin/LinuxGcc5ToolChain/LinuxGcc5ToolChain_plug_in.yaml +++ /dev/null @@ -1,12 +0,0 @@ -## @file -# Build Plugin used to set the path -# for the GCC5 ARM/AARCH64 downloaded compilers -# -# Copyright (c) Microsoft Corporation. -# SPDX-License-Identifier: BSD-2-Clause-Patent -## -{ - "scope": "global-nix", - "name": "Linux GCC5 Tool Chain Support", - "module": "LinuxGcc5ToolChain" -} diff --git a/BaseTools/Plugin/LinuxGcc5ToolChain/LinuxGcc5ToolChain.py b/BaseTools/Plugin/LinuxGccToolChain/LinuxGccToolChain.py similarity index 50% rename from BaseTools/Plugin/LinuxGcc5ToolChain/LinuxGcc5ToolChain.py rename to BaseTools/Plugin/LinuxGccToolChain/LinuxGccToolChain.py index 57866a5159fd..e7ef3df3b6ab 100644 --- a/BaseTools/Plugin/LinuxGcc5ToolChain/LinuxGcc5ToolChain.py +++ b/BaseTools/Plugin/LinuxGccToolChain/LinuxGccToolChain.py @@ -1,7 +1,8 @@ -# @file LinuxGcc5ToolChain.py -# Plugin to configures paths for GCC5 ARM/AARCH64 Toolchain +# @file LinuxGccToolChain.py +# Plugin to configures paths for GCC/GCC5 ARM/AARCH64/RISCV/LOONGARCH64 Toolchain ## -# This plugin works in conjuncture with the tools_def +# This plugin sets environment variables used in tools_def.template to specify the GCC compiler +# for the requested build architecture. # # Copyright (c) Microsoft Corporation # Copyright (c) 2020, Hewlett Packard Enterprise Development LP. All rights reserved.
@@ -14,110 +15,120 @@ from edk2toolext.environment import shell_environment -class LinuxGcc5ToolChain(IUefiBuildPlugin): +class LinuxGccToolChain(IUefiBuildPlugin): def do_post_build(self, thebuilder): return 0 def do_pre_build(self, thebuilder): - self.Logger = logging.getLogger("LinuxGcc5ToolChain") + self.Logger = logging.getLogger("LinuxGccToolChain") # - # GCC5 - The ARM and AARCH64 compilers need their paths set if available - if thebuilder.env.GetValue("TOOL_CHAIN_TAG") == "GCC5": + # In order to keep this plugin backwards compatible with the older GCC5 toolchain tag, + # we support setting either the GCC5 or GCC set of env variables required + # + toolchain = "GCC" + + # + # GCC - The non-x86 compilers need their paths set if available. To make this more stable, check for + # any substring of GCC in the TOOL_CHAIN_TAG to get the right compiler + # + if "GCC" in thebuilder.env.GetValue("TOOL_CHAIN_TAG"): + if "GCC5" in thebuilder.env.GetValue("TOOL_CHAIN_TAG"): + toolchain = "GCC5" # Start with AARACH64 compiler - ret = self._check_aarch64() + ret = self._check_aarch64(toolchain) if ret != 0: self.Logger.critical("Failed in check aarch64") return ret # Check arm compiler - ret = self._check_arm() + ret = self._check_arm(toolchain) if ret != 0: self.Logger.critical("Failed in check arm") return ret # Check RISCV64 compiler - ret = self._check_riscv64() + ret = self._check_riscv64(toolchain) if ret != 0: self.Logger.critical("Failed in check riscv64") return ret # Check LoongArch64 compiler - ret = self._check_loongarch64() + ret = self._check_loongarch64(toolchain) if ret != 0: self.Logger.critical("Failed in check loongarch64") return ret return 0 - def _check_arm(self): + def _check_arm(self, toolchain): # check to see if full path already configured - if shell_environment.GetEnvironment().get_shell_var("GCC5_ARM_PREFIX") is not None: - self.Logger.info("GCC5_ARM_PREFIX is already set.") + if shell_environment.GetEnvironment().get_shell_var(toolchain + "_ARM_PREFIX") is not None: + self.Logger.info(toolchain + "_ARM_PREFIX is already set.") else: # now check for install dir. If set then set the Prefix - install_path = shell_environment.GetEnvironment().get_shell_var("GCC5_ARM_INSTALL") + install_path = shell_environment.GetEnvironment().get_shell_var(toolchain + "_ARM_INSTALL") if install_path is None: return 0 - # make GCC5_ARM_PREFIX to align with tools_def.txt + # make the PREFIX to align with tools_def.txt prefix = os.path.join(install_path, "bin", "arm-none-linux-gnueabihf-") - shell_environment.GetEnvironment().set_shell_var("GCC5_ARM_PREFIX", prefix) + shell_environment.GetEnvironment().set_shell_var(toolchain + "_ARM_PREFIX", prefix) # now confirm it exists - if not os.path.exists(shell_environment.GetEnvironment().get_shell_var("GCC5_ARM_PREFIX") + "gcc"): - self.Logger.error("Path for GCC5_ARM_PREFIX toolchain is invalid") + if not os.path.exists(shell_environment.GetEnvironment().get_shell_var(toolchain + "_ARM_PREFIX") + "gcc"): + self.Logger.error("Path for " + toolchain + "_ARM_PREFIX toolchain is invalid") return -2 return 0 - def _check_aarch64(self): + def _check_aarch64(self, toolchain): # check to see if full path already configured - if shell_environment.GetEnvironment().get_shell_var("GCC5_AARCH64_PREFIX") is not None: - self.Logger.info("GCC5_AARCH64_PREFIX is already set.") + if shell_environment.GetEnvironment().get_shell_var(toolchain + "_AARCH64_PREFIX") is not None: + self.Logger.info(toolchain + "_AARCH64_PREFIX is already set.") else: # now check for install dir. If set then set the Prefix install_path = shell_environment.GetEnvironment( - ).get_shell_var("GCC5_AARCH64_INSTALL") + ).get_shell_var(toolchain + "_AARCH64_INSTALL") if install_path is None: return 0 - # make GCC5_AARCH64_PREFIX to align with tools_def.txt + # make PREFIX to align with tools_def.txt prefix = os.path.join(install_path, "bin", "aarch64-none-linux-gnu-") - shell_environment.GetEnvironment().set_shell_var("GCC5_AARCH64_PREFIX", prefix) + shell_environment.GetEnvironment().set_shell_var(toolchain + "_AARCH64_PREFIX", prefix) # now confirm it exists - if not os.path.exists(shell_environment.GetEnvironment().get_shell_var("GCC5_AARCH64_PREFIX") + "gcc"): + if not os.path.exists(shell_environment.GetEnvironment().get_shell_var(toolchain + "_AARCH64_PREFIX") + "gcc"): self.Logger.error( - "Path for GCC5_AARCH64_PREFIX toolchain is invalid") + "Path for " + toolchain + "_AARCH64_PREFIX toolchain is invalid") return -2 return 0 - def _check_riscv64(self): + def _check_riscv64(self, toolchain): # now check for install dir. If set then set the Prefix install_path = shell_environment.GetEnvironment( - ).get_shell_var("GCC5_RISCV64_INSTALL") + ).get_shell_var(toolchain + "_RISCV64_INSTALL") if install_path is None: return 0 # check to see if full path already configured - if shell_environment.GetEnvironment().get_shell_var("GCC5_RISCV64_PREFIX") is not None: - self.Logger.info("GCC5_RISCV64_PREFIX is already set.") + if shell_environment.GetEnvironment().get_shell_var(toolchain + "_RISCV64_PREFIX") is not None: + self.Logger.info(toolchain + "_RISCV64_PREFIX is already set.") else: - # make GCC5_RISCV64_PREFIX to align with tools_def.txt + # make PREFIX to align with tools_def.txt prefix = os.path.join(install_path, "bin", "riscv64-unknown-elf-") - shell_environment.GetEnvironment().set_shell_var("GCC5_RISCV64_PREFIX", prefix) + shell_environment.GetEnvironment().set_shell_var(toolchain + "_RISCV64_PREFIX", prefix) # now confirm it exists - if not os.path.exists(shell_environment.GetEnvironment().get_shell_var("GCC5_RISCV64_PREFIX") + "gcc"): + if not os.path.exists(shell_environment.GetEnvironment().get_shell_var(toolchain + "_RISCV64_PREFIX") + "gcc"): self.Logger.error( - "Path for GCC5_RISCV64_PREFIX toolchain is invalid") + "Path for " + toolchain + "_RISCV64_PREFIX toolchain is invalid") return -2 # Check if LD_LIBRARY_PATH is set for the libraries of RISC-V GCC toolchain @@ -129,26 +140,26 @@ def _check_riscv64(self): return 0 - def _check_loongarch64(self): + def _check_loongarch64(self, toolchain): # check to see if full path already configured - if shell_environment.GetEnvironment().get_shell_var("GCC5_LOONGARCH64_PREFIX") is not None: - self.Logger.info("GCC5_LOONGARCH64_PREFIX is already set.") + if shell_environment.GetEnvironment().get_shell_var(toolchain + "_LOONGARCH64_PREFIX") is not None: + self.Logger.info(toolchain + "_LOONGARCH64_PREFIX is already set.") else: # now check for install dir. If set then set the Prefix install_path = shell_environment.GetEnvironment( - ).get_shell_var("GCC5_LOONGARCH64_INSTALL") + ).get_shell_var(toolchain + "_LOONGARCH64_INSTALL") if install_path is None: return 0 - # make GCC5_LOONGARCH64_PREFIX to align with tools_def.txt + # make PREFIX to align with tools_def.txt prefix = os.path.join(install_path, "bin", "loongarch64-unknown-linux-gnu-") - shell_environment.GetEnvironment().set_shell_var("GCC5_LOONGARCH64_PREFIX", prefix) + shell_environment.GetEnvironment().set_shell_var(toolchain + "_LOONGARCH64_PREFIX", prefix) # now confirm it exists - if not os.path.exists(shell_environment.GetEnvironment().get_shell_var("GCC5_LOONGARCH64_PREFIX") + "gcc"): + if not os.path.exists(shell_environment.GetEnvironment().get_shell_var(toolchain + "_LOONGARCH64_PREFIX") + "gcc"): self.Logger.error( - "Path for GCC5_LOONGARCH64_PREFIX toolchain is invalid") + "Path for " + toolchain + "_LOONGARCH64_PREFIX toolchain is invalid") return -2 return 0 diff --git a/BaseTools/Plugin/LinuxGccToolChain/LinuxGccToolChain_plug_in.yaml b/BaseTools/Plugin/LinuxGccToolChain/LinuxGccToolChain_plug_in.yaml new file mode 100644 index 000000000000..dd1e14c34d45 --- /dev/null +++ b/BaseTools/Plugin/LinuxGccToolChain/LinuxGccToolChain_plug_in.yaml @@ -0,0 +1,12 @@ +## @file +# This plugin sets environment variables used in tools_def.template to specify the GCC compiler +# for the requested build architecture. +# +# Copyright (c) Microsoft Corporation. +# SPDX-License-Identifier: BSD-2-Clause-Patent +## +{ + "scope": "global-nix", + "name": "Linux GCC Tool Chain Support", + "module": "LinuxGccToolChain" +} diff --git a/BaseTools/Scripts/SetupGit.py b/BaseTools/Scripts/SetupGit.py index 5f93124967bf..9014eb584c6a 100644 --- a/BaseTools/Scripts/SetupGit.py +++ b/BaseTools/Scripts/SetupGit.py @@ -150,7 +150,7 @@ def write_config_value(repo, section, option, data): action='store_true', required=False) PARSER.add_argument('-n', '--name', type=str, metavar='repo', - choices=['edk2', 'edk2-platforms', 'edk2-non-osi'], + choices=['edk2', 'edk2-platforms', 'edk2-non-osi', 'edk2-test'], help='set the repo name to configure for, if not ' 'detected automatically', required=False) diff --git a/BaseTools/Source/C/Common/Decompress.c b/BaseTools/Source/C/Common/Decompress.c index 0f2bdbffa72e..0cf0c4a0a8e5 100644 --- a/BaseTools/Source/C/Common/Decompress.c +++ b/BaseTools/Source/C/Common/Decompress.c @@ -15,7 +15,9 @@ SPDX-License-Identifier: BSD-2-Clause-Patent // // Decompression algorithm begins here // +#ifndef UINT8_MAX #define UINT8_MAX 0xff +#endif #define BITBUFSIZ 32 #define MAXMATCH 256 #define THRESHOLD 3 diff --git a/BaseTools/Source/C/GenFw/Elf64Convert.c b/BaseTools/Source/C/GenFw/Elf64Convert.c index 9d04fc612eb4..897045b2be16 100644 --- a/BaseTools/Source/C/GenFw/Elf64Convert.c +++ b/BaseTools/Source/C/GenFw/Elf64Convert.c @@ -1482,9 +1482,18 @@ WriteSections64 ( - (SecOffset - SecShdr->sh_addr)); VerboseMsg ("Relocation: 0x%08X", *(UINT32 *)Targ); break; + case R_X86_64_REX_GOTPCRELX: + // + // This is a relaxable GOTPCREL relocation, and the linker may have + // applied this relaxation without updating the relocation type. + // In the position independent code model, only transformations + // from MOV to LEA are possible for REX-prefixed instructions. + // + if (Targ[-2] == 0x8d) { // LEA + break; + } case R_X86_64_GOTPCREL: case R_X86_64_GOTPCRELX: - case R_X86_64_REX_GOTPCRELX: VerboseMsg ("R_X86_64_GOTPCREL family"); VerboseMsg ("Offset: 0x%08X, Addend: 0x%08X", (UINT32)(SecOffset + (Rel->r_offset - SecShdr->sh_addr)), diff --git a/BaseTools/Source/C/Include/Common/BaseTypes.h b/BaseTools/Source/C/Include/Common/BaseTypes.h index e669da894c32..5093a2f1f9f5 100644 --- a/BaseTools/Source/C/Include/Common/BaseTypes.h +++ b/BaseTools/Source/C/Include/Common/BaseTypes.h @@ -4,6 +4,8 @@ This file is stand alone self consistent set of definitions. Copyright (c) 2006 - 2018, Intel Corporation. All rights reserved.
+ Copyright (C) 2024 Advanced Micro Devices, Inc. All rights reserved. + SPDX-License-Identifier: BSD-2-Clause-Patent **/ @@ -202,7 +204,7 @@ typedef UINTN RETURN_STATUS; #define ENCODE_ERROR(a) ((RETURN_STATUS)(MAX_BIT | (a))) #define ENCODE_WARNING(a) ((RETURN_STATUS)(a)) -#define RETURN_ERROR(a) (((INTN)(RETURN_STATUS)(a)) < 0) +#define RETURN_ERROR(a) (((RETURN_STATUS)(a)) >= MAX_BIT) #define RETURN_SUCCESS 0 #define RETURN_LOAD_ERROR ENCODE_ERROR (1) diff --git a/BaseTools/Source/Python/Ecc/Check.py b/BaseTools/Source/Python/Ecc/Check.py index 4561961141d4..160e803764fe 100644 --- a/BaseTools/Source/Python/Ecc/Check.py +++ b/BaseTools/Source/Python/Ecc/Check.py @@ -1092,7 +1092,7 @@ def MetaDataFileCheckModuleFileNoUse(self): RecordSet = EccGlobalData.gDb.TblInf.Exec(SqlCommand) for Record in RecordSet: Path = Record[1] - Path = Path.upper().replace('\X64', '').replace('\IA32', '').replace('\EBC', '').replace('\IPF', '').replace('\ARM', '') + Path = Path.upper().replace(r'\X64', '').replace(r'\IA32', '').replace(r'\EBC', '').replace(r'\IPF', '').replace(r'\ARM', '') if Path in InfPathList: if not EccGlobalData.gException.IsException(ERROR_META_DATA_FILE_CHECK_MODULE_FILE_NO_USE, Record[2]): EccGlobalData.gDb.TblReport.Insert(ERROR_META_DATA_FILE_CHECK_MODULE_FILE_NO_USE, OtherMsg="The source file [%s] is existing in module directory but it is not described in INF file." % (Record[2]), BelongsToTable='File', BelongsToItem=Record[0]) diff --git a/BaseTools/Source/Python/Ecc/Configuration.py b/BaseTools/Source/Python/Ecc/Configuration.py index d4aab1d1310b..9a9ca49eee41 100644 --- a/BaseTools/Source/Python/Ecc/Configuration.py +++ b/BaseTools/Source/Python/Ecc/Configuration.py @@ -432,7 +432,7 @@ def ShowMe(self): # test that our dict and out class still match in contents. # if __name__ == '__main__': - myconfig = Configuration("BaseTools\Source\Python\Ecc\config.ini") + myconfig = Configuration(r"BaseTools\Source\Python\Ecc\config.ini") for each in myconfig.__dict__: if each == "Filename": continue diff --git a/BaseTools/Source/Python/Ecc/MetaFileWorkspace/MetaFileParser.py b/BaseTools/Source/Python/Ecc/MetaFileWorkspace/MetaFileParser.py index 2d98ac5eadb2..2ef2847b1ba9 100644 --- a/BaseTools/Source/Python/Ecc/MetaFileWorkspace/MetaFileParser.py +++ b/BaseTools/Source/Python/Ecc/MetaFileWorkspace/MetaFileParser.py @@ -1841,14 +1841,14 @@ def _PcdParser(self): if EccGlobalData.gConfig.UniCheckPCDInfo == '1' or EccGlobalData.gConfig.UniCheckAll == '1' or EccGlobalData.gConfig.CheckAll == '1': # check Description, Prompt information - PatternDesc = re.compile('##\s*([\x21-\x7E\s]*)', re.S) - PatternPrompt = re.compile('#\s+@Prompt\s+([\x21-\x7E\s]*)', re.S) + PatternDesc = re.compile(r'##\s*([\x21-\x7E\s]*)', re.S) + PatternPrompt = re.compile(r'#\s+@Prompt\s+([\x21-\x7E\s]*)', re.S) Description = None Prompt = None # check @ValidRange, @ValidList and @Expression format valid ErrorCodeValid = '0x0 <= %s <= 0xFFFFFFFF' - PatternValidRangeIn = '(NOT)?\s*(\d+\s*-\s*\d+|0[xX][a-fA-F0-9]+\s*-\s*0[xX][a-fA-F0-9]+|LT\s*\d+|LT\s*0[xX][a-fA-F0-9]+|GT\s*\d+|GT\s*0[xX][a-fA-F0-9]+|LE\s*\d+|LE\s*0[xX][a-fA-F0-9]+|GE\s*\d+|GE\s*0[xX][a-fA-F0-9]+|XOR\s*\d+|XOR\s*0[xX][a-fA-F0-9]+|EQ\s*\d+|EQ\s*0[xX][a-fA-F0-9]+)' - PatternValidRng = re.compile('^' + '(NOT)?\s*' + PatternValidRangeIn + '$') + PatternValidRangeIn = r'(NOT)?\s*(\d+\s*-\s*\d+|0[xX][a-fA-F0-9]+\s*-\s*0[xX][a-fA-F0-9]+|LT\s*\d+|LT\s*0[xX][a-fA-F0-9]+|GT\s*\d+|GT\s*0[xX][a-fA-F0-9]+|LE\s*\d+|LE\s*0[xX][a-fA-F0-9]+|GE\s*\d+|GE\s*0[xX][a-fA-F0-9]+|XOR\s*\d+|XOR\s*0[xX][a-fA-F0-9]+|EQ\s*\d+|EQ\s*0[xX][a-fA-F0-9]+)' + PatternValidRng = re.compile('^' + r'(NOT)?\s*' + PatternValidRangeIn + '$') for Comment in self._Comments: Comm = Comment[0].strip() if not Comm: @@ -2071,7 +2071,7 @@ def Start(self): def CheckKeyValid(self, Key, Contents=None): if not Contents: Contents = self.FileIn - KeyPattern = re.compile('#string\s+%s\s+.*?#language.*?".*?"' % Key, re.S) + KeyPattern = re.compile(r'#string\s+%s\s+.*?#language.*?".*?"' % Key, re.S) if KeyPattern.search(Contents): return True return False diff --git a/BaseTools/Source/Python/Ecc/c.py b/BaseTools/Source/Python/Ecc/c.py index 61ad084fcc5b..0ebdc1a99605 100644 --- a/BaseTools/Source/Python/Ecc/c.py +++ b/BaseTools/Source/Python/Ecc/c.py @@ -43,7 +43,7 @@ def GetArrayPattern(): return p def GetTypedefFuncPointerPattern(): - p = re.compile('[_\w\s]*\([\w\s]*\*+\s*[_\w]+\s*\)\s*\(.*\)', re.DOTALL) + p = re.compile(r'[_\w\s]*\([\w\s]*\*+\s*[_\w]+\s*\)\s*\(.*\)', re.DOTALL) return p def GetDB(): diff --git a/BaseTools/Source/Python/Eot/EotGlobalData.py b/BaseTools/Source/Python/Eot/EotGlobalData.py index 3218f86f441c..887a7a259545 100644 --- a/BaseTools/Source/Python/Eot/EotGlobalData.py +++ b/BaseTools/Source/Python/Eot/EotGlobalData.py @@ -11,7 +11,7 @@ gEFI_SOURCE = '' gEDK_SOURCE = '' gWORKSPACE = '' -gSHELL_INF = 'Application\Shell' +gSHELL_INF = r'Application\Shell' gMAKE_FILE = '' gDSC_FILE = '' gFV_FILE = [] diff --git a/BaseTools/Source/Python/Eot/c.py b/BaseTools/Source/Python/Eot/c.py index dd9530fed6d0..a85564d60030 100644 --- a/BaseTools/Source/Python/Eot/c.py +++ b/BaseTools/Source/Python/Eot/c.py @@ -54,7 +54,7 @@ def GetArrayPattern(): # @return p: the pattern of function pointer # def GetTypedefFuncPointerPattern(): - p = re.compile('[_\w\s]*\([\w\s]*\*+\s*[_\w]+\s*\)\s*\(.*\)', re.DOTALL) + p = re.compile(r'[_\w\s]*\([\w\s]*\*+\s*[_\w]+\s*\)\s*\(.*\)', re.DOTALL) return p ## GetDB() method diff --git a/BaseTools/Source/Python/UPT/Library/CommentParsing.py b/BaseTools/Source/Python/UPT/Library/CommentParsing.py index 7ba9830d34ac..7b1ce05493c1 100644 --- a/BaseTools/Source/Python/UPT/Library/CommentParsing.py +++ b/BaseTools/Source/Python/UPT/Library/CommentParsing.py @@ -238,7 +238,7 @@ def ParseDecPcdGenericComment (GenericComment, ContainerFile, TokenSpaceGuidCNam # # To replace Macro # - MACRO_PATTERN = '[\t\s]*\$\([A-Z][_A-Z0-9]*\)' + MACRO_PATTERN = r'[\t\s]*\$\([A-Z][_A-Z0-9]*\)' MatchedStrs = re.findall(MACRO_PATTERN, Comment) for MatchedStr in MatchedStrs: if MatchedStr: diff --git a/BaseTools/Source/Python/UPT/Library/ExpressionValidate.py b/BaseTools/Source/Python/UPT/Library/ExpressionValidate.py index 7718ca12e5cf..2c0750efe45d 100644 --- a/BaseTools/Source/Python/UPT/Library/ExpressionValidate.py +++ b/BaseTools/Source/Python/UPT/Library/ExpressionValidate.py @@ -66,13 +66,13 @@ def __init__(self, Error = ''): ## _ExprBase # class _ExprBase: - HEX_PATTERN = '[\t\s]*0[xX][a-fA-F0-9]+' - INT_PATTERN = '[\t\s]*[0-9]+' - MACRO_PATTERN = '[\t\s]*\$\(([A-Z][_A-Z0-9]*)\)' + HEX_PATTERN = r'[\t\s]*0[xX][a-fA-F0-9]+' + INT_PATTERN = r'[\t\s]*[0-9]+' + MACRO_PATTERN = r'[\t\s]*\$\(([A-Z][_A-Z0-9]*)\)' PCD_PATTERN = \ - '[\t\s]*[_a-zA-Z][a-zA-Z0-9_]*[\t\s]*\.[\t\s]*[_a-zA-Z][a-zA-Z0-9_]*' - QUOTED_PATTERN = '[\t\s]*L?"[^"]*"' - BOOL_PATTERN = '[\t\s]*(true|True|TRUE|false|False|FALSE)' + r'[\t\s]*[_a-zA-Z][a-zA-Z0-9_]*[\t\s]*\.[\t\s]*[_a-zA-Z][a-zA-Z0-9_]*' + QUOTED_PATTERN = r'[\t\s]*L?"[^"]*"' + BOOL_PATTERN = r'[\t\s]*(true|True|TRUE|false|False|FALSE)' def __init__(self, Token): self.Token = Token self.Index = 0 @@ -303,9 +303,9 @@ def IsValidLogicalExpression(self): ## _ValidRangeExpressionParser # class _ValidRangeExpressionParser(_ExprBase): - INT_RANGE_PATTERN = '[\t\s]*[0-9]+[\t\s]*-[\t\s]*[0-9]+' + INT_RANGE_PATTERN = r'[\t\s]*[0-9]+[\t\s]*-[\t\s]*[0-9]+' HEX_RANGE_PATTERN = \ - '[\t\s]*0[xX][a-fA-F0-9]+[\t\s]*-[\t\s]*0[xX][a-fA-F0-9]+' + r'[\t\s]*0[xX][a-fA-F0-9]+[\t\s]*-[\t\s]*0[xX][a-fA-F0-9]+' def __init__(self, Token): _ExprBase.__init__(self, Token) self.Parens = 0 @@ -407,7 +407,7 @@ def ValidRange(self): ## _ValidListExpressionParser # class _ValidListExpressionParser(_ExprBase): - VALID_LIST_PATTERN = '(0[xX][0-9a-fA-F]+|[0-9]+)([\t\s]*,[\t\s]*(0[xX][0-9a-fA-F]+|[0-9]+))*' + VALID_LIST_PATTERN = r'(0[xX][0-9a-fA-F]+|[0-9]+)([\t\s]*,[\t\s]*(0[xX][0-9a-fA-F]+|[0-9]+))*' def __init__(self, Token): _ExprBase.__init__(self, Token) self.NUM = 1 diff --git a/BaseTools/Source/Python/UPT/Library/Misc.py b/BaseTools/Source/Python/UPT/Library/Misc.py index 77ba3584e000..f3688de4b1b7 100644 --- a/BaseTools/Source/Python/UPT/Library/Misc.py +++ b/BaseTools/Source/Python/UPT/Library/Misc.py @@ -69,11 +69,11 @@ def GuidStringToGuidStructureString(Guid): def CheckGuidRegFormat(GuidValue): ## Regular expression used to find out register format of GUID # - RegFormatGuidPattern = re.compile("^\s*([0-9a-fA-F]){8}-" + RegFormatGuidPattern = re.compile(r"^\s*([0-9a-fA-F]){8}-" "([0-9a-fA-F]){4}-" "([0-9a-fA-F]){4}-" "([0-9a-fA-F]){4}-" - "([0-9a-fA-F]){12}\s*$") + r"([0-9a-fA-F]){12}\s*$") if RegFormatGuidPattern.match(GuidValue): return True @@ -837,8 +837,8 @@ def GetLibInstanceInfo(String, WorkSpace, LineNo): ST.ERR_FILE_OPEN_FAILURE, File=FullFileName) - ReFileGuidPattern = re.compile("^\s*FILE_GUID\s*=.*$") - ReVerStringPattern = re.compile("^\s*VERSION_STRING\s*=.*$") + ReFileGuidPattern = re.compile(r"^\s*FILE_GUID\s*=.*$") + ReVerStringPattern = re.compile(r"^\s*VERSION_STRING\s*=.*$") FileLinesList = ProcessLineExtender(FileLinesList) @@ -978,7 +978,7 @@ def ValidateUNIFilePath(Path): # # Check if the file name is valid according to the DEC and INF specification # - Pattern = '[a-zA-Z0-9_][a-zA-Z0-9_\-\.]*' + Pattern = r'[a-zA-Z0-9_][a-zA-Z0-9_\-\.]*' FileName = Path.replace(Suffix, '') InvalidCh = re.sub(Pattern, '', FileName) if InvalidCh: diff --git a/BaseTools/Source/Python/UPT/Library/StringUtils.py b/BaseTools/Source/Python/UPT/Library/StringUtils.py index fbc5177caf5a..a6f47d0dd79b 100644 --- a/BaseTools/Source/Python/UPT/Library/StringUtils.py +++ b/BaseTools/Source/Python/UPT/Library/StringUtils.py @@ -23,7 +23,7 @@ # # Regular expression for matching macro used in DSC/DEC/INF file inclusion # -gMACRO_PATTERN = re.compile("\$\(([_A-Z][_A-Z0-9]*)\)", re.UNICODE) +gMACRO_PATTERN = re.compile(r"\$\(([_A-Z][_A-Z0-9]*)\)", re.UNICODE) ## GetSplitValueList # diff --git a/BaseTools/Source/Python/UPT/Parser/DecParserMisc.py b/BaseTools/Source/Python/UPT/Parser/DecParserMisc.py index 27990467d1c5..92dbcaaabeb0 100644 --- a/BaseTools/Source/Python/UPT/Parser/DecParserMisc.py +++ b/BaseTools/Source/Python/UPT/Parser/DecParserMisc.py @@ -25,7 +25,7 @@ from Library.Misc import CheckGuidRegFormat TOOL_NAME = 'DecParser' -VERSION_PATTERN = '[0-9]+(\.[0-9]+)?' +VERSION_PATTERN = r'[0-9]+(\.[0-9]+)?' CVAR_PATTERN = '[_a-zA-Z][a-zA-Z0-9_]*' PCD_TOKEN_PATTERN = '(0[xX]0*[a-fA-F0-9]{1,8})|([0-9]+)' MACRO_PATTERN = '[A-Z][_A-Z0-9]*' diff --git a/BaseTools/Source/Python/UPT/Parser/InfAsBuiltProcess.py b/BaseTools/Source/Python/UPT/Parser/InfAsBuiltProcess.py index 992b609120f8..fb646191b186 100644 --- a/BaseTools/Source/Python/UPT/Parser/InfAsBuiltProcess.py +++ b/BaseTools/Source/Python/UPT/Parser/InfAsBuiltProcess.py @@ -53,12 +53,12 @@ def GetLibInstanceInfo(String, WorkSpace, LineNo, CurrentInfFileName): # # To deal with library instance specified by GUID and version # - RegFormatGuidPattern = re.compile("\s*([0-9a-fA-F]){8}-" + RegFormatGuidPattern = re.compile(r"\s*([0-9a-fA-F]){8}-" "([0-9a-fA-F]){4}-" "([0-9a-fA-F]){4}-" "([0-9a-fA-F]){4}-" - "([0-9a-fA-F]){12}\s*") - VersionPattern = re.compile('[\t\s]*\d+(\.\d+)?[\t\s]*') + r"([0-9a-fA-F]){12}\s*") + VersionPattern = re.compile(r'[\t\s]*\d+(\.\d+)?[\t\s]*') GuidMatchedObj = RegFormatGuidPattern.search(String) if String.upper().startswith('GUID') and GuidMatchedObj and 'Version' in String: @@ -75,8 +75,8 @@ def GetLibInstanceInfo(String, WorkSpace, LineNo, CurrentInfFileName): FileLinesList = GetFileLineContent(String, WorkSpace, LineNo, OriginalString) - ReFindFileGuidPattern = re.compile("^\s*FILE_GUID\s*=.*$") - ReFindVerStringPattern = re.compile("^\s*VERSION_STRING\s*=.*$") + ReFindFileGuidPattern = re.compile(r"^\s*FILE_GUID\s*=.*$") + ReFindVerStringPattern = re.compile(r"^\s*VERSION_STRING\s*=.*$") for Line in FileLinesList: if ReFindFileGuidPattern.match(Line): @@ -106,8 +106,8 @@ def GetPackageListInfo(FileNameString, WorkSpace, LineNo): FileLinesList = GetFileLineContent(FileNameString, WorkSpace, LineNo, '') - RePackageHeader = re.compile('^\s*\[Packages.*\].*$') - ReDefineHeader = re.compile('^\s*\[Defines].*$') + RePackageHeader = re.compile(r'^\s*\[Packages.*\].*$') + ReDefineHeader = re.compile(r'^\s*\[Defines].*$') PackageHederFlag = False DefineHeaderFlag = False @@ -255,8 +255,8 @@ def GetGuidVerFormLibInstance(Guid, Version, WorkSpace, CurrentInfFileName): FileLinesList = InfFileObj.readlines() FileLinesList = ProcessLineExtender(FileLinesList) - ReFindFileGuidPattern = re.compile("^\s*FILE_GUID\s*=.*$") - ReFindVerStringPattern = re.compile("^\s*VERSION_STRING\s*=.*$") + ReFindFileGuidPattern = re.compile(r"^\s*FILE_GUID\s*=.*$") + ReFindVerStringPattern = re.compile(r"^\s*VERSION_STRING\s*=.*$") for Line in FileLinesList: if ReFindFileGuidPattern.match(Line): diff --git a/BaseTools/Source/Python/UPT/Parser/InfDefineSectionParser.py b/BaseTools/Source/Python/UPT/Parser/InfDefineSectionParser.py index a63e40e61787..9edcc2cb3f4c 100644 --- a/BaseTools/Source/Python/UPT/Parser/InfDefineSectionParser.py +++ b/BaseTools/Source/Python/UPT/Parser/InfDefineSectionParser.py @@ -40,7 +40,7 @@ def GetValidateArchList(LineContent): TempArch = GetSplitValueList(TempArch, '(', 1)[0] - ArchList = re.split('\s+', TempArch) + ArchList = re.split(r'\s+', TempArch) NewArchList = [] for Arch in ArchList: if IsValidArch(Arch): diff --git a/BaseTools/Source/Python/UPT/Parser/InfParserMisc.py b/BaseTools/Source/Python/UPT/Parser/InfParserMisc.py index d01ae9aa0246..eb768b9a1241 100644 --- a/BaseTools/Source/Python/UPT/Parser/InfParserMisc.py +++ b/BaseTools/Source/Python/UPT/Parser/InfParserMisc.py @@ -109,7 +109,7 @@ def InfExpandMacro(Content, LineInfo, GlobalMacros=None, SectionMacros=None, Fla return Content else: for Macro in MacroUsed: - gQuotedMacro = re.compile(".*\".*\$\(%s\).*\".*"%(Macro)) + gQuotedMacro = re.compile(r".*\".*\$\(%s\).*\".*"%(Macro)) if not gQuotedMacro.match(Content): # # Still have MACROs can't be expanded. @@ -130,8 +130,8 @@ def IsBinaryInf(FileLineList): if not FileLineList: return False - ReIsSourcesSection = re.compile("^\s*\[Sources.*\]\s.*$", re.IGNORECASE) - ReIsBinarySection = re.compile("^\s*\[Binaries.*\]\s.*$", re.IGNORECASE) + ReIsSourcesSection = re.compile(r"^\s*\[Sources.*\]\s.*$", re.IGNORECASE) + ReIsBinarySection = re.compile(r"^\s*\[Binaries.*\]\s.*$", re.IGNORECASE) BinarySectionFoundFlag = False for Line in FileLineList: @@ -155,7 +155,7 @@ def IsBinaryInf(FileLineList): # @return Flag # def IsLibInstanceInfo(String): - ReIsLibInstance = re.compile("^\s*##\s*@LIB_INSTANCES\s*$") + ReIsLibInstance = re.compile(r"^\s*##\s*@LIB_INSTANCES\s*$") if ReIsLibInstance.match(String): return True else: @@ -171,7 +171,7 @@ def IsLibInstanceInfo(String): # @return Flag # def IsAsBuildOptionInfo(String): - ReIsAsBuildInstance = re.compile("^\s*##\s*@AsBuilt\s*$") + ReIsAsBuildInstance = re.compile(r"^\s*##\s*@AsBuilt\s*$") if ReIsAsBuildInstance.match(String): return True else: diff --git a/BaseTools/Source/Python/UPT/PomAdapter/DecPomAlignment.py b/BaseTools/Source/Python/UPT/PomAdapter/DecPomAlignment.py index da92fe5d3eb2..b1f8135bc780 100644 --- a/BaseTools/Source/Python/UPT/PomAdapter/DecPomAlignment.py +++ b/BaseTools/Source/Python/UPT/PomAdapter/DecPomAlignment.py @@ -747,12 +747,12 @@ def ReplaceForEval(self, ReplaceValue, IsRange=False, IsExpr=False): # # deal with "NOT EQ", "NOT LT", "NOT GT", "NOT LE", "NOT GE", "NOT NOT" # - NOTNOT_Pattern = '[\t\s]*NOT[\t\s]+NOT[\t\s]*' - NOTGE_Pattern = '[\t\s]*NOT[\t\s]+GE[\t\s]*' - NOTLE_Pattern = '[\t\s]*NOT[\t\s]+LE[\t\s]*' - NOTGT_Pattern = '[\t\s]*NOT[\t\s]+GT[\t\s]*' - NOTLT_Pattern = '[\t\s]*NOT[\t\s]+LT[\t\s]*' - NOTEQ_Pattern = '[\t\s]*NOT[\t\s]+EQ[\t\s]*' + NOTNOT_Pattern = r'[\t\s]*NOT[\t\s]+NOT[\t\s]*' + NOTGE_Pattern = r'[\t\s]*NOT[\t\s]+GE[\t\s]*' + NOTLE_Pattern = r'[\t\s]*NOT[\t\s]+LE[\t\s]*' + NOTGT_Pattern = r'[\t\s]*NOT[\t\s]+GT[\t\s]*' + NOTLT_Pattern = r'[\t\s]*NOT[\t\s]+LT[\t\s]*' + NOTEQ_Pattern = r'[\t\s]*NOT[\t\s]+EQ[\t\s]*' ReplaceValue = re.compile(NOTNOT_Pattern).sub('', ReplaceValue) ReplaceValue = re.compile(NOTLT_Pattern).sub('x >= ', ReplaceValue) ReplaceValue = re.compile(NOTGT_Pattern).sub('x <= ', ReplaceValue) @@ -785,7 +785,7 @@ def ReplaceForEval(self, ReplaceValue, IsRange=False, IsExpr=False): if ReplaceValue.find('!') >= 0 and ReplaceValue[ReplaceValue.index('!') + 1] != '=': ReplaceValue = ReplaceValue.replace('!', ' not ') if '.' in ReplaceValue: - Pattern = '[a-zA-Z0-9]{1,}\.[a-zA-Z0-9]{1,}' + Pattern = r'[a-zA-Z0-9]{1,}\.[a-zA-Z0-9]{1,}' MatchedList = re.findall(Pattern, ReplaceValue) for MatchedItem in MatchedList: if MatchedItem not in self.PcdDefaultValueDict: @@ -814,7 +814,7 @@ def CheckPcdValue(self): # # Delete the 'L' prefix of a quoted string, this operation is for eval() # - QUOTED_PATTERN = '[\t\s]*L?"[^"]*"' + QUOTED_PATTERN = r'[\t\s]*L?"[^"]*"' QuotedMatchedObj = re.search(QUOTED_PATTERN, Expression) if QuotedMatchedObj: MatchedStr = QuotedMatchedObj.group().strip() @@ -847,7 +847,7 @@ def CheckPcdValue(self): # # Delete the 'L' prefix of a quoted string, this operation is for eval() # - QUOTED_PATTERN = '[\t\s]*L?"[^"]*"' + QUOTED_PATTERN = r'[\t\s]*L?"[^"]*"' QuotedMatchedObj = re.search(QUOTED_PATTERN, DefaultValue) if QuotedMatchedObj: MatchedStr = QuotedMatchedObj.group().strip() diff --git a/BaseTools/Source/Python/UPT/Xml/IniToXml.py b/BaseTools/Source/Python/UPT/Xml/IniToXml.py index 3dc4001313de..2c01c97fa519 100644 --- a/BaseTools/Source/Python/UPT/Xml/IniToXml.py +++ b/BaseTools/Source/Python/UPT/Xml/IniToXml.py @@ -200,9 +200,9 @@ def ValidateRegValues(Key, Value): ('[a-fA-F0-9]{8}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}' '-[a-fA-F0-9]{4}-[a-fA-F0-9]{12}', ST.ERR_GUID_VALUE % Value), - 'Version' : ('[0-9]+(\.[0-9]+)?', ST.ERR_VERSION_VALUE % \ + 'Version' : (r'[0-9]+(\.[0-9]+)?', ST.ERR_VERSION_VALUE % \ (Key, Value)), - 'XmlSpecification' : ('1\.1', ST.ERR_VERSION_XMLSPEC % Value) + 'XmlSpecification' : (r'1\.1', ST.ERR_VERSION_XMLSPEC % Value) } if Key not in ValidateMap: return True, '' diff --git a/BaseTools/Source/Python/UPT/Xml/PcdXml.py b/BaseTools/Source/Python/UPT/Xml/PcdXml.py index bbcee45a0132..ca95c820c9a9 100644 --- a/BaseTools/Source/Python/UPT/Xml/PcdXml.py +++ b/BaseTools/Source/Python/UPT/Xml/PcdXml.py @@ -100,11 +100,11 @@ def ToXml(self, PcdError, Key): def TransferValidRange2Expr(self, TokenSpaceGuidCName, CName, ValidRange): if self.Expression: pass - INT_RANGE_PATTERN1 = '[\t\s]*[0-9]+[\t\s]*-[\t\s]*[0-9]+' - INT_RANGE_PATTERN2 = '[\t\s]*(LT|GT|LE|GE|XOR|EQ)[\t\s]+\d+[\t\s]*' + INT_RANGE_PATTERN1 = r'[\t\s]*[0-9]+[\t\s]*-[\t\s]*[0-9]+' + INT_RANGE_PATTERN2 = r'[\t\s]*(LT|GT|LE|GE|XOR|EQ)[\t\s]+\d+[\t\s]*' HEX_RANGE_PATTERN1 = \ - '[\t\s]*0[xX][a-fA-F0-9]+[\t\s]*-[\t\s]*0[xX][a-fA-F0-9]+' - HEX_RANGE_PATTERN2 = '[\t\s]*(LT|GT|LE|GE|XOR|EQ)[\t\s]+0[xX][a-fA-F0-9]+[\t\s]*' + r'[\t\s]*0[xX][a-fA-F0-9]+[\t\s]*-[\t\s]*0[xX][a-fA-F0-9]+' + HEX_RANGE_PATTERN2 = r'[\t\s]*(LT|GT|LE|GE|XOR|EQ)[\t\s]+0[xX][a-fA-F0-9]+[\t\s]*' IntMatch1 = re.compile(INT_RANGE_PATTERN1) IntMatch2 = re.compile(INT_RANGE_PATTERN2) HexMatch1 = re.compile(HEX_RANGE_PATTERN1) @@ -158,18 +158,18 @@ def TransferValidEpxr2ValidRange(self, ValidRangeExpr): pass PCD_PATTERN = \ - '[\t\s]*[_a-zA-Z][a-zA-Z0-9_]*[\t\s]*\.[\t\s]*[_a-zA-Z][a-zA-Z0-9_]*[\t\s]*' + r'[\t\s]*[_a-zA-Z][a-zA-Z0-9_]*[\t\s]*\.[\t\s]*[_a-zA-Z][a-zA-Z0-9_]*[\t\s]*' IntPattern1 = \ - '[\t\s]*\([\t\s]*'+PCD_PATTERN+'[\t\s]+GE[\t\s]+\d+[\t\s]*\)[\t\s]+AND[\t\s]+\([\t\s]*'+\ - PCD_PATTERN+'[\t\s]+LE[\t\s]+\d+[\t\s]*\)' + r'[\t\s]*\([\t\s]*'+PCD_PATTERN+r'[\t\s]+GE[\t\s]+\d+[\t\s]*\)[\t\s]+AND[\t\s]+\([\t\s]*'+\ + PCD_PATTERN+r'[\t\s]+LE[\t\s]+\d+[\t\s]*\)' IntPattern1 = IntPattern1.replace(' ', '') - IntPattern2 = '[\t\s]*'+PCD_PATTERN+'[\t\s]+(LT|GT|LE|GE|XOR|EQ)[\t\s]+\d+[\t\s]*' + IntPattern2 = r'[\t\s]*'+PCD_PATTERN+r'[\t\s]+(LT|GT|LE|GE|XOR|EQ)[\t\s]+\d+[\t\s]*' HexPattern1 = \ - '[\t\s]*\([\t\s]*'+PCD_PATTERN+'[\t\s]+GE[\t\s]+0[xX][0-9a-fA-F]+[\t\s]*\)[\t\s]+AND[\t\s]+\([\t\s]*'+\ - PCD_PATTERN+'[\t\s]+LE[\t\s]+0[xX][0-9a-fA-F]+[\t\s]*\)' + r'[\t\s]*\([\t\s]*'+PCD_PATTERN+r'[\t\s]+GE[\t\s]+0[xX][0-9a-fA-F]+[\t\s]*\)[\t\s]+AND[\t\s]+\([\t\s]*'+\ + PCD_PATTERN+r'[\t\s]+LE[\t\s]+0[xX][0-9a-fA-F]+[\t\s]*\)' HexPattern1 = HexPattern1.replace(' ', '') - HexPattern2 = '[\t\s]*'+PCD_PATTERN+'[\t\s]+(LT|GT|LE|GE|XOR|EQ)[\t\s]+0[xX][0-9a-zA-Z]+[\t\s]*' + HexPattern2 = r'[\t\s]*'+PCD_PATTERN+r'[\t\s]+(LT|GT|LE|GE|XOR|EQ)[\t\s]+0[xX][0-9a-zA-Z]+[\t\s]*' # # Do the Hex1 conversion @@ -180,7 +180,7 @@ def TransferValidEpxr2ValidRange(self, ValidRangeExpr): # # To match items on both sides of '-' # - RangeItemList = re.compile('[\t\s]*0[xX][0-9a-fA-F]+[\t\s]*').findall(HexMatchedItem) + RangeItemList = re.compile(r'[\t\s]*0[xX][0-9a-fA-F]+[\t\s]*').findall(HexMatchedItem) if RangeItemList and len(RangeItemList) == 2: HexRangeDict[HexMatchedItem] = RangeItemList @@ -204,7 +204,7 @@ def TransferValidEpxr2ValidRange(self, ValidRangeExpr): # # To match items on both sides of '-' # - RangeItemList = re.compile('[\t\s]*\d+[\t\s]*').findall(MatchedItem) + RangeItemList = re.compile(r'[\t\s]*\d+[\t\s]*').findall(MatchedItem) if RangeItemList and len(RangeItemList) == 2: IntRangeDict[MatchedItem] = RangeItemList diff --git a/BaseTools/Source/Python/UPT/Xml/XmlParser.py b/BaseTools/Source/Python/UPT/Xml/XmlParser.py index 8e22a280f655..f23958883180 100644 --- a/BaseTools/Source/Python/UPT/Xml/XmlParser.py +++ b/BaseTools/Source/Python/UPT/Xml/XmlParser.py @@ -281,33 +281,33 @@ def ToXml(self, DistP): # XmlContent = \ re.sub(r'[\s\r\n]*SupArchList[\s\r\n]*=[\s\r\n]*"[\s\r\n]*COMMON' - '[\s\r\n]*"', '', XmlContent) + r'[\s\r\n]*"', '', XmlContent) XmlContent = \ re.sub(r'[\s\r\n]*SupArchList[\s\r\n]*=[\s\r\n]*"[\s\r\n]*common' - '[\s\r\n]*"', '', XmlContent) + r'[\s\r\n]*"', '', XmlContent) # # Remove COMMON # XmlContent = \ re.sub(r'[\s\r\n]*[\s\r\n]*COMMON[\s\r\n]*' - '[\s\r\n]*', '', XmlContent) + r'[\s\r\n]*', '', XmlContent) # # Remove common # XmlContent = \ re.sub(r'[\s\r\n]*[\s\r\n]*' - 'common[\s\r\n]*[\s\r\n]*', '', XmlContent) + r'common[\s\r\n]*[\s\r\n]*', '', XmlContent) # # Remove SupModList="COMMON" or "common" # XmlContent = \ re.sub(r'[\s\r\n]*SupModList[\s\r\n]*=[\s\r\n]*"[\s\r\n]*COMMON' - '[\s\r\n]*"', '', XmlContent) + r'[\s\r\n]*"', '', XmlContent) XmlContent = \ re.sub(r'[\s\r\n]*SupModList[\s\r\n]*=[\s\r\n]*"[\s\r\n]*common' - '[\s\r\n]*"', '', XmlContent) + r'[\s\r\n]*"', '', XmlContent) return XmlContent diff --git a/CryptoPkg/CryptoPkg.dec b/CryptoPkg/CryptoPkg.dec index e613b6b1ae30..dc521c09a805 100644 --- a/CryptoPkg/CryptoPkg.dec +++ b/CryptoPkg/CryptoPkg.dec @@ -22,6 +22,7 @@ [Includes.Common.Private] Private Library/Include + Library/OpensslLib/openssl Library/OpensslLib/openssl/include Library/OpensslLib/openssl/providers/common/include Library/OpensslLib/openssl/providers/implementations/include diff --git a/CryptoPkg/CryptoPkg.dsc b/CryptoPkg/CryptoPkg.dsc index f23fb6f945e1..8492f91b12ed 100644 --- a/CryptoPkg/CryptoPkg.dsc +++ b/CryptoPkg/CryptoPkg.dsc @@ -6,6 +6,7 @@ # Copyright (c) 2020, Hewlett Packard Enterprise Development LP. All rights reserved.
# Copyright (c) 2022, Loongson Technology Corporation Limited. All rights reserved.
# Copyright (c) 2023, Arm Limited. All rights reserved.
+# Copyright (c) 2024, American Megatrends International LLC. All rights reserved.
# SPDX-License-Identifier: BSD-2-Clause-Patent # ## @@ -83,6 +84,12 @@ DEFINE SMM_FULL_GUID = 1930CE7E-6598-48ED-8AB1-EBE7E85EC254 DEFINE SMM_STD_ACCEL_GUID = 828959D3-CEA6-4B79-B1FC-5AFA0D7F2144 DEFINE SMM_FULL_ACCEL_GUID = C1760694-AB3A-4532-8C6D-52D8F86EB1AA + DEFINE MM_STANDALONE_CRYPTO_GUID = 4E14BAAE-8AA0-4F28-B1F0-53215E4DEA81 + DEFINE MM_STANDALONE_STD_GUID = FB88FFE8-C6E3-4752-8E85-0865DF7CDB1F + DEFINE MM_STANDALONE_FULL_GUID = 4A6F4C6E-6207-4801-9706-B9429936A38C + DEFINE MM_STANDALONE_STD_ACCEL_GUID = 9EF13BFA-912E-4589-8D6A-3ECCF1156B5E + DEFINE MM_STANDALONE_FULL_ACCEL_GUID = 0A13116A-D6BF-4E4A-90DC-615C4C0A711D + !if $(CRYPTO_SERVICES) == TARGET_UNIT_TESTS !include UnitTestFrameworkPkg/UnitTestFrameworkPkgTarget.dsc.inc @@ -162,6 +169,15 @@ BaseCryptLib|CryptoPkg/Library/BaseCryptLib/SmmCryptLib.inf TlsLib|CryptoPkg/Library/TlsLibNull/TlsLibNull.inf +[LibraryClasses.common.MM_STANDALONE] + BaseCryptLib|CryptoPkg/Library/BaseCryptLib/SmmCryptLib.inf + MmServicesTableLib|MdePkg/Library/StandaloneMmServicesTableLib/StandaloneMmServicesTableLib.inf + StandaloneMmDriverEntryPoint|MdePkg/Library/StandaloneMmDriverEntryPoint/StandaloneMmDriverEntryPoint.inf + TlsLib|CryptoPkg/Library/TlsLibNull/TlsLibNull.inf + PcdLib|MdePkg/Library/BasePcdLibNull/BasePcdLibNull.inf + ReportStatusCodeLib|MdePkg/Library/BaseReportStatusCodeLibNull/BaseReportStatusCodeLibNull.inf + MemoryAllocationLib|StandaloneMmPkg/Library/StandaloneMmMemoryAllocationLib/StandaloneMmMemoryAllocationLib.inf + [LibraryClasses.common.UEFI_APPLICATION] UefiApplicationEntryPoint|MdePkg/Library/UefiApplicationEntryPoint/UefiApplicationEntryPoint.inf UefiBootServicesTableLib|MdePkg/Library/UefiBootServicesTableLib/UefiBootServicesTableLib.inf @@ -372,10 +388,12 @@ CryptoPkg/Library/OpensslLib/OpensslLibCrypto.inf CryptoPkg/Library/OpensslLib/OpensslLib.inf CryptoPkg/Library/OpensslLib/OpensslLibFull.inf + CryptoPkg/Library/OpensslLib/OpensslLibSm3.inf CryptoPkg/Library/BaseHashApiLib/BaseHashApiLib.inf CryptoPkg/Library/BaseCryptLibOnProtocolPpi/PeiCryptLib.inf CryptoPkg/Library/BaseCryptLibOnProtocolPpi/DxeCryptLib.inf CryptoPkg/Library/BaseCryptLibOnProtocolPpi/SmmCryptLib.inf + CryptoPkg/Library/BaseCryptLibOnProtocolPpi/StandaloneMmCryptLib.inf # # Build verification of target-based unit tests # @@ -579,6 +597,59 @@ MSFT:*_*_IA32_DLINK_FLAGS = /ALIGN:4096 MSFT:*_*_X64_DLINK_FLAGS = /ALIGN:4096 } + # + # CryptoStandaloneMm with OpensslLib instance with no SSL or EC services + # + CryptoPkg/Driver/CryptoStandaloneMm.inf { + + FILE_GUID = $(MM_STANDALONE_CRYPTO_GUID) + + OpensslLib|CryptoPkg/Library/OpensslLib/OpensslLibCrypto.inf + } + # + # CryptoStandaloneMm with OpensslLib instance with no SSL services + # + CryptoPkg/Driver/CryptoStandaloneMm.inf { + + FILE_GUID = $(MM_STANDALONE_STD_GUID) + + OpensslLib|CryptoPkg/Library/OpensslLib/OpensslLib.inf + } + # + # CryptoStandaloneMm with OpensslLib instance with no all services + # + CryptoPkg/Driver/CryptoStandaloneMm.inf { + + FILE_GUID = $(MM_STANDALONE_FULL_GUID) + + OpensslLib|CryptoPkg/Library/OpensslLib/OpensslLibFull.inf + } + # + # CryptoStandaloneMm with IA32/X64/AARCH64 performance optimized OpensslLib instance with no EC services + # IA32/X64 assembly optimizations required larger alignments + # + CryptoPkg/Driver/CryptoStandaloneMm.inf { + + FILE_GUID = $(MM_STANDALONE_STD_ACCEL_GUID) + + OpensslLib|CryptoPkg/Library/OpensslLib/OpensslLibAccel.inf + + MSFT:*_*_IA32_DLINK_FLAGS = /ALIGN:64 + MSFT:*_*_X64_DLINK_FLAGS = /ALIGN:256 + } + # + # CryptoStandaloneMm with IA32/X64/AARCH64 performance optimized OpensslLib instance with all services + # IA32/X64 assembly optimizations required larger alignments + # + CryptoPkg/Driver/CryptoStandaloneMm.inf { + + FILE_GUID = $(MM_STANDALONE_FULL_ACCEL_GUID) + + OpensslLib|CryptoPkg/Library/OpensslLib/OpensslLibFullAccel.inf + + MSFT:*_*_IA32_DLINK_FLAGS = /ALIGN:4096 + MSFT:*_*_X64_DLINK_FLAGS = /ALIGN:4096 + } !endif [BuildOptions] diff --git a/CryptoPkg/Driver/CryptoStandaloneMm.c b/CryptoPkg/Driver/CryptoStandaloneMm.c new file mode 100644 index 000000000000..2ea2f5b798df --- /dev/null +++ b/CryptoPkg/Driver/CryptoStandaloneMm.c @@ -0,0 +1,41 @@ +/** @file + Installs the EDK II Crypto SMM Protocol in Standalone MM. + + Copyright (c) 2024, American Megatrends International LLC. All rights reserved.
+ SPDX-License-Identifier: BSD-2-Clause-Patent + +**/ + +#include +#include +#include + +extern CONST EDKII_CRYPTO_PROTOCOL mEdkiiCrypto; + +/** + The module Entry Point of the Crypto Standalone MM Driver. + + @param[in] ImageHandle The firmware allocated handle for the EFI image. + @param[in] SystemTable A pointer to the EFI System Table. + + @retval EFI_SUCCESS The entry point is executed successfully. + @retval Other Some error occurs when executing this entry point. + +**/ +EFI_STATUS +EFIAPI +CryptoStandaloneMmEntry ( + IN EFI_HANDLE ImageHandle, + IN EFI_MM_SYSTEM_TABLE *MmSystemTable + ) +{ + EFI_HANDLE Handle; + + Handle = NULL; + return gMmst->MmInstallProtocolInterface ( + &Handle, + &gEdkiiSmmCryptoProtocolGuid, + EFI_NATIVE_INTERFACE, + (EDKII_CRYPTO_PROTOCOL *)&mEdkiiCrypto + ); +} diff --git a/CryptoPkg/Driver/CryptoStandaloneMm.inf b/CryptoPkg/Driver/CryptoStandaloneMm.inf new file mode 100644 index 000000000000..e78a40cf509b --- /dev/null +++ b/CryptoPkg/Driver/CryptoStandaloneMm.inf @@ -0,0 +1,48 @@ +## @file +# Produces the EDK II SMM Crypto Protocol using the library services from +# BaseCryptLib and TlsLib for Standalone MM. +# +# Copyright (c) 2024, American Megatrends International LLC. All rights reserved.
+# SPDX-License-Identifier: BSD-2-Clause-Patent +# +## + +[Defines] + INF_VERSION = 0x0001001B + PI_SPECIFICATION_VERSION = 0x00010032 + BASE_NAME = CryptoStandaloneMm + MODULE_UNI_FILE = Crypto.uni + FILE_GUID = B7946FEA-15EF-43F4-9FF6-0F71E032ECF5 + MODULE_TYPE = MM_STANDALONE + VERSION_STRING = 1.0 + ENTRY_POINT = CryptoStandaloneMmEntry + +# +# The following information is for reference only and not required by the build tools. +# +# VALID_ARCHITECTURES = IA32 X64 +# + +[Sources] + Crypto.c + CryptoStandaloneMm.c + +[Packages] + MdePkg/MdePkg.dec + CryptoPkg/CryptoPkg.dec + +[LibraryClasses] + BaseCryptLib + DebugLib + MmServicesTableLib + StandaloneMmDriverEntryPoint + TlsLib + +[Protocols] + gEdkiiSmmCryptoProtocolGuid ## PRODUCES + +[Pcd] + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceFamilyEnable ## CONSUMES + +[Depex] + TRUE diff --git a/CryptoPkg/Library/BaseCryptLib/PeiCryptLib.inf b/CryptoPkg/Library/BaseCryptLib/PeiCryptLib.inf index d10c83b53c09..a979652538de 100644 --- a/CryptoPkg/Library/BaseCryptLib/PeiCryptLib.inf +++ b/CryptoPkg/Library/BaseCryptLib/PeiCryptLib.inf @@ -30,7 +30,7 @@ # # The following information is for reference only and not required by the build tools. # -# VALID_ARCHITECTURES = IA32 X64 +# VALID_ARCHITECTURES = IA32 X64 ARM AARCH64 # [Sources] diff --git a/CryptoPkg/Library/BaseCryptLib/Pk/CryptX509.c b/CryptoPkg/Library/BaseCryptLib/Pk/CryptX509.c index 349d37b045fb..0239fee4e12d 100644 --- a/CryptoPkg/Library/BaseCryptLib/Pk/CryptX509.c +++ b/CryptoPkg/Library/BaseCryptLib/Pk/CryptX509.c @@ -102,7 +102,6 @@ X509ConstructCertificateStackV ( STACK_OF (X509) *CertStack; BOOLEAN Status; - UINTN Index; // // Check input parameters. @@ -124,7 +123,7 @@ X509ConstructCertificateStackV ( } } - for (Index = 0; ; Index++) { + while (TRUE) { // // If Cert is NULL, then it is the end of the list. // @@ -1057,7 +1056,7 @@ X509GetSerialNumber ( } if (SerialNumber != NULL) { - CopyMem (SerialNumber, Asn1Integer->data, *SerialNumberSize); + CopyMem (SerialNumber, Asn1Integer->data, (UINTN)Asn1Integer->length); Status = TRUE; } diff --git a/CryptoPkg/Library/BaseCryptLib/SysCall/ConstantTimeClock.c b/CryptoPkg/Library/BaseCryptLib/SysCall/ConstantTimeClock.c index 2956b92d0827..3f3ec3e81f41 100644 --- a/CryptoPkg/Library/BaseCryptLib/SysCall/ConstantTimeClock.c +++ b/CryptoPkg/Library/BaseCryptLib/SysCall/ConstantTimeClock.c @@ -42,3 +42,32 @@ gmtime ( { return NULL; } + +time_t +mktime ( + struct tm *t + ) +{ + return 0; +} + +unsigned int +sleep ( + unsigned int seconds + ) +{ + return 0; +} + +int +gettimeofday ( + struct timeval *tv, + struct timezone *tz + ) +{ + tv->tv_sec = 0; + tv->tv_usec = 0; + return 0; +} + +long timezone; diff --git a/CryptoPkg/Library/BaseCryptLib/SysCall/RuntimeMemAllocation.c b/CryptoPkg/Library/BaseCryptLib/SysCall/RuntimeMemAllocation.c index 0d2ca604ea3e..27b0b5e0083e 100644 --- a/CryptoPkg/Library/BaseCryptLib/SysCall/RuntimeMemAllocation.c +++ b/CryptoPkg/Library/BaseCryptLib/SysCall/RuntimeMemAllocation.c @@ -33,7 +33,7 @@ SPDX-License-Identifier: BSD-2-Clause-Patent #define RT_PAGE_FREE 0x00000000 #define RT_PAGE_USED 0x00000001 -#define MIN_REQUIRED_BLOCKS 600 +#define MIN_REQUIRED_BLOCKS 1100 // // Memory Page Table diff --git a/CryptoPkg/Library/BaseCryptLib/SysCall/TimerWrapper.c b/CryptoPkg/Library/BaseCryptLib/SysCall/TimerWrapper.c index 2dfc6fe6c593..9b3a2911d0b3 100644 --- a/CryptoPkg/Library/BaseCryptLib/SysCall/TimerWrapper.c +++ b/CryptoPkg/Library/BaseCryptLib/SysCall/TimerWrapper.c @@ -9,6 +9,7 @@ SPDX-License-Identifier: BSD-2-Clause-Patent #include #include +#include #include // @@ -19,6 +20,8 @@ SPDX-License-Identifier: BSD-2-Clause-Patent #define SECSPERHOUR (60 * 60) #define SECSPERDAY (24 * SECSPERHOUR) +long timezone; + // // The arrays give the cumulative number of days up to the first of the // month number used as the index (1 -> 12) for regular and leap years. @@ -79,6 +82,37 @@ IsLeap ( return (Remainder1 == 0 && (Remainder2 != 0 || Remainder3 == 0)); } +STATIC +time_t +CalculateTimeT ( + EFI_TIME *Time + ) +{ + time_t CalTime; + UINTN Year; + + // + // Years Handling + // UTime should now be set to 00:00:00 on Jan 1 of the current year. + // + for (Year = 1970, CalTime = 0; Year != Time->Year; Year++) { + CalTime = CalTime + (time_t)(CumulativeDays[IsLeap (Year)][13] * SECSPERDAY); + } + + // + // Add in number of seconds for current Month, Day, Hour, Minute, Seconds, and TimeZone adjustment + // + CalTime = CalTime + + (time_t)((Time->TimeZone != EFI_UNSPECIFIED_TIMEZONE) ? (Time->TimeZone * 60) : 0) + + (time_t)(CumulativeDays[IsLeap (Time->Year)][Time->Month] * SECSPERDAY) + + (time_t)(((Time->Day > 0) ? Time->Day - 1 : 0) * SECSPERDAY) + + (time_t)(Time->Hour * SECSPERHOUR) + + (time_t)(Time->Minute * 60) + + (time_t)Time->Second; + + return CalTime; +} + /* Get the system time as seconds elapsed since midnight, January 1, 1970. */ // INTN time( // INTN *timer @@ -91,7 +125,6 @@ time ( EFI_STATUS Status; EFI_TIME Time; time_t CalTime; - UINTN Year; // // Get the current time and date information @@ -101,24 +134,7 @@ time ( return 0; } - // - // Years Handling - // UTime should now be set to 00:00:00 on Jan 1 of the current year. - // - for (Year = 1970, CalTime = 0; Year != Time.Year; Year++) { - CalTime = CalTime + (time_t)(CumulativeDays[IsLeap (Year)][13] * SECSPERDAY); - } - - // - // Add in number of seconds for current Month, Day, Hour, Minute, Seconds, and TimeZone adjustment - // - CalTime = CalTime + - (time_t)((Time.TimeZone != EFI_UNSPECIFIED_TIMEZONE) ? (Time.TimeZone * 60) : 0) + - (time_t)(CumulativeDays[IsLeap (Time.Year)][Time.Month] * SECSPERDAY) + - (time_t)(((Time.Day > 0) ? Time.Day - 1 : 0) * SECSPERDAY) + - (time_t)(Time.Hour * SECSPERHOUR) + - (time_t)(Time.Minute * 60) + - (time_t)Time.Second; + CalTime = CalculateTimeT (&Time); if (timer != NULL) { *timer = CalTime; @@ -127,6 +143,24 @@ time ( return CalTime; } +time_t +mktime ( + struct tm *t + ) +{ + EFI_TIME Time = { + .Year = (UINT16)t->tm_year, + .Month = (UINT8)t->tm_mon, + .Day = (UINT8)t->tm_mday, + .Hour = (UINT8)t->tm_hour, + .Minute = (UINT8)t->tm_min, + .Second = (UINT8)t->tm_sec, + .TimeZone = EFI_UNSPECIFIED_TIMEZONE, + }; + + return CalculateTimeT (&Time); +} + // // Convert a time value from type time_t to struct tm. // @@ -195,3 +229,23 @@ gmtime ( return GmTime; } + +unsigned int +sleep ( + unsigned int seconds + ) +{ + gBS->Stall (seconds * 1000 * 1000); + return 0; +} + +int +gettimeofday ( + struct timeval *tv, + struct timezone *tz + ) +{ + tv->tv_sec = (long)time (NULL); + tv->tv_usec = 0; + return 0; +} diff --git a/CryptoPkg/Library/BaseCryptLib/SysCall/UnitTestHostCrtWrapper.c b/CryptoPkg/Library/BaseCryptLib/SysCall/UnitTestHostCrtWrapper.c index 244e57437ecd..3aa76e0a6b14 100644 --- a/CryptoPkg/Library/BaseCryptLib/SysCall/UnitTestHostCrtWrapper.c +++ b/CryptoPkg/Library/BaseCryptLib/SysCall/UnitTestHostCrtWrapper.c @@ -104,4 +104,24 @@ getegid ( return 0; } -int errno = 0; +unsigned int +sleep ( + unsigned int seconds + ) +{ + return 0; +} + +int +gettimeofday ( + struct timeval *tv, + struct timezone *tz + ) +{ + tv->tv_sec = 0; + tv->tv_usec = 0; + return 0; +} + +int errno = 0; +long timezone; diff --git a/CryptoPkg/Library/BaseCryptLibMbedTls/PeiCryptLib.inf b/CryptoPkg/Library/BaseCryptLibMbedTls/PeiCryptLib.inf index 3c057660d884..5ff7bf4c7b70 100644 --- a/CryptoPkg/Library/BaseCryptLibMbedTls/PeiCryptLib.inf +++ b/CryptoPkg/Library/BaseCryptLibMbedTls/PeiCryptLib.inf @@ -99,8 +99,7 @@ # MSFT:*_*_*_CC_FLAGS = /wd4090 /wd4718 - GCC:*_CLANG35_*_CC_FLAGS = -std=c99 - GCC:*_CLANG38_*_CC_FLAGS = -std=c99 + GCC:*_CLANGDWARF_*_CC_FLAGS = -std=gnu99 GCC:*_CLANGPDB_*_CC_FLAGS = -std=c99 -Wno-error=incompatible-pointer-types XCODE:*_*_*_CC_FLAGS = -std=c99 diff --git a/CryptoPkg/Library/BaseCryptLibMbedTls/RuntimeCryptLib.inf b/CryptoPkg/Library/BaseCryptLibMbedTls/RuntimeCryptLib.inf index 824aa4fa5d27..7cf478ad39e4 100644 --- a/CryptoPkg/Library/BaseCryptLibMbedTls/RuntimeCryptLib.inf +++ b/CryptoPkg/Library/BaseCryptLibMbedTls/RuntimeCryptLib.inf @@ -87,11 +87,7 @@ # Remove these [BuildOptions] after this library is cleaned up # [BuildOptions] - # - # suppress the following warnings so we do not break the build with warnings-as-errors: - # - GCC:*_CLANG35_*_CC_FLAGS = -std=c99 - GCC:*_CLANG38_*_CC_FLAGS = -std=c99 + GCC:*_CLANGDWARF_*_CC_FLAGS = -std=gnu99 GCC:*_CLANGPDB_*_CC_FLAGS = -std=c99 -Wno-error=incompatible-pointer-types XCODE:*_*_*_CC_FLAGS = -std=c99 diff --git a/CryptoPkg/Library/BaseCryptLibMbedTls/SecCryptLib.inf b/CryptoPkg/Library/BaseCryptLibMbedTls/SecCryptLib.inf index e61e07dfa485..e21deb290c83 100644 --- a/CryptoPkg/Library/BaseCryptLibMbedTls/SecCryptLib.inf +++ b/CryptoPkg/Library/BaseCryptLibMbedTls/SecCryptLib.inf @@ -73,11 +73,7 @@ # Remove these [BuildOptions] after this library is cleaned up # [BuildOptions] - # - # suppress the following warnings so we do not break the build with warnings-as-errors: - # - GCC:*_CLANG35_*_CC_FLAGS = -std=c99 - GCC:*_CLANG38_*_CC_FLAGS = -std=c99 + GCC:*_CLANGDWARF_*_CC_FLAGS = -std=gnu99 GCC:*_CLANGPDB_*_CC_FLAGS = -std=c99 -Wno-error=incompatible-pointer-types XCODE:*_*_*_CC_FLAGS = -std=c99 diff --git a/CryptoPkg/Library/BaseCryptLibMbedTls/SmmCryptLib.inf b/CryptoPkg/Library/BaseCryptLibMbedTls/SmmCryptLib.inf index 649c2a3c0c4f..33e86b453d72 100644 --- a/CryptoPkg/Library/BaseCryptLibMbedTls/SmmCryptLib.inf +++ b/CryptoPkg/Library/BaseCryptLibMbedTls/SmmCryptLib.inf @@ -87,12 +87,7 @@ # Remove these [BuildOptions] after this library is cleaned up # [BuildOptions] - # - # suppress the following warnings so we do not break the build with warnings-as-errors: - # - XCODE:*_*_*_CC_FLAGS = -mmmx -msse -std=c99 - GCC:*_CLANG35_*_CC_FLAGS = -std=c99 - GCC:*_CLANG38_*_CC_FLAGS = -std=c99 + GCC:*_CLANGDWARF_*_CC_FLAGS = -std=gnu99 GCC:*_CLANGPDB_*_CC_FLAGS = -std=c99 -Wno-error=incompatible-pointer-types diff --git a/CryptoPkg/Library/BaseCryptLibOnProtocolPpi/StandaloneMmCryptLib.c b/CryptoPkg/Library/BaseCryptLibOnProtocolPpi/StandaloneMmCryptLib.c new file mode 100644 index 000000000000..184333f8af05 --- /dev/null +++ b/CryptoPkg/Library/BaseCryptLibOnProtocolPpi/StandaloneMmCryptLib.c @@ -0,0 +1,79 @@ +/** @file + Implements the GetCryptoServices() API that retuns a pointer to the EDK II + SMM Crypto Protocol. + + Copyright (c) 2024, American Megatrends International LLC. All rights reserved.
+ SPDX-License-Identifier: BSD-2-Clause-Patent + +**/ + +#include +#include +#include +#include +#include + +EDKII_SMM_CRYPTO_PROTOCOL *mSmmCryptoProtocol = NULL; + +/** + Internal worker function that returns the pointer to an EDK II Crypto + Protocol/PPI. The layout of the PPI, DXE Protocol, and SMM Protocol are + identical which allows the implementation of the BaseCryptLib functions that + call through a Protocol/PPI to be shared for the PEI, DXE, and SMM + implementations. + + This SMM implementation returns the pointer to the EDK II SMM Crypto Protocol + that was found in the library constructor SmmCryptLibConstructor(). +**/ +VOID * +GetCryptoServices ( + VOID + ) +{ + return (VOID *)mSmmCryptoProtocol; +} + +/** + Constructor looks up the EDK II SMM Crypto Protocol and verifies that it is + not NULL and has a high enough version value to support all the BaseCryptLib + functions. + + @param ImageHandle The firmware allocated handle for the EFI image. + @param MmSystemTable A pointer to the MM System Table. + + @retval EFI_SUCCESS The EDK II SMM Crypto Protocol was found. + @retval EFI_NOT_FOUND The EDK II SMM Crypto Protocol was not found. +**/ +EFI_STATUS +EFIAPI +StandaloneMmCryptLibConstructor ( + IN EFI_HANDLE ImageHandle, + IN EFI_MM_SYSTEM_TABLE *MmSystemTable + ) +{ + EFI_STATUS Status; + UINTN Version; + + Status = gMmst->MmLocateProtocol ( + &gEdkiiSmmCryptoProtocolGuid, + NULL, + (VOID **)&mSmmCryptoProtocol + ); + if (EFI_ERROR (Status) || (mSmmCryptoProtocol == NULL)) { + DEBUG ((DEBUG_ERROR, "[StandaloneMmCryptLib] Failed to locate Crypto SMM Protocol. Status = %r\n", Status)); + ASSERT_EFI_ERROR (Status); + ASSERT (mSmmCryptoProtocol != NULL); + mSmmCryptoProtocol = NULL; + return EFI_NOT_FOUND; + } + + Version = mSmmCryptoProtocol->GetVersion (); + if (Version < EDKII_CRYPTO_VERSION) { + DEBUG ((DEBUG_ERROR, "[StandaloneMmCryptLib] Crypto SMM Protocol unsupported version %d\n", Version)); + ASSERT (Version >= EDKII_CRYPTO_VERSION); + mSmmCryptoProtocol = NULL; + return EFI_NOT_FOUND; + } + + return EFI_SUCCESS; +} diff --git a/CryptoPkg/Library/BaseCryptLibOnProtocolPpi/StandaloneMmCryptLib.inf b/CryptoPkg/Library/BaseCryptLibOnProtocolPpi/StandaloneMmCryptLib.inf new file mode 100644 index 000000000000..b229e75582de --- /dev/null +++ b/CryptoPkg/Library/BaseCryptLibOnProtocolPpi/StandaloneMmCryptLib.inf @@ -0,0 +1,45 @@ +## @file +# Implements the BaseCryptLib and TlsLib using the services of the EDK II Crypto +# SMM Protocol for Stdandalone MM. +# +# Copyright (c) 2024, American Megatrends International LLC. All rights reserved.
+# SPDX-License-Identifier: BSD-2-Clause-Patent +# +## + +[Defines] + INF_VERSION = 0x0001001B + BASE_NAME = StandaloneMmCryptLib + MODULE_UNI_FILE = CryptLib.uni + FILE_GUID = FA7EB4FD-7B3B-4FE4-BA95-1CE47CD0BE3E + VERSION_STRING = 1.0 + PI_SPECIFICATION_VERSION = 0x00010032 + MODULE_TYPE = MM_STANDALONE + LIBRARY_CLASS = BaseCryptLib | MM_STANDALONE + LIBRARY_CLASS = TlsLib | MM_STANDALONE + CONSTRUCTOR = StandaloneMmCryptLibConstructor + +# +# The following information is for reference only and not required by the build tools. +# +# VALID_ARCHITECTURES = IA32 X64 ARM AARCH64 +# + +[Packages] + MdePkg/MdePkg.dec + CryptoPkg/CryptoPkg.dec + +[LibraryClasses] + BaseLib + DebugLib + MmServicesTableLib + +[Sources] + StandaloneMmCryptLib.c + CryptLib.c + +[Protocols] + gEdkiiSmmCryptoProtocolGuid ## CONSUMES + +[Depex] + gEdkiiSmmCryptoProtocolGuid diff --git a/CryptoPkg/Library/Include/CrtLibSupport.h b/CryptoPkg/Library/Include/CrtLibSupport.h index afc00956ab4b..cd51e197e74d 100644 --- a/CryptoPkg/Library/Include/CrtLibSupport.h +++ b/CryptoPkg/Library/Include/CrtLibSupport.h @@ -16,6 +16,7 @@ SPDX-License-Identifier: BSD-2-Clause-Patent #include #include #include +#include #define OPENSSLDIR "" #define ENGINESDIR "" @@ -108,6 +109,7 @@ SPDX-License-Identifier: BSD-2-Clause-Patent typedef UINTN size_t; typedef UINTN off_t; typedef UINTN u_int; +typedef UINTN intptr_t; typedef INTN ptrdiff_t; typedef INTN ssize_t; typedef INT64 time_t; @@ -146,6 +148,8 @@ struct timeval { long tv_usec; /* time value, in microseconds */ }; +struct timezone; + struct sockaddr { __uint8_t sa_len; /* total length */ sa_family_t sa_family; /* address family */ @@ -157,6 +161,7 @@ struct sockaddr { // extern int errno; extern FILE *stderr; +extern long timezone; // // Function prototypes of CRT Library routines @@ -334,6 +339,22 @@ gmtime ( const time_t * ); +unsigned int +sleep ( + unsigned int seconds + ); + +int +gettimeofday ( + struct timeval *tv, + struct timezone *tz + ); + +time_t +mktime ( + struct tm *t + ); + uid_t getuid ( void @@ -433,6 +454,5 @@ strcat ( #define assert(expression) #define offsetof(type, member) OFFSET_OF(type,member) #define atoi(nptr) AsciiStrDecimalToUintn(nptr) -#define gettimeofday(tvp, tz) do { (tvp)->tv_sec = time(NULL); (tvp)->tv_usec = 0; } while (0) #endif diff --git a/CryptoPkg/Library/MbedTlsLib/MbedTlsLib.inf b/CryptoPkg/Library/MbedTlsLib/MbedTlsLib.inf index adcf7709022f..4ccd173eb0db 100644 --- a/CryptoPkg/Library/MbedTlsLib/MbedTlsLib.inf +++ b/CryptoPkg/Library/MbedTlsLib/MbedTlsLib.inf @@ -135,8 +135,7 @@ GCC:*_*_AARCH64_CC_FLAGS = -Wno-error=maybe-uninitialized -Wno-format -Wno-error=unused-but-set-variable -Wno-error=format GCC:*_*_RISCV64_CC_FLAGS = -Wno-error=maybe-uninitialized -Wno-format -Wno-error=unused-but-set-variable GCC:*_*_LOONGARCH64_CC_FLAGS = -Wno-error=maybe-uninitialized -Wno-format -Wno-error=unused-but-set-variable - GCC:*_CLANG35_*_CC_FLAGS = -std=c99 -Wno-error=uninitialized - GCC:*_CLANG38_*_CC_FLAGS = -std=c99 -Wno-error=uninitialized + GCC:*_CLANGDWARF_*_CC_FLAGS = -std=gnu99 -Wno-error=uninitialized GCC:*_CLANGPDB_*_CC_FLAGS = -std=c99 -Wno-error=uninitialized -Wno-error=incompatible-pointer-types -Wno-error=pointer-sign -Wno-error=implicit-function-declaration -Wno-error=ignored-pragma-optimize # suppress the following warnings in mbedtls so we don't break the build with warnings-as-errors: diff --git a/CryptoPkg/Library/MbedTlsLib/MbedTlsLibFull.inf b/CryptoPkg/Library/MbedTlsLib/MbedTlsLibFull.inf index 7715392a9d1e..a26e9ac060ba 100644 --- a/CryptoPkg/Library/MbedTlsLib/MbedTlsLibFull.inf +++ b/CryptoPkg/Library/MbedTlsLib/MbedTlsLibFull.inf @@ -139,8 +139,7 @@ GCC:*_*_AARCH64_CC_FLAGS = -Wno-error=maybe-uninitialized -Wno-format -Wno-error=unused-but-set-variable -Wno-error=format GCC:*_*_RISCV64_CC_FLAGS = -Wno-error=maybe-uninitialized -Wno-format -Wno-error=unused-but-set-variable GCC:*_*_LOONGARCH64_CC_FLAGS = -Wno-error=maybe-uninitialized -Wno-format -Wno-error=unused-but-set-variable - GCC:*_CLANG35_*_CC_FLAGS = -std=c99 -Wno-error=uninitialized - GCC:*_CLANG38_*_CC_FLAGS = -std=c99 -Wno-error=uninitialized + GCC:*_CLANGDWARF_*_CC_FLAGS = -std=gnu99 -Wno-error=uninitialized GCC:*_CLANGPDB_*_CC_FLAGS = -std=c99 -Wno-error=uninitialized -Wno-error=incompatible-pointer-types -Wno-error=pointer-sign -Wno-error=implicit-function-declaration -Wno-error=ignored-pragma-optimize # suppress the following warnings in mbedtls so we don't break the build with warnings-as-errors: diff --git a/CryptoPkg/Library/OpensslLib/OpensslGen/AARCH64-GCC/crypto/aes/aesv8-armx.S b/CryptoPkg/Library/OpensslLib/OpensslGen/AARCH64-GCC/crypto/aes/aesv8-armx.S index 5c50b4a0180b..1e61e46937d2 100644 --- a/CryptoPkg/Library/OpensslLib/OpensslGen/AARCH64-GCC/crypto/aes/aesv8-armx.S +++ b/CryptoPkg/Library/OpensslLib/OpensslGen/AARCH64-GCC/crypto/aes/aesv8-armx.S @@ -103,7 +103,7 @@ aes_v8_set_encrypt_key: .Loop192: tbl v6.16b,{v4.16b},v2.16b ext v5.16b,v0.16b,v3.16b,#12 -#ifdef __ARMEB__ +#ifdef __AARCH64EB__ st1 {v4.4s},[x2],#16 sub x2,x2,#8 #else @@ -1510,7 +1510,7 @@ aes_v8_ctr32_encrypt_blocks: ldr w5,[x3,#240] ldr w8, [x4, #12] -#ifdef __ARMEB__ +#ifdef __AARCH64EB__ ld1 {v0.16b},[x4] #else ld1 {v0.4s},[x4] @@ -1527,7 +1527,7 @@ aes_v8_ctr32_encrypt_blocks: add x7,x3,#32 mov w6,w5 csel x12,xzr,x12,lo -#ifndef __ARMEB__ +#ifndef __AARCH64EB__ rev w8, w8 #endif orr v1.16b,v0.16b,v0.16b diff --git a/CryptoPkg/Library/OpensslLib/OpensslGen/AARCH64-GCC/crypto/modes/ghashv8-armx.S b/CryptoPkg/Library/OpensslLib/OpensslGen/AARCH64-GCC/crypto/modes/ghashv8-armx.S index ae1afff44127..cf2eadb62953 100644 --- a/CryptoPkg/Library/OpensslLib/OpensslGen/AARCH64-GCC/crypto/modes/ghashv8-armx.S +++ b/CryptoPkg/Library/OpensslLib/OpensslGen/AARCH64-GCC/crypto/modes/ghashv8-armx.S @@ -101,7 +101,7 @@ gcm_gmult_v8: movi v19.16b,#0xe1 ld1 {v20.2d,v21.2d},[x1] //load twisted H, ... shl v19.2d,v19.2d,#57 -#ifndef __ARMEB__ +#ifndef __AARCH64EB__ rev64 v17.16b,v17.16b #endif ext v3.16b,v17.16b,v17.16b,#8 @@ -126,7 +126,7 @@ gcm_gmult_v8: eor v18.16b,v18.16b,v2.16b eor v0.16b,v0.16b,v18.16b -#ifndef __ARMEB__ +#ifndef __AARCH64EB__ rev64 v0.16b,v0.16b #endif ext v0.16b,v0.16b,v0.16b,#8 @@ -163,14 +163,14 @@ gcm_ghash_v8: ext v0.16b,v0.16b,v0.16b,#8 //rotate Xi ld1 {v16.2d},[x2],#16 //load [rotated] I[0] shl v19.2d,v19.2d,#57 //compose 0xc2.0 constant -#ifndef __ARMEB__ +#ifndef __AARCH64EB__ rev64 v16.16b,v16.16b rev64 v0.16b,v0.16b #endif ext v3.16b,v16.16b,v16.16b,#8 //rotate I[0] b.lo .Lodd_tail_v8 //x3 was less than 32 ld1 {v17.2d},[x2],x12 //load [rotated] I[1] -#ifndef __ARMEB__ +#ifndef __AARCH64EB__ rev64 v17.16b,v17.16b #endif ext v7.16b,v17.16b,v17.16b,#8 @@ -202,13 +202,13 @@ gcm_ghash_v8: eor v18.16b,v0.16b,v2.16b eor v1.16b,v1.16b,v17.16b ld1 {v17.2d},[x2],x12 //load [rotated] I[i+3] -#ifndef __ARMEB__ +#ifndef __AARCH64EB__ rev64 v16.16b,v16.16b #endif eor v1.16b,v1.16b,v18.16b pmull v18.1q,v0.1d,v19.1d //1st phase of reduction -#ifndef __ARMEB__ +#ifndef __AARCH64EB__ rev64 v17.16b,v17.16b #endif ins v2.d[0],v1.d[1] @@ -258,7 +258,7 @@ gcm_ghash_v8: eor v0.16b,v0.16b,v18.16b .Ldone_v8: -#ifndef __ARMEB__ +#ifndef __AARCH64EB__ rev64 v0.16b,v0.16b #endif ext v0.16b,v0.16b,v0.16b,#8 @@ -277,7 +277,7 @@ gcm_ghash_v8_4x: shl v19.2d,v19.2d,#57 //compose 0xc2.0 constant ld1 {v4.2d,v5.2d,v6.2d,v7.2d},[x2],#64 -#ifndef __ARMEB__ +#ifndef __AARCH64EB__ rev64 v0.16b,v0.16b rev64 v5.16b,v5.16b rev64 v6.16b,v6.16b @@ -321,7 +321,7 @@ gcm_ghash_v8_4x: eor v16.16b,v4.16b,v0.16b ld1 {v4.2d,v5.2d,v6.2d,v7.2d},[x2],#64 ext v3.16b,v16.16b,v16.16b,#8 -#ifndef __ARMEB__ +#ifndef __AARCH64EB__ rev64 v5.16b,v5.16b rev64 v6.16b,v6.16b rev64 v7.16b,v7.16b @@ -404,7 +404,7 @@ gcm_ghash_v8_4x: eor v1.16b,v1.16b,v17.16b ld1 {v4.2d,v5.2d,v6.2d},[x2] eor v1.16b,v1.16b,v18.16b -#ifndef __ARMEB__ +#ifndef __AARCH64EB__ rev64 v5.16b,v5.16b rev64 v6.16b,v6.16b rev64 v4.16b,v4.16b @@ -456,7 +456,7 @@ gcm_ghash_v8_4x: eor v1.16b,v1.16b,v17.16b ld1 {v4.2d,v5.2d},[x2] eor v1.16b,v1.16b,v18.16b -#ifndef __ARMEB__ +#ifndef __AARCH64EB__ rev64 v5.16b,v5.16b rev64 v4.16b,v4.16b #endif @@ -499,7 +499,7 @@ gcm_ghash_v8_4x: eor v1.16b,v1.16b,v17.16b ld1 {v4.2d},[x2] eor v1.16b,v1.16b,v18.16b -#ifndef __ARMEB__ +#ifndef __AARCH64EB__ rev64 v4.16b,v4.16b #endif @@ -539,7 +539,7 @@ gcm_ghash_v8_4x: eor v0.16b,v0.16b,v18.16b ext v0.16b,v0.16b,v0.16b,#8 -#ifndef __ARMEB__ +#ifndef __AARCH64EB__ rev64 v0.16b,v0.16b #endif st1 {v0.2d},[x0] //write out Xi diff --git a/CryptoPkg/Library/OpensslLib/OpensslGen/AARCH64-GCC/crypto/sha/sha256-armv8.S b/CryptoPkg/Library/OpensslLib/OpensslGen/AARCH64-GCC/crypto/sha/sha256-armv8.S index f762580f0932..92a596403a1b 100644 --- a/CryptoPkg/Library/OpensslLib/OpensslGen/AARCH64-GCC/crypto/sha/sha256-armv8.S +++ b/CryptoPkg/Library/OpensslLib/OpensslGen/AARCH64-GCC/crypto/sha/sha256-armv8.S @@ -4,57 +4,6 @@ // this file except in compliance with the License. You can obtain a copy // in the file LICENSE in the source distribution or at // https://www.openssl.org/source/license.html - -// ==================================================================== -// Written by Andy Polyakov for the OpenSSL -// project. The module is, however, dual licensed under OpenSSL and -// CRYPTOGAMS licenses depending on where you obtain it. For further -// details see http://www.openssl.org/~appro/cryptogams/. -// -// Permission to use under GPLv2 terms is granted. -// ==================================================================== -// -// SHA256/512 for ARMv8. -// -// Performance in cycles per processed byte and improvement coefficient -// over code generated with "default" compiler: -// -// SHA256-hw SHA256(*) SHA512 -// Apple A7 1.97 10.5 (+33%) 6.73 (-1%(**)) -// Cortex-A53 2.38 15.5 (+115%) 10.0 (+150%(***)) -// Cortex-A57 2.31 11.6 (+86%) 7.51 (+260%(***)) -// Denver 2.01 10.5 (+26%) 6.70 (+8%) -// X-Gene 20.0 (+100%) 12.8 (+300%(***)) -// Mongoose 2.36 13.0 (+50%) 8.36 (+33%) -// Kryo 1.92 17.4 (+30%) 11.2 (+8%) -// ThunderX2 2.54 13.2 (+40%) 8.40 (+18%) -// -// (*) Software SHA256 results are of lesser relevance, presented -// mostly for informational purposes. -// (**) The result is a trade-off: it's possible to improve it by -// 10% (or by 1 cycle per round), but at the cost of 20% loss -// on Cortex-A53 (or by 4 cycles per round). -// (***) Super-impressive coefficients over gcc-generated code are -// indication of some compiler "pathology", most notably code -// generated with -mgeneral-regs-only is significantly faster -// and the gap is only 40-90%. -// -// October 2016. -// -// Originally it was reckoned that it makes no sense to implement NEON -// version of SHA256 for 64-bit processors. This is because performance -// improvement on most wide-spread Cortex-A5x processors was observed -// to be marginal, same on Cortex-A53 and ~10% on A57. But then it was -// observed that 32-bit NEON SHA256 performs significantly better than -// 64-bit scalar version on *some* of the more recent processors. As -// result 64-bit NEON version of SHA256 was added to provide best -// all-round performance. For example it executes ~30% faster on X-Gene -// and Mongoose. [For reference, NEON version of SHA512 is bound to -// deliver much less improvement, likely *negative* on Cortex-A5x. -// Which is why NEON support is limited to SHA256.] - -// $output is the last argument if it looks like a file (it has an extension) -// $flavour is the first argument if it doesn't look like a file #ifndef __KERNEL__ # include "arm_arch.h" diff --git a/CryptoPkg/Library/OpensslLib/OpensslGen/AARCH64-GCC/crypto/sha/sha512-armv8.S b/CryptoPkg/Library/OpensslLib/OpensslGen/AARCH64-GCC/crypto/sha/sha512-armv8.S index 00269c027b3e..9c2cdfe79ef0 100644 --- a/CryptoPkg/Library/OpensslLib/OpensslGen/AARCH64-GCC/crypto/sha/sha512-armv8.S +++ b/CryptoPkg/Library/OpensslLib/OpensslGen/AARCH64-GCC/crypto/sha/sha512-armv8.S @@ -4,57 +4,6 @@ // this file except in compliance with the License. You can obtain a copy // in the file LICENSE in the source distribution or at // https://www.openssl.org/source/license.html - -// ==================================================================== -// Written by Andy Polyakov for the OpenSSL -// project. The module is, however, dual licensed under OpenSSL and -// CRYPTOGAMS licenses depending on where you obtain it. For further -// details see http://www.openssl.org/~appro/cryptogams/. -// -// Permission to use under GPLv2 terms is granted. -// ==================================================================== -// -// SHA256/512 for ARMv8. -// -// Performance in cycles per processed byte and improvement coefficient -// over code generated with "default" compiler: -// -// SHA256-hw SHA256(*) SHA512 -// Apple A7 1.97 10.5 (+33%) 6.73 (-1%(**)) -// Cortex-A53 2.38 15.5 (+115%) 10.0 (+150%(***)) -// Cortex-A57 2.31 11.6 (+86%) 7.51 (+260%(***)) -// Denver 2.01 10.5 (+26%) 6.70 (+8%) -// X-Gene 20.0 (+100%) 12.8 (+300%(***)) -// Mongoose 2.36 13.0 (+50%) 8.36 (+33%) -// Kryo 1.92 17.4 (+30%) 11.2 (+8%) -// ThunderX2 2.54 13.2 (+40%) 8.40 (+18%) -// -// (*) Software SHA256 results are of lesser relevance, presented -// mostly for informational purposes. -// (**) The result is a trade-off: it's possible to improve it by -// 10% (or by 1 cycle per round), but at the cost of 20% loss -// on Cortex-A53 (or by 4 cycles per round). -// (***) Super-impressive coefficients over gcc-generated code are -// indication of some compiler "pathology", most notably code -// generated with -mgeneral-regs-only is significantly faster -// and the gap is only 40-90%. -// -// October 2016. -// -// Originally it was reckoned that it makes no sense to implement NEON -// version of SHA256 for 64-bit processors. This is because performance -// improvement on most wide-spread Cortex-A5x processors was observed -// to be marginal, same on Cortex-A53 and ~10% on A57. But then it was -// observed that 32-bit NEON SHA256 performs significantly better than -// 64-bit scalar version on *some* of the more recent processors. As -// result 64-bit NEON version of SHA256 was added to provide best -// all-round performance. For example it executes ~30% faster on X-Gene -// and Mongoose. [For reference, NEON version of SHA512 is bound to -// deliver much less improvement, likely *negative* on Cortex-A5x. -// Which is why NEON support is limited to SHA256.] - -// $output is the last argument if it looks like a file (it has an extension) -// $flavour is the first argument if it doesn't look like a file #ifndef __KERNEL__ # include "arm_arch.h" diff --git a/CryptoPkg/Library/OpensslLib/OpensslGen/include/openssl/bio.h b/CryptoPkg/Library/OpensslLib/OpensslGen/include/openssl/bio.h index 43a6608c7c08..9021fd226825 100644 --- a/CryptoPkg/Library/OpensslLib/OpensslGen/include/openssl/bio.h +++ b/CryptoPkg/Library/OpensslLib/OpensslGen/include/openssl/bio.h @@ -867,7 +867,7 @@ int BIO_meth_set_puts(BIO_METHOD *biom, int (*puts) (BIO *, const char *)); int (*BIO_meth_get_gets(const BIO_METHOD *biom)) (BIO *, char *, int); int BIO_meth_set_gets(BIO_METHOD *biom, - int (*gets) (BIO *, char *, int)); + int (*ossl_gets) (BIO *, char *, int)); long (*BIO_meth_get_ctrl(const BIO_METHOD *biom)) (BIO *, int, long, void *); int BIO_meth_set_ctrl(BIO_METHOD *biom, long (*ctrl) (BIO *, int, long, void *)); diff --git a/CryptoPkg/Library/OpensslLib/OpensslGen/include/openssl/opensslv.h b/CryptoPkg/Library/OpensslLib/OpensslGen/include/openssl/opensslv.h index 9340a01afdac..efbc858cdd51 100644 --- a/CryptoPkg/Library/OpensslLib/OpensslGen/include/openssl/opensslv.h +++ b/CryptoPkg/Library/OpensslLib/OpensslGen/include/openssl/opensslv.h @@ -29,7 +29,7 @@ extern "C" { */ # define OPENSSL_VERSION_MAJOR 3 # define OPENSSL_VERSION_MINOR 0 -# define OPENSSL_VERSION_PATCH 9 +# define OPENSSL_VERSION_PATCH 15 /* * Additional version information @@ -74,21 +74,21 @@ extern "C" { * longer variant with OPENSSL_VERSION_PRE_RELEASE_STR and * OPENSSL_VERSION_BUILD_METADATA_STR appended. */ -# define OPENSSL_VERSION_STR "3.0.9" -# define OPENSSL_FULL_VERSION_STR "3.0.9" +# define OPENSSL_VERSION_STR "3.0.15" +# define OPENSSL_FULL_VERSION_STR "3.0.15" /* * SECTION 3: ADDITIONAL METADATA * * These strings are defined separately to allow them to be parsable. */ -# define OPENSSL_RELEASE_DATE "30 May 2023" +# define OPENSSL_RELEASE_DATE "3 Sep 2024" /* * SECTION 4: BACKWARD COMPATIBILITY */ -# define OPENSSL_VERSION_TEXT "OpenSSL 3.0.9 30 May 2023" +# define OPENSSL_VERSION_TEXT "OpenSSL 3.0.15 3 Sep 2024" /* Synthesize OPENSSL_VERSION_NUMBER with the layout 0xMNN00PPSL */ # ifdef OPENSSL_VERSION_PRE_RELEASE diff --git a/CryptoPkg/Library/OpensslLib/OpensslGen/include/openssl/pkcs7.h b/CryptoPkg/Library/OpensslLib/OpensslGen/include/openssl/pkcs7.h index 7b07d9cade73..497fcf379226 100644 --- a/CryptoPkg/Library/OpensslLib/OpensslGen/include/openssl/pkcs7.h +++ b/CryptoPkg/Library/OpensslLib/OpensslGen/include/openssl/pkcs7.h @@ -2,7 +2,7 @@ * WARNING: do not edit! * Generated by Makefile from include/openssl/pkcs7.h.in * - * Copyright 1995-2021 The OpenSSL Project Authors. All Rights Reserved. + * Copyright 1995-2023 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy @@ -56,8 +56,8 @@ typedef struct pkcs7_signer_info_st { PKCS7_ISSUER_AND_SERIAL *issuer_and_serial; X509_ALGOR *digest_alg; STACK_OF(X509_ATTRIBUTE) *auth_attr; /* [ 0 ] */ - X509_ALGOR *digest_enc_alg; - ASN1_OCTET_STRING *enc_digest; + X509_ALGOR *digest_enc_alg; /* confusing name, actually used for signing */ + ASN1_OCTET_STRING *enc_digest; /* confusing name, actually signature */ STACK_OF(X509_ATTRIBUTE) *unauth_attr; /* [ 1 ] */ /* The private key to sign with */ EVP_PKEY *pkey; diff --git a/CryptoPkg/Library/OpensslLib/OpensslLib.inf b/CryptoPkg/Library/OpensslLib/OpensslLib.inf index d499eb710232..ebdeae18c74c 100644 --- a/CryptoPkg/Library/OpensslLib/OpensslLib.inf +++ b/CryptoPkg/Library/OpensslLib/OpensslLib.inf @@ -29,7 +29,6 @@ [Sources] OpensslLibConstructor.c - $(OPENSSL_PATH)/e_os.h $(OPENSSL_PATH)/ms/uplink.h # Autogenerated files list starts here $(OPENSSL_PATH)/crypto/aes/aes_cbc.c @@ -739,8 +738,8 @@ # 1: ignore "#1-D: last line of file ends without a newline" # 3017: may be used before being set (NOTE: This was fixed in OpenSSL 1.1 HEAD with # commit d9b8b89bec4480de3a10bdaf9425db371c19145b, and can be dropped then.) - XCODE:*_*_IA32_CC_FLAGS = -mmmx -msse -U_WIN32 -U_WIN64 $(OPENSSL_FLAGS) $(OPENSSL_FLAGS_NOASM) -w -std=c99 -Wno-error=uninitialized - XCODE:*_*_X64_CC_FLAGS = -mmmx -msse -U_WIN32 -U_WIN64 $(OPENSSL_FLAGS) $(OPENSSL_FLAGS_NOASM) -w -std=c99 -Wno-error=uninitialized + XCODE:*_*_IA32_CC_FLAGS = -mmmx -msse -U_WIN32 -U_WIN64 $(OPENSSL_FLAGS) $(OPENSSL_FLAGS_NOASM) -w -std=c99 -Wno-error=uninitialized -DOPENSSL_NO_APPLE_CRYPTO_RANDOM + XCODE:*_*_X64_CC_FLAGS = -mmmx -msse -U_WIN32 -U_WIN64 $(OPENSSL_FLAGS) $(OPENSSL_FLAGS_NOASM) -w -std=c99 -Wno-error=uninitialized -DOPENSSL_NO_APPLE_CRYPTO_RANDOM # # AARCH64 uses strict alignment and avoids SIMD registers for code that may execute diff --git a/CryptoPkg/Library/OpensslLib/OpensslLibAccel.inf b/CryptoPkg/Library/OpensslLib/OpensslLibAccel.inf index dd07d0f72260..7ef206ec1695 100644 --- a/CryptoPkg/Library/OpensslLib/OpensslLibAccel.inf +++ b/CryptoPkg/Library/OpensslLib/OpensslLibAccel.inf @@ -33,7 +33,6 @@ [Sources] OpensslLibConstructor.c - $(OPENSSL_PATH)/e_os.h $(OPENSSL_PATH)/ms/uplink.h $(OPENSSL_PATH)/crypto/bn/bn_asm.c # Autogenerated files list starts here @@ -2027,8 +2026,8 @@ # 1: ignore "#1-D: last line of file ends without a newline" # 3017: may be used before being set (NOTE: This was fixed in OpenSSL 1.1 HEAD with # commit d9b8b89bec4480de3a10bdaf9425db371c19145b, and can be dropped then.) - XCODE:*_*_IA32_CC_FLAGS = -mmmx -msse -U_WIN32 -U_WIN64 $(OPENSSL_FLAGS) $(OPENSSL_FLAGS_IA32) -w -std=c99 -Wno-error=uninitialized - XCODE:*_*_X64_CC_FLAGS = -mmmx -msse -U_WIN32 -U_WIN64 $(OPENSSL_FLAGS) $(OPENSSL_FLAGS_X64) -w -std=c99 -Wno-error=uninitialized + XCODE:*_*_IA32_CC_FLAGS = -mmmx -msse -U_WIN32 -U_WIN64 $(OPENSSL_FLAGS) $(OPENSSL_FLAGS_IA32) -w -std=c99 -Wno-error=uninitialized -DOPENSSL_NO_APPLE_CRYPTO_RANDOM + XCODE:*_*_X64_CC_FLAGS = -mmmx -msse -U_WIN32 -U_WIN64 $(OPENSSL_FLAGS) $(OPENSSL_FLAGS_X64) -w -std=c99 -Wno-error=uninitialized -DOPENSSL_NO_APPLE_CRYPTO_RANDOM GCC:*_*_AARCH64_CC_FLAGS = $(OPENSSL_FLAGS) $(OPENSSL_FLAGS_AARCH64) -Wno-error=format -Wno-format -D_BITS_STDINT_UINTN_H -D_BITS_STDINT_INTN_H diff --git a/CryptoPkg/Library/OpensslLib/OpensslLibCrypto.inf b/CryptoPkg/Library/OpensslLib/OpensslLibCrypto.inf index d414988f7815..77ce80f2b81c 100644 --- a/CryptoPkg/Library/OpensslLib/OpensslLibCrypto.inf +++ b/CryptoPkg/Library/OpensslLib/OpensslLibCrypto.inf @@ -30,7 +30,6 @@ [Sources] OpensslLibConstructor.c - $(OPENSSL_PATH)/e_os.h $(OPENSSL_PATH)/ms/uplink.h # Autogenerated files list starts here $(OPENSSL_PATH)/crypto/aes/aes_cbc.c @@ -695,8 +694,8 @@ # 1: ignore "#1-D: last line of file ends without a newline" # 3017: may be used before being set (NOTE: This was fixed in OpenSSL 1.1 HEAD with # commit d9b8b89bec4480de3a10bdaf9425db371c19145b, and can be dropped then.) - XCODE:*_*_IA32_CC_FLAGS = -mmmx -msse -U_WIN32 -U_WIN64 $(OPENSSL_FLAGS) $(OPENSSL_FLAGS_NOASM) -w -std=c99 -Wno-error=uninitialized - XCODE:*_*_X64_CC_FLAGS = -mmmx -msse -U_WIN32 -U_WIN64 $(OPENSSL_FLAGS) $(OPENSSL_FLAGS_NOASM) -w -std=c99 -Wno-error=uninitialized + XCODE:*_*_IA32_CC_FLAGS = -mmmx -msse -U_WIN32 -U_WIN64 $(OPENSSL_FLAGS) $(OPENSSL_FLAGS_NOASM) -w -std=c99 -Wno-error=uninitialized -DOPENSSL_NO_APPLE_CRYPTO_RANDOM + XCODE:*_*_X64_CC_FLAGS = -mmmx -msse -U_WIN32 -U_WIN64 $(OPENSSL_FLAGS) $(OPENSSL_FLAGS_NOASM) -w -std=c99 -Wno-error=uninitialized -DOPENSSL_NO_APPLE_CRYPTO_RANDOM # # AARCH64 uses strict alignment and avoids SIMD registers for code that may execute diff --git a/CryptoPkg/Library/OpensslLib/OpensslLibFull.inf b/CryptoPkg/Library/OpensslLib/OpensslLibFull.inf index 55c634290484..32c79c39bb4f 100644 --- a/CryptoPkg/Library/OpensslLib/OpensslLibFull.inf +++ b/CryptoPkg/Library/OpensslLib/OpensslLibFull.inf @@ -34,7 +34,6 @@ [Sources] OpensslLibConstructor.c - $(OPENSSL_PATH)/e_os.h $(OPENSSL_PATH)/ms/uplink.h # Autogenerated files list starts here $(OPENSSL_PATH)/crypto/aes/aes_cbc.c @@ -793,8 +792,8 @@ # 1: ignore "#1-D: last line of file ends without a newline" # 3017: may be used before being set (NOTE: This was fixed in OpenSSL 1.1 HEAD with # commit d9b8b89bec4480de3a10bdaf9425db371c19145b, and can be dropped then.) - XCODE:*_*_IA32_CC_FLAGS = -mmmx -msse -U_WIN32 -U_WIN64 $(OPENSSL_FLAGS) $(OPENSSL_FLAGS_NOASM) -w -std=c99 -Wno-error=uninitialized - XCODE:*_*_X64_CC_FLAGS = -mmmx -msse -U_WIN32 -U_WIN64 $(OPENSSL_FLAGS) $(OPENSSL_FLAGS_NOASM) -w -std=c99 -Wno-error=uninitialized + XCODE:*_*_IA32_CC_FLAGS = -mmmx -msse -U_WIN32 -U_WIN64 $(OPENSSL_FLAGS) $(OPENSSL_FLAGS_NOASM) -w -std=c99 -Wno-error=uninitialized -DOPENSSL_NO_APPLE_CRYPTO_RANDOM + XCODE:*_*_X64_CC_FLAGS = -mmmx -msse -U_WIN32 -U_WIN64 $(OPENSSL_FLAGS) $(OPENSSL_FLAGS_NOASM) -w -std=c99 -Wno-error=uninitialized -DOPENSSL_NO_APPLE_CRYPTO_RANDOM # # AARCH64 uses strict alignment and avoids SIMD registers for code that may execute diff --git a/CryptoPkg/Library/OpensslLib/OpensslLibFullAccel.inf b/CryptoPkg/Library/OpensslLib/OpensslLibFullAccel.inf index b65ecf1e37cf..bbcf7485f15d 100644 --- a/CryptoPkg/Library/OpensslLib/OpensslLibFullAccel.inf +++ b/CryptoPkg/Library/OpensslLib/OpensslLibFullAccel.inf @@ -38,7 +38,6 @@ [Sources] OpensslLibConstructor.c - $(OPENSSL_PATH)/e_os.h $(OPENSSL_PATH)/ms/uplink.h $(OPENSSL_PATH)/crypto/bn/bn_asm.c # Autogenerated files list starts here @@ -2179,8 +2178,8 @@ # 1: ignore "#1-D: last line of file ends without a newline" # 3017: may be used before being set (NOTE: This was fixed in OpenSSL 1.1 HEAD with # commit d9b8b89bec4480de3a10bdaf9425db371c19145b, and can be dropped then.) - XCODE:*_*_IA32_CC_FLAGS = -mmmx -msse -U_WIN32 -U_WIN64 $(OPENSSL_FLAGS) $(OPENSSL_FLAGS_IA32) -w -std=c99 -Wno-error=uninitialized - XCODE:*_*_X64_CC_FLAGS = -mmmx -msse -U_WIN32 -U_WIN64 $(OPENSSL_FLAGS) $(OPENSSL_FLAGS_X64) -w -std=c99 -Wno-error=uninitialized + XCODE:*_*_IA32_CC_FLAGS = -mmmx -msse -U_WIN32 -U_WIN64 $(OPENSSL_FLAGS) $(OPENSSL_FLAGS_IA32) -w -std=c99 -Wno-error=uninitialized -DOPENSSL_NO_APPLE_CRYPTO_RANDOM + XCODE:*_*_X64_CC_FLAGS = -mmmx -msse -U_WIN32 -U_WIN64 $(OPENSSL_FLAGS) $(OPENSSL_FLAGS_X64) -w -std=c99 -Wno-error=uninitialized -DOPENSSL_NO_APPLE_CRYPTO_RANDOM GCC:*_*_AARCH64_CC_FLAGS = $(OPENSSL_FLAGS) $(OPENSSL_FLAGS_AARCH64) -Wno-error=format -Wno-format -D_BITS_STDINT_UINTN_H -D_BITS_STDINT_INTN_H diff --git a/CryptoPkg/Library/OpensslLib/OpensslLibSm3.inf b/CryptoPkg/Library/OpensslLib/OpensslLibSm3.inf new file mode 100644 index 000000000000..9e36490db73c --- /dev/null +++ b/CryptoPkg/Library/OpensslLib/OpensslLibSm3.inf @@ -0,0 +1,30 @@ +## @file +# Minimal OpensslLib implementation that only provides SM3 and nothing else. +# Needed by MbedTlsLib. +# +# Copyright (c) 2024, Google LLC. All rights reserved.
+# +# SPDX-License-Identifier: BSD-2-Clause-Patent +# +## + +[Defines] + INF_VERSION = 1.30 + BASE_NAME = OpensslLibSm3 + FILE_GUID = 96469bab-9c3f-4a60-a583-71a8bda64ec9 + MODULE_TYPE = BASE + VERSION_STRING = 1.0 + LIBRARY_CLASS = OpensslLib + + DEFINE OPENSSL_PATH = openssl + +[Sources] + $(OPENSSL_PATH)/crypto/sm3/sm3.c + OpensslStub/OpensslCleanse.c + +[Packages] + MdePkg/MdePkg.dec + CryptoPkg/CryptoPkg.dec + +[LibraryClasses] + BaseMemoryLib diff --git a/CryptoPkg/Library/OpensslLib/OpensslStub/OpensslCleanse.c b/CryptoPkg/Library/OpensslLib/OpensslStub/OpensslCleanse.c new file mode 100644 index 000000000000..21c939992dfd --- /dev/null +++ b/CryptoPkg/Library/OpensslLib/OpensslStub/OpensslCleanse.c @@ -0,0 +1,20 @@ +/** @file + Minimal implementation of OPENSSL_cleanse for OpensslLibSm3.inf. + + Copyright (c) 2024, Google LLC. All rights reserved.
+ + SPDX-License-Identifier: BSD-2-Clause-Patent + +**/ + +#include +#include + +VOID +OPENSSL_cleanse ( + VOID *Buffer, + UINTN Size + ) +{ + ZeroMem (Buffer, Size); +} diff --git a/CryptoPkg/Library/OpensslLib/openssl b/CryptoPkg/Library/OpensslLib/openssl index de90e54bbe82..c523121f902f 160000 --- a/CryptoPkg/Library/OpensslLib/openssl +++ b/CryptoPkg/Library/OpensslLib/openssl @@ -1 +1 @@ -Subproject commit de90e54bbe82e5be4fb9608b6f5c308bb837d355 +Subproject commit c523121f902fde2929909dc7f76b13ceb4961efe diff --git a/CryptoPkg/Test/UnitTest/Library/BaseCryptLib/HashTests.c b/CryptoPkg/Test/UnitTest/Library/BaseCryptLib/HashTests.c index dc5820227a0d..ab5c0d7b9ae8 100644 --- a/CryptoPkg/Test/UnitTest/Library/BaseCryptLib/HashTests.c +++ b/CryptoPkg/Test/UnitTest/Library/BaseCryptLib/HashTests.c @@ -62,6 +62,15 @@ GLOBAL_REMOVE_IF_UNREFERENCED CONST UINT8 Sha512Digest[SHA512_DIGEST_SIZE] = { 0x45, 0x4d, 0x44, 0x23, 0x64, 0x3c, 0xe8, 0x0e, 0x2a, 0x9a, 0xc9, 0x4f, 0xa5, 0x4c, 0xa4, 0x9f }; +// +// Result for SM3("abc"). (From "A.1 Example 1" of +// http://www.gmbz.org.cn/upload/2018-07-24/1532401392982079739.pdf) +// +GLOBAL_REMOVE_IF_UNREFERENCED CONST UINT8 Sm3Digest[SM3_256_DIGEST_SIZE] = { + 0x66, 0xc7, 0xf0, 0xf4, 0x62, 0xee, 0xed, 0xd9, 0xd1, 0xf2, 0xd4, 0x6b, 0xdc, 0x10, 0xe4, 0xe2, + 0x41, 0x67, 0xc4, 0x87, 0x5c, 0xf2, 0xf7, 0xa2, 0x29, 0x7d, 0xa0, 0x2b, 0x8f, 0x4b, 0xa8, 0xe0 +}; + typedef UINTN (EFIAPI *EFI_HASH_GET_CONTEXT_SIZE)( @@ -123,6 +132,7 @@ HASH_TEST_CONTEXT mSha1TestCtx = { SHA1_DIGEST_SIZE, Sha1GetContextSize, Sha1 HASH_TEST_CONTEXT mSha256TestCtx = { SHA256_DIGEST_SIZE, Sha256GetContextSize, Sha256Init, Sha256Update, Sha256Duplicate, Sha256Final, Sha256HashAll, Sha256Digest }; HASH_TEST_CONTEXT mSha384TestCtx = { SHA384_DIGEST_SIZE, Sha384GetContextSize, Sha384Init, Sha384Update, Sha384Duplicate, Sha384Final, Sha384HashAll, Sha384Digest }; HASH_TEST_CONTEXT mSha512TestCtx = { SHA512_DIGEST_SIZE, Sha512GetContextSize, Sha512Init, Sha512Update, Sha512Duplicate, Sha512Final, Sha512HashAll, Sha512Digest }; +HASH_TEST_CONTEXT mSm3TestCtx = { SM3_256_DIGEST_SIZE, Sm3GetContextSize, Sm3Init, Sm3Update, Sm3Duplicate, Sm3Final, Sm3HashAll, Sm3Digest }; UNIT_TEST_STATUS EFIAPI @@ -220,6 +230,7 @@ TEST_DESC mHashTest[] = { { "TestVerifySha256()", "CryptoPkg.BaseCryptLib.Hash", TestVerifyHash, TestVerifyHashPreReq, TestVerifyHashCleanUp, &mSha256TestCtx }, { "TestVerifySha384()", "CryptoPkg.BaseCryptLib.Hash", TestVerifyHash, TestVerifyHashPreReq, TestVerifyHashCleanUp, &mSha384TestCtx }, { "TestVerifySha512()", "CryptoPkg.BaseCryptLib.Hash", TestVerifyHash, TestVerifyHashPreReq, TestVerifyHashCleanUp, &mSha512TestCtx }, + { "TestVerifySm3()", "CryptoPkg.BaseCryptLib.Hash", TestVerifyHash, TestVerifyHashPreReq, TestVerifyHashCleanUp, &mSm3TestCtx }, }; UINTN mHashTestNum = ARRAY_SIZE (mHashTest); diff --git a/DynamicTablesPkg/DynamicTables.dsc.inc b/DynamicTablesPkg/DynamicTables.dsc.inc index c9bfa756c77a..99424b0d50dc 100644 --- a/DynamicTablesPkg/DynamicTables.dsc.inc +++ b/DynamicTablesPkg/DynamicTables.dsc.inc @@ -17,6 +17,7 @@ [LibraryClasses.common] AcpiHelperLib|DynamicTablesPkg/Library/Common/AcpiHelperLib/AcpiHelperLib.inf AmlLib|DynamicTablesPkg/Library/Common/AmlLib/AmlLib.inf + IpmiCommandLib|MdeModulePkg/Library/BaseIpmiCommandLibNull/BaseIpmiCommandLibNull.inf SsdtPcieSupportLib|DynamicTablesPkg/Library/Common/SsdtPcieSupportLib/SsdtPcieSupportLib.inf SsdtSerialPortFixupLib|DynamicTablesPkg/Library/Common/SsdtSerialPortFixupLib/SsdtSerialPortFixupLib.inf TableHelperLib|DynamicTablesPkg/Library/Common/TableHelperLib/TableHelperLib.inf @@ -38,6 +39,7 @@ DynamicTablesPkg/Library/Acpi/Common/AcpiSpcrLib/AcpiSpcrLib.inf DynamicTablesPkg/Library/Acpi/Common/AcpiSratLib/AcpiSratLib.inf DynamicTablesPkg/Library/Acpi/Common/AcpiTpm2Lib/AcpiTpm2Lib.inf + DynamicTablesPkg/Library/Acpi/Common/AcpiSpmiLib/AcpiSpmiLib.inf # AML Fixup (Common) DynamicTablesPkg/Library/Acpi/Common/AcpiSsdtSerialPortLib/SsdtSerialPortLib.inf @@ -67,6 +69,8 @@ # Generators # Common NULL|DynamicTablesPkg/Library/Acpi/Common/AcpiFadtLib/AcpiFadtLib.inf + NULL|DynamicTablesPkg/Library/Acpi/Common/AcpiSpmiLib/AcpiSpmiLib.inf + # X64 specific NULL|DynamicTablesPkg/Library/Acpi/X64/AcpiWsmtLib/AcpiWsmtLib.inf NULL|DynamicTablesPkg/Library/Acpi/X64/AcpiHpetLib/AcpiHpetLib.inf NULL|DynamicTablesPkg/Library/Acpi/X64/AcpiSsdtHpetLib/AcpiSsdtHpetLib.inf @@ -97,6 +101,7 @@ NULL|DynamicTablesPkg/Library/Acpi/Common/AcpiPpttLib/AcpiPpttLib.inf NULL|DynamicTablesPkg/Library/Acpi/Common/AcpiRawLib/AcpiRawLib.inf NULL|DynamicTablesPkg/Library/Acpi/Common/AcpiSpcrLib/AcpiSpcrLib.inf + NULL|DynamicTablesPkg/Library/Acpi/Common/AcpiSpmiLib/AcpiSpmiLib.inf NULL|DynamicTablesPkg/Library/Acpi/Common/AcpiSratLib/AcpiSratLib.inf NULL|DynamicTablesPkg/Library/Acpi/Common/AcpiTpm2Lib/AcpiTpm2Lib.inf # Arm specific diff --git a/DynamicTablesPkg/DynamicTablesPkg.ci.yaml b/DynamicTablesPkg/DynamicTablesPkg.ci.yaml index f7c8897fcbbe..5f2c6e8fb6e4 100644 --- a/DynamicTablesPkg/DynamicTablesPkg.ci.yaml +++ b/DynamicTablesPkg/DynamicTablesPkg.ci.yaml @@ -104,6 +104,7 @@ "CCIDX", "CCSIDR", "countof", + "deviceid", "EArch", "edynamic", "EOBJECT", diff --git a/DynamicTablesPkg/Include/AcpiTableGenerator.h b/DynamicTablesPkg/Include/AcpiTableGenerator.h old mode 100644 new mode 100755 index 69c012e67586..6387bf3f0aa0 --- a/DynamicTablesPkg/Include/AcpiTableGenerator.h +++ b/DynamicTablesPkg/Include/AcpiTableGenerator.h @@ -75,6 +75,9 @@ The Dynamic Tables Framework implements the following ACPI table generators: SSDT table describing a Pci Express bus. - WSMT : The WSMT generator collates the WSMT protection flag information from the Configuration Manager and builds the WSMT table. + - SPMI : The SPMI generator collects the SPMI interface and + optionally SPMI interrupt and deviceid (or uid) information from the + Configuration Manager and builds the SPMI table. */ /** The ACPI_TABLE_GENERATOR_ID type describes ACPI table generator ID. @@ -107,6 +110,7 @@ typedef enum StdAcpiTableId { EStdAcpiTableIdWsmt, ///< WSMT Generator EStdAcpiTableIdHpet, ///< HPET Generator EStdAcpiTableIdSsdtHpet, ///< SSDT HPET Generator + EStdAcpiTableIdSpmi, ///< SPMI Generator EStdAcpiTableIdMax } ESTD_ACPI_TABLE_ID; diff --git a/DynamicTablesPkg/Include/ArchCommonNameSpaceObjects.h b/DynamicTablesPkg/Include/ArchCommonNameSpaceObjects.h old mode 100644 new mode 100755 index 4b83e53b4d84..91514ee8dd2c --- a/DynamicTablesPkg/Include/ArchCommonNameSpaceObjects.h +++ b/DynamicTablesPkg/Include/ArchCommonNameSpaceObjects.h @@ -2,6 +2,7 @@ Copyright (c) 2024, Arm Limited. All rights reserved.
Copyright (c) 2024, NVIDIA CORPORATION & AFFILIATES. All rights reserved.
+ Copyright (c) 2024 Advanced Micro Devices, Inc. All rights reserved. SPDX-License-Identifier: BSD-2-Clause-Patent @@ -50,6 +51,8 @@ typedef enum ArchCommonObjectID { EArchCommonObjPccSubspaceType5Info, ///< 24 - Pcc Subspace Type 5 Info EArchCommonObjPsdInfo, ///< 25 - P-State Dependency (PSD) Info EArchCommonObjTpm2InterfaceInfo, ///< 26 - TPM Interface Info + EArchCommonObjSpmiInterfaceInfo, ///< 27 - SPMI Interface Info + EArchCommonObjSpmiInterruptDeviceInfo, ///< 28 - SPMI Interrupt and Device Info EArchCommonObjMax } EARCH_COMMON_OBJECT_ID; @@ -691,6 +694,40 @@ typedef struct CmArchCommonTpm2InterfaceInfo { UINT64 Lasa; } CM_ARCH_COMMON_TPM2_INTERFACE_INFO; +/** A structure that describes the + SPMI (Service Processor Management Interface) Info. + + ID: EArchCommonObjSpmiInterfaceInfo +*/ +typedef struct CmArchCommonObjSpmiInterfaceInfo { + /** Interface type */ + UINT8 InterfaceType; + + /** Base address */ + EFI_ACPI_6_5_GENERIC_ADDRESS_STRUCTURE BaseAddress; +} CM_ARCH_COMMON_SPMI_INTERFACE_INFO; + +/** A structure that describes the + SPMI (Service Processor Management Interface) Interrupt and Device Info. + + ID: EArchCommonObjSpmiInterruptDeviceInfo +*/ +typedef struct CmArchCommonObjSpmiInterruptDeviceInfo { + /** Interrupt type */ + UINT8 InterruptType; + + /** GPE number */ + UINT8 Gpe; + + /** PCI device flag */ + UINT8 PciDeviceFlag; + + /** GSI number */ + UINT32 GlobalSystemInterrupt; + + /** Uid of the device */ + UINT32 DeviceId; +} CM_ARCH_COMMON_SPMI_INTERRUPT_DEVICE_INFO; #pragma pack() #endif // ARCH_COMMON_NAMESPACE_OBJECTS_H_ diff --git a/DynamicTablesPkg/Library/Acpi/Common/AcpiFadtLib/FadtGenerator.c b/DynamicTablesPkg/Library/Acpi/Common/AcpiFadtLib/FadtGenerator.c index 3ba3fc230b6c..58ac02415719 100644 --- a/DynamicTablesPkg/Library/Acpi/Common/AcpiFadtLib/FadtGenerator.c +++ b/DynamicTablesPkg/Library/Acpi/Common/AcpiFadtLib/FadtGenerator.c @@ -2,6 +2,8 @@ FADT Table Generator Copyright (c) 2017 - 2023, Arm Limited. All rights reserved. + Copyright (C) 2024 Advanced Micro Devices, Inc. All rights reserved. + SPDX-License-Identifier: BSD-2-Clause-Patent @par Reference(s): @@ -66,6 +68,57 @@ EFI_ACPI_6_5_HW_REDUCED_ACPI | \ EFI_ACPI_6_5_LOW_POWER_S0_IDLE_CAPABLE) +/** This macro defines the valid mask for the FADT flag option + if HW_REDUCED_ACPI flag in the table is not set. + + Invalid bits are: Bit 20 and 22-31 (reserved). + + Valid bits are: + EFI_ACPI_6_5_WBINVD BIT0 + EFI_ACPI_6_5_WBINVD_FLUSH BIT1 + EFI_ACPI_6_5_PROC_C1 BIT2 + EFI_ACPI_6_5_P_LVL2_UP BIT3 + EFI_ACPI_6_5_PWR_BUTTON BIT4 + EFI_ACPI_6_5_SLP_BUTTON BIT5 + EFI_ACPI_6_5_FIX_RTC BIT6 + EFI_ACPI_6_5_RTC_S4 BIT7 + EFI_ACPI_6_5_TMR_VAL_EXT BIT8 + EFI_ACPI_6_5_DCK_CAP BIT9 + EFI_ACPI_6_5_RESET_REG_SUP BIT10 + EFI_ACPI_6_5_SEALED_CASE BIT11 + EFI_ACPI_6_5_HEADLESS BIT12 + EFI_ACPI_6_5_CPU_SW_SLP BIT13 + EFI_ACPI_6_5_PCI_EXP_WAK BIT14 + EFI_ACPI_6_5_USE_PLATFORM_CLOCK BIT15 + EFI_ACPI_6_5_S4_RTC_STS_VALID BIT16 + EFI_ACPI_6_5_REMOTE_POWER_ON_CAPABLE BIT17 + EFI_ACPI_6_5_FORCE_APIC_CLUSTER_MODEL BIT18 + EFI_ACPI_6_5_FORCE_APIC_PHYSICAL_DESTINATION_MODE BIT19 + EFI_ACPI_6_5_LOW_POWER_S0_IDLE_CAPABLE BIT21 +*/ +#define VALID_NON_HARDWARE_REDUCED_FLAG_MASK ( \ + EFI_ACPI_6_5_WBINVD | \ + EFI_ACPI_6_5_WBINVD_FLUSH | \ + EFI_ACPI_6_5_PROC_C1 | \ + EFI_ACPI_6_5_P_LVL2_UP | \ + EFI_ACPI_6_5_PWR_BUTTON | \ + EFI_ACPI_6_5_SLP_BUTTON | \ + EFI_ACPI_6_5_FIX_RTC | \ + EFI_ACPI_6_5_RTC_S4 | \ + EFI_ACPI_6_5_TMR_VAL_EXT | \ + EFI_ACPI_6_5_DCK_CAP | \ + EFI_ACPI_6_5_RESET_REG_SUP | \ + EFI_ACPI_6_5_SEALED_CASE | \ + EFI_ACPI_6_5_HEADLESS | \ + EFI_ACPI_6_5_CPU_SW_SLP | \ + EFI_ACPI_6_5_PCI_EXP_WAK | \ + EFI_ACPI_6_5_USE_PLATFORM_CLOCK | \ + EFI_ACPI_6_5_S4_RTC_STS_VALID | \ + EFI_ACPI_6_5_REMOTE_POWER_ON_CAPABLE | \ + EFI_ACPI_6_5_FORCE_APIC_CLUSTER_MODEL | \ + EFI_ACPI_6_5_FORCE_APIC_PHYSICAL_DESTINATION_MODE | \ + EFI_ACPI_6_5_LOW_POWER_S0_IDLE_CAPABLE) + #pragma pack(1) /** The AcpiFadt is a template EFI_ACPI_6_5_FIXED_ACPI_DESCRIPTION_TABLE @@ -391,17 +444,31 @@ FadtAddFixedFeatureFlags ( FixedFeatureFlags->Flags )); - if ((FixedFeatureFlags->Flags & ~(VALID_HARDWARE_REDUCED_FLAG_MASK)) != 0) { - DEBUG (( - DEBUG_WARN, - "FADT: Invalid Fixed feature flags defined by platform," - "Invalid Flags bits are = 0x%x\n", - (FixedFeatureFlags->Flags & ~(VALID_HARDWARE_REDUCED_FLAG_MASK)) - )); - } + if ((FixedFeatureFlags->Flags & EFI_ACPI_6_5_HW_REDUCED_ACPI) != 0) { + if ((FixedFeatureFlags->Flags & ~(VALID_HARDWARE_REDUCED_FLAG_MASK)) != 0) { + DEBUG (( + DEBUG_WARN, + "FADT: Invalid Fixed feature flags defined by platform," + "Invalid Flags bits are = 0x%x\n", + (FixedFeatureFlags->Flags & ~(VALID_HARDWARE_REDUCED_FLAG_MASK)) + )); + } + + AcpiFadt.Flags |= (FixedFeatureFlags->Flags & + VALID_HARDWARE_REDUCED_FLAG_MASK); + } else { + if ((FixedFeatureFlags->Flags & ~(VALID_NON_HARDWARE_REDUCED_FLAG_MASK)) != 0) { + DEBUG (( + DEBUG_WARN, + "FADT: Invalid Fixed feature flags defined for non-hardware reduced model," + "Invalid Flags bits are = 0x%x\n", + (FixedFeatureFlags->Flags & ~(VALID_NON_HARDWARE_REDUCED_FLAG_MASK)) + )); + } - AcpiFadt.Flags |= (FixedFeatureFlags->Flags & - VALID_HARDWARE_REDUCED_FLAG_MASK); + AcpiFadt.Flags |= (FixedFeatureFlags->Flags & + VALID_NON_HARDWARE_REDUCED_FLAG_MASK); + } error_handler: return Status; diff --git a/DynamicTablesPkg/Library/Acpi/Common/AcpiFadtLib/X64/X64FadtGenerator.c b/DynamicTablesPkg/Library/Acpi/Common/AcpiFadtLib/X64/X64FadtGenerator.c index 113894183de6..164f64559fcc 100644 --- a/DynamicTablesPkg/Library/Acpi/Common/AcpiFadtLib/X64/X64FadtGenerator.c +++ b/DynamicTablesPkg/Library/Acpi/Common/AcpiFadtLib/X64/X64FadtGenerator.c @@ -244,8 +244,8 @@ FadtArchUpdate ( )); } else { CopyMem ( - &Fadt->XPm1aCntBlk, - &XpmBlockInfo->XPm1aCntBlk, + &Fadt->XPm1aEvtBlk, + &XpmBlockInfo->XPm1aEvtBlk, sizeof (EFI_ACPI_6_5_GENERIC_ADDRESS_STRUCTURE) ); CopyMem ( diff --git a/DynamicTablesPkg/Library/Acpi/Common/AcpiSpmiLib/AcpiSpmiLib.inf b/DynamicTablesPkg/Library/Acpi/Common/AcpiSpmiLib/AcpiSpmiLib.inf new file mode 100755 index 000000000000..e6796dcb6fe7 --- /dev/null +++ b/DynamicTablesPkg/Library/Acpi/Common/AcpiSpmiLib/AcpiSpmiLib.inf @@ -0,0 +1,29 @@ +## @file +# SPMI Table Generator +# +# Copyright (C) 2024 Advanced Micro Devices, Inc. All rights reserved. +# +# SPDX-License-Identifier: BSD-2-Clause-Patent +## + +[Defines] + INF_VERSION = 1.30 + BASE_NAME = AcpiSpmiLib + FILE_GUID = 31307BFF-BA0E-42C3-BD73-6C482740120D + VERSION_STRING = 1.0 + MODULE_TYPE = DXE_DRIVER + LIBRARY_CLASS = NULL|DXE_DRIVER + CONSTRUCTOR = AcpiSpmiLibConstructor + DESTRUCTOR = AcpiSpmiLibDestructor + +[Sources] + SpmiGenerator.c + +[Packages] + MdePkg/MdePkg.dec + MdeModulePkg/MdeModulePkg.dec + DynamicTablesPkg/DynamicTablesPkg.dec + +[LibraryClasses] + BaseLib + IpmiCommandLib diff --git a/DynamicTablesPkg/Library/Acpi/Common/AcpiSpmiLib/SpmiGenerator.c b/DynamicTablesPkg/Library/Acpi/Common/AcpiSpmiLib/SpmiGenerator.c new file mode 100755 index 000000000000..af46bb6c1e8c --- /dev/null +++ b/DynamicTablesPkg/Library/Acpi/Common/AcpiSpmiLib/SpmiGenerator.c @@ -0,0 +1,390 @@ +/** @file + SPMI Table Generator + + Copyright (C) 2024 Advanced Micro Devices, Inc. All rights reserved. + SPDX-License-Identifier: BSD-2-Clause-Patent + + @par Reference(s): + - IPMI - Revision 2.0, April 21, 2015. + +**/ + +#include +#include +#include +#include + +// Module specific include files. +#include +#include +#include +#include +#include +#include +#include + +/** Standard SPMI Generator + +Requirements: + The following Configuration Manager Object(s) are required by + this Generator: + - EArchCommonObjSpmiInterfaceInfo + - EArchCommonObjSpmiInterruptDeviceInfo (OPTIONAL) +*/ + +/** Retrieve the SPMI interface information. */ +GET_OBJECT_LIST ( + EObjNameSpaceArchCommon, + EArchCommonObjSpmiInterfaceInfo, + CM_ARCH_COMMON_SPMI_INTERFACE_INFO + ); + +/** Retrieve the SPMI interrupt and device information. */ +GET_OBJECT_LIST ( + EObjNameSpaceArchCommon, + EArchCommonObjSpmiInterruptDeviceInfo, + CM_ARCH_COMMON_SPMI_INTERRUPT_DEVICE_INFO + ); + +STATIC +EFI_ACPI_SERVICE_PROCESSOR_MANAGEMENT_INTERFACE_TABLE AcpiSpmi = { + ACPI_HEADER ( + EFI_ACPI_6_5_SERVER_PLATFORM_MANAGEMENT_INTERFACE_TABLE_SIGNATURE, + EFI_ACPI_SERVICE_PROCESSOR_MANAGEMENT_INTERFACE_TABLE, + EFI_ACPI_SERVICE_PROCESSOR_MANAGEMENT_INTERFACE_5_TABLE_REVISION + ), + /// Interface Type + /// 0 - Reserved + /// 1 - KCS + /// 2 - SMIC + /// 3 - BT + /// 4 - SSIF + /// 5-255 - Reserved + 0x00, + /// Reserved1, must be 0x01 as per the IPMI specification. + 0x01, + /// Specification Revision + 0x0200, + /// Interrupt Type + 0x00, + /// GPE Number + 0x00, + /// Reserved2 + 0x00, + /// PCI device flag + 0x00, + /// Global System Interrupt + 0x00, + /// Base Address + { 0, 0,0, 0, 0 }, + /// Device ID + { + { 0x00 } + }, + /// Reserved3 + 0x00 +}; + +/** Construct the SPMI ACPI table. + + This function invokes the Configuration Manager protocol interface + to get the required hardware information for generating the ACPI + table. + + If this function allocates any resources then they must be freed + in the FreeXXXXTableResources function. + + @param [in] This Pointer to the table generator. + @param [in] AcpiTableInfo Pointer to the ACPI Table Info. + @param [in] CfgMgrProtocol Pointer to the Configuration Manager + Protocol Interface. + @param [out] Table Pointer to the constructed ACPI Table. + + @retval EFI_SUCCESS Table generated successfully. + @retval EFI_INVALID_PARAMETER A parameter is invalid. + @retval EFI_NOT_FOUND The required object was not found. + @retval EFI_BAD_BUFFER_SIZE The size returned by the Configuration + Manager is less than the Object size for the + requested object. +**/ +STATIC +EFI_STATUS +EFIAPI +BuildSpmiTable ( + IN CONST ACPI_TABLE_GENERATOR *CONST This, + IN CONST CM_STD_OBJ_ACPI_TABLE_INFO *CONST AcpiTableInfo, + IN CONST EDKII_CONFIGURATION_MANAGER_PROTOCOL *CONST CfgMgrProtocol, + OUT EFI_ACPI_DESCRIPTION_HEADER **CONST Table + ) +{ + EFI_STATUS Status; + CM_ARCH_COMMON_SPMI_INTERFACE_INFO *SpmiInfo; + CM_ARCH_COMMON_SPMI_INTERRUPT_DEVICE_INFO *SpmiIntrDeviceInfo; + IPMI_GET_DEVICE_ID_RESPONSE DeviceId; + + ASSERT (This != NULL); + ASSERT (AcpiTableInfo != NULL); + ASSERT (CfgMgrProtocol != NULL); + ASSERT (Table != NULL); + ASSERT (AcpiTableInfo->TableGeneratorId == This->GeneratorID); + ASSERT (AcpiTableInfo->AcpiTableSignature == This->AcpiTableSignature); + + if ((AcpiTableInfo->AcpiTableRevision < This->MinAcpiTableRevision) || + (AcpiTableInfo->AcpiTableRevision > This->AcpiTableRevision)) + { + DEBUG (( + DEBUG_ERROR, + "ERROR: SPMI: Requested table revision = %d, is not supported." + "Supported table revision: Minimum = %d, Maximum = %d\n", + AcpiTableInfo->AcpiTableRevision, + This->MinAcpiTableRevision, + This->AcpiTableRevision + )); + return EFI_INVALID_PARAMETER; + } + + *Table = NULL; + + Status = GetEArchCommonObjSpmiInterfaceInfo ( + CfgMgrProtocol, + CM_NULL_TOKEN, + &SpmiInfo, + NULL + ); + if (EFI_ERROR (Status)) { + DEBUG (( + DEBUG_ERROR, + "ERROR: SPMI: Failed to retrieve interface type and base address.\n" + )); + return Status; + } + + /// Validate interface type. + if ((SpmiInfo->InterfaceType < EFI_ACPI_SPMI_INTERFACE_TYPE_KCS) || + (SpmiInfo->InterfaceType > EFI_ACPI_SPMI_INTERFACE_TYPE_SSIF)) + { + DEBUG (( + DEBUG_ERROR, + "ERROR: SPMI: The Interface Type is invalid. Type = %d\n", + SpmiInfo->InterfaceType + )); + return EFI_INVALID_PARAMETER; + } + + /// If the interface type is SSIF, the Address Space ID should be SMBUS. + if ((SpmiInfo->InterfaceType == EFI_ACPI_SPMI_INTERFACE_TYPE_SSIF) && + (SpmiInfo->BaseAddress.AddressSpaceId != EFI_ACPI_6_5_SMBUS)) + { + DEBUG (( + DEBUG_ERROR, + "ERROR: SPMI: Invalid Address Space ID for SSIF. ID = %d\n", + SpmiInfo->BaseAddress.AddressSpaceId + )); + return EFI_INVALID_PARAMETER; + } + + /// For non-ssif interface types, the Address Space ID should be System Memory or System I/O. + if ((SpmiInfo->InterfaceType != EFI_ACPI_SPMI_INTERFACE_TYPE_SSIF) && + ((SpmiInfo->BaseAddress.AddressSpaceId != EFI_ACPI_6_5_SYSTEM_MEMORY) && + (SpmiInfo->BaseAddress.AddressSpaceId != EFI_ACPI_6_5_SYSTEM_IO))) + { + DEBUG (( + DEBUG_ERROR, + "ERROR: SPMI: Invalid Address Space ID. ID = %d\n", + SpmiInfo->BaseAddress.AddressSpaceId + )); + return EFI_INVALID_PARAMETER; + } + + Status = GetEArchCommonObjSpmiInterruptDeviceInfo ( + CfgMgrProtocol, + CM_NULL_TOKEN, + &SpmiIntrDeviceInfo, + NULL + ); + if (!EFI_ERROR (Status)) { + /// Validate Interrupt Type, bit[7:2] should be zero. + if ((SpmiIntrDeviceInfo->InterruptType >> 2) != 0 ) { + DEBUG (( + DEBUG_ERROR, + "ERROR: SPMI: The Interrupt Type has non-zero reserved bits. InterruptType = 0x%x\n", + SpmiIntrDeviceInfo->InterruptType + )); + return EFI_INVALID_PARAMETER; + } + + if (SpmiInfo->InterfaceType == EFI_ACPI_SPMI_INTERFACE_TYPE_SSIF) { + /// Interrupt Type bit[0] should be zero for SSIF interface type. + if ((SpmiIntrDeviceInfo->InterruptType & BIT0) != 0) { + DEBUG (( + DEBUG_ERROR, + "ERROR: SPMI: The Interrupt Type bit0 should be zero for SSIF interface type.\n" + )); + return EFI_INVALID_PARAMETER; + } + + /// PCI device flag bit0 should be zero for SSIF interface type. + if ((SpmiIntrDeviceInfo->PciDeviceFlag & BIT0) != 0) { + DEBUG (( + DEBUG_ERROR, + "ERROR: SPMI: PCI Device Flag is invalid for SSIF interface type.\n" + )); + return EFI_INVALID_PARAMETER; + } + } + + /// Validate SCI GPE bit if GPE number is provided. + if ((SpmiIntrDeviceInfo->Gpe != 0) && + ((SpmiIntrDeviceInfo->InterruptType & BIT0) == 0)) + { + DEBUG (( + DEBUG_ERROR, + "ERROR: SPMI: The Interrupt Type bit0 should be set if a GPE number is provided.\n" + )); + return EFI_INVALID_PARAMETER; + } + + /// If GlobalSystemInterrupt is provided, the interrupt type should be GSI. + if ((SpmiIntrDeviceInfo->GlobalSystemInterrupt != 0) && + ((SpmiIntrDeviceInfo->InterruptType & BIT1) == 0)) + { + DEBUG (( + DEBUG_ERROR, + "ERROR: SPMI: Invalid interrupt type = 0x%x for GSI 0x%x\n", + SpmiIntrDeviceInfo->InterruptType, + SpmiIntrDeviceInfo->GlobalSystemInterrupt + )); + return EFI_INVALID_PARAMETER; + } + + AcpiSpmi.InterruptType = SpmiIntrDeviceInfo->InterruptType; + AcpiSpmi.Gpe = SpmiIntrDeviceInfo->Gpe; + AcpiSpmi.PciDeviceFlag = SpmiIntrDeviceInfo->PciDeviceFlag; + AcpiSpmi.GlobalSystemInterrupt = SpmiIntrDeviceInfo->GlobalSystemInterrupt; + AcpiSpmi.DeviceId.Uid = SpmiIntrDeviceInfo->DeviceId; + } else { + DEBUG (( + DEBUG_INFO, + "INFO: SPMI: The platform does not provide interrupt and PCI device information.\n" + )); + DEBUG (( + DEBUG_INFO, + "Using default values (0) for the interrupt and PCI device information.\n" + )); + } + + /// Update IPMI specification version + Status = IpmiGetDeviceId (&DeviceId); + if (!EFI_ERROR (Status) && (DeviceId.CompletionCode == IPMI_COMP_CODE_NORMAL)) { + AcpiSpmi.SpecificationRevision = DeviceId.SpecificationVersion & 0xF0; + AcpiSpmi.SpecificationRevision |= (DeviceId.SpecificationVersion & 0xF) << 8; + } + + AcpiSpmi.InterfaceType = SpmiInfo->InterfaceType; + CopyMem ( + &AcpiSpmi.BaseAddress, + &SpmiInfo->BaseAddress, + sizeof (EFI_ACPI_6_5_GENERIC_ADDRESS_STRUCTURE) + ); + + Status = AddAcpiHeader ( + CfgMgrProtocol, + This, + (EFI_ACPI_DESCRIPTION_HEADER *)&AcpiSpmi, + AcpiTableInfo, + sizeof (EFI_ACPI_SERVICE_PROCESSOR_MANAGEMENT_INTERFACE_TABLE) + ); + if (EFI_ERROR (Status)) { + DEBUG (( + DEBUG_ERROR, + "ERROR: SPMI: Failed to add ACPI header. Status = %r\n", + Status + )); + } + + *Table = (EFI_ACPI_DESCRIPTION_HEADER *)&AcpiSpmi; + return Status; +} + +/** This macro defines the SPMI Table Generator revision. +*/ +#define SPMI_GENERATOR_REVISION CREATE_REVISION (1, 0) + +/** The interface for the SPMI Table Generator. +*/ +STATIC +CONST +ACPI_TABLE_GENERATOR SpmiGenerator = { + // Generator ID + CREATE_STD_ACPI_TABLE_GEN_ID (EStdAcpiTableIdSpmi), + // Generator Description + L"ACPI.STD.SPMI.GENERATOR", + // ACPI Table Signature + EFI_ACPI_6_5_SERVER_PLATFORM_MANAGEMENT_INTERFACE_TABLE_SIGNATURE, + // ACPI Table Revision supported by this Generator + EFI_ACPI_SERVICE_PROCESSOR_MANAGEMENT_INTERFACE_5_TABLE_REVISION, + // Minimum supported ACPI Table Revision + EFI_ACPI_SERVICE_PROCESSOR_MANAGEMENT_INTERFACE_5_TABLE_REVISION, + // Creator ID + TABLE_GENERATOR_CREATOR_ID, + // Creator Revision + SPMI_GENERATOR_REVISION, + // Build Table function + BuildSpmiTable, + // Free Resource function + NULL, + // Extended build function not needed + NULL, + // Extended build function not implemented by the generator. + // Hence extended free resource function is not required. + NULL +}; + +/** Register the Generator with the ACPI Table Factory. + + @param [in] ImageHandle The handle to the image. + @param [in] SystemTable Pointer to the System Table. + + @retval EFI_SUCCESS The Generator is registered. + @retval EFI_INVALID_PARAMETER A parameter is invalid. + @retval EFI_ALREADY_STARTED The Generator for the Table ID + is already registered. +**/ +EFI_STATUS +EFIAPI +AcpiSpmiLibConstructor ( + IN EFI_HANDLE ImageHandle, + IN EFI_SYSTEM_TABLE *SystemTable + ) +{ + EFI_STATUS Status; + + Status = RegisterAcpiTableGenerator (&SpmiGenerator); + DEBUG ((DEBUG_INFO, "SPMI: Register Generator. Status = %r\n", Status)); + ASSERT_EFI_ERROR (Status); + return Status; +} + +/** Deregister the Generator from the ACPI Table Factory. + + @param [in] ImageHandle The handle to the image. + @param [in] SystemTable Pointer to the System Table. + + @retval EFI_SUCCESS The Generator is deregistered. + @retval EFI_INVALID_PARAMETER A parameter is invalid. + @retval EFI_NOT_FOUND The Generator is not registered. +**/ +EFI_STATUS +EFIAPI +AcpiSpmiLibDestructor ( + IN EFI_HANDLE ImageHandle, + IN EFI_SYSTEM_TABLE *SystemTable + ) +{ + EFI_STATUS Status; + + Status = DeregisterAcpiTableGenerator (&SpmiGenerator); + DEBUG ((DEBUG_INFO, "SPMI: Deregister Generator. Status = %r\n", Status)); + ASSERT_EFI_ERROR (Status); + return Status; +} diff --git a/DynamicTablesPkg/Library/Acpi/X64/AcpiWsmtLib/WsmtGenerator.c b/DynamicTablesPkg/Library/Acpi/X64/AcpiWsmtLib/WsmtGenerator.c index 97622948f593..d6e3be5f3d49 100644 --- a/DynamicTablesPkg/Library/Acpi/X64/AcpiWsmtLib/WsmtGenerator.c +++ b/DynamicTablesPkg/Library/Acpi/X64/AcpiWsmtLib/WsmtGenerator.c @@ -223,7 +223,7 @@ ACPI_TABLE_GENERATOR WsmtGenerator = { // Minimum supported ACPI Table Revision EFI_WSMT_TABLE_REVISION, // Creator ID - TABLE_GENERATOR_CREATOR_ID_ARM, + TABLE_GENERATOR_CREATOR_ID, // Creator Revision WSMT_GENERATOR_REVISION, // Build Table function diff --git a/DynamicTablesPkg/Library/Common/AmlLib/AmlEncoding/Aml.c b/DynamicTablesPkg/Library/Common/AmlLib/AmlEncoding/Aml.c index e46dc6c1f1c8..c67066d28eab 100644 --- a/DynamicTablesPkg/Library/Common/AmlLib/AmlEncoding/Aml.c +++ b/DynamicTablesPkg/Library/Common/AmlLib/AmlEncoding/Aml.c @@ -774,7 +774,7 @@ AmlSetPkgLength ( // Write to the Buffer. *Buffer = LeadByte; CurrentOffset = 1; - while (CurrentOffset < (Offset + 1)) { + while (CurrentOffset < (Offset + (UINT8)1)) { CurrentShift = (UINT8)((CurrentOffset - 1) * 8); ComputedLength = Length & (UINT32)(0x00000FF0 << CurrentShift); ComputedLength = (ComputedLength) >> (4 + CurrentShift); diff --git a/DynamicTablesPkg/Library/Common/AmlLib/CodeGen/AmlCodeGen.c b/DynamicTablesPkg/Library/Common/AmlLib/CodeGen/AmlCodeGen.c index 35ec2aaa6703..0f28e27c9449 100644 --- a/DynamicTablesPkg/Library/Common/AmlLib/CodeGen/AmlCodeGen.c +++ b/DynamicTablesPkg/Library/Common/AmlLib/CodeGen/AmlCodeGen.c @@ -4183,11 +4183,13 @@ AmlCodeGenInvokeMethod ( Creates and optionally adds the following node Name(_PSD, Package() { - NumEntries, // Integer - Revision, // Integer - Domain, // Integer - CoordType, // Integer - NumProc, // Integer + Package () { + NumEntries, // Integer + Revision, // Integer + Domain, // Integer + CoordType, // Integer + NumProc, // Integer + } }) Cf. ACPI 6.5, s8.4.5.5 _PSD (P-State Dependency) @@ -4213,10 +4215,14 @@ AmlCreatePsdNode ( { EFI_STATUS Status; AML_OBJECT_NODE_HANDLE PsdNode; + AML_OBJECT_NODE_HANDLE PsdParentPackage; AML_OBJECT_NODE_HANDLE PsdPackage; AML_OBJECT_NODE_HANDLE IntegerNode; UINT32 NumberOfEntries; + PsdParentPackage = NULL; + PsdPackage = NULL; + if ((PsdInfo == NULL) || ((ParentNode == NULL) && (NewPsdNode == NULL))) { @@ -4253,19 +4259,25 @@ AmlCreatePsdNode ( // Get the Package object node of the _PSD node, // which is the 2nd fixed argument (i.e. index 1). - PsdPackage = (AML_OBJECT_NODE_HANDLE)AmlGetFixedArgument ( - PsdNode, - EAmlParseIndexTerm1 - ); - if ((PsdPackage == NULL) || - (AmlGetNodeType ((AML_NODE_HANDLE)PsdPackage) != EAmlNodeObject) || - (!AmlNodeHasOpCode (PsdPackage, AML_PACKAGE_OP, 0))) + PsdParentPackage = (AML_OBJECT_NODE_HANDLE)AmlGetFixedArgument ( + PsdNode, + EAmlParseIndexTerm1 + ); + if ((PsdParentPackage == NULL) || + (AmlGetNodeType ((AML_NODE_HANDLE)PsdParentPackage) != EAmlNodeObject) || + (!AmlNodeHasOpCode (PsdParentPackage, AML_PACKAGE_OP, 0))) { Status = EFI_INVALID_PARAMETER; ASSERT_EFI_ERROR (Status); goto error_handler; } + Status = AmlCodeGenPackage (&PsdPackage); + if (EFI_ERROR (Status)) { + ASSERT_EFI_ERROR (Status); + goto error_handler; + } + // NumEntries Status = AmlCodeGenInteger (NumberOfEntries, &IntegerNode); if (EFI_ERROR (Status)) { @@ -4351,6 +4363,17 @@ AmlCreatePsdNode ( goto error_handler; } + Status = AmlVarListAddTail ( + (AML_NODE_HANDLE)PsdParentPackage, + (AML_NODE_HANDLE)PsdPackage + ); + if (EFI_ERROR (Status)) { + ASSERT_EFI_ERROR (Status); + goto error_handler; + } + + PsdPackage = NULL; // Prevent double free if error occurs after this point + Status = LinkNode (PsdNode, ParentNode, NewPsdNode); if (EFI_ERROR (Status)) { ASSERT_EFI_ERROR (Status); @@ -4360,6 +4383,13 @@ AmlCreatePsdNode ( return Status; error_handler: - AmlDeleteTree ((AML_NODE_HANDLE)PsdNode); + if (PsdPackage != NULL) { + AmlDeleteTree ((AML_NODE_HANDLE)PsdPackage); + } + + if (PsdParentPackage != NULL) { + AmlDeleteTree ((AML_NODE_HANDLE)PsdParentPackage); + } + return Status; } diff --git a/DynamicTablesPkg/Library/Common/AmlLib/CodeGen/AmlResourceDataCodeGen.c b/DynamicTablesPkg/Library/Common/AmlLib/CodeGen/AmlResourceDataCodeGen.c index 3db536dddf49..bf0d7b0ccaa3 100644 --- a/DynamicTablesPkg/Library/Common/AmlLib/CodeGen/AmlResourceDataCodeGen.c +++ b/DynamicTablesPkg/Library/Common/AmlLib/CodeGen/AmlResourceDataCodeGen.c @@ -1437,9 +1437,7 @@ AmlCodeGenRdRegister ( // Cf. ACPI 6.4, s14.7 Referencing the PCC address space // The AccessSize represents the Subspace Id for the PCC address space. - if (((AddressSpace == EFI_ACPI_6_4_PLATFORM_COMMUNICATION_CHANNEL) && - (AccessSize > 256)) || - ((AddressSpace != EFI_ACPI_6_4_PLATFORM_COMMUNICATION_CHANNEL) && + if (((AddressSpace != EFI_ACPI_6_4_PLATFORM_COMMUNICATION_CHANNEL) && (AccessSize > EFI_ACPI_6_4_QWORD)) || ((NameOpNode == NULL) && (NewRdNode == NULL))) { diff --git a/DynamicTablesPkg/Library/Common/TableHelperLib/ConfigurationManagerObjectParser.c b/DynamicTablesPkg/Library/Common/TableHelperLib/ConfigurationManagerObjectParser.c old mode 100644 new mode 100755 index 0f74f3d6b9a4..6dc48abb8134 --- a/DynamicTablesPkg/Library/Common/TableHelperLib/ConfigurationManagerObjectParser.c +++ b/DynamicTablesPkg/Library/Common/TableHelperLib/ConfigurationManagerObjectParser.c @@ -677,6 +677,24 @@ STATIC CONST CM_OBJ_PARSER CmArchCommonTpm2InterfaceInfo[] = { { "Lasa", sizeof (UINT64), "0x%llx", NULL }, }; +/** A parser for EArchCommonObjSpmiInfo. +*/ +STATIC CONST CM_OBJ_PARSER CmArchCommonSpmiInterfaceInfoParser[] = { + { "InterfaceType", sizeof (UINT8), "0x%x", NULL }, + { "BaseAddress", sizeof (EFI_ACPI_6_5_GENERIC_ADDRESS_STRUCTURE), + NULL, NULL, AcpiGenericAddressParser } +}; + +/** A parser for EArchCommonObjSpmiInterruptDeviceInfo. +*/ +STATIC CONST CM_OBJ_PARSER CmArchCommonSpmiInterruptDeviceInfoParser[] = { + { "InterruptType", sizeof (UINT8), "0x%x", NULL }, + { "GPE", sizeof (UINT8), "0x%x", NULL }, + { "PciDeviceFlag", sizeof (UINT8), "0x%x", NULL }, + { "GlobalSystemInterrupt", sizeof (UINT32), "0x%x", NULL }, + { "DeviceId", sizeof (UINT32), "0x%x", NULL } +}; + /** A parser for Arch Common namespace objects. */ STATIC CONST CM_OBJ_PARSER_ARRAY ArchCommonNamespaceObjectParser[] = { @@ -707,6 +725,8 @@ STATIC CONST CM_OBJ_PARSER_ARRAY ArchCommonNamespaceObjectParser[] = { CM_PARSER_ADD_OBJECT (EArchCommonObjPccSubspaceType5Info, CmArchCommonPccSubspaceType5InfoParser), CM_PARSER_ADD_OBJECT (EArchCommonObjPsdInfo, CmArchCommonPsdInfoParser), CM_PARSER_ADD_OBJECT (EArchCommonObjTpm2InterfaceInfo, CmArchCommonTpm2InterfaceInfo), + CM_PARSER_ADD_OBJECT (EArchCommonObjSpmiInterfaceInfo, CmArchCommonSpmiInterfaceInfoParser), + CM_PARSER_ADD_OBJECT (EArchCommonObjSpmiInterruptDeviceInfo, CmArchCommonSpmiInterruptDeviceInfoParser), CM_PARSER_ADD_OBJECT_RESERVED (EArchCommonObjMax) }; diff --git a/DynamicTablesPkg/Library/FdtHwInfoParserLib/Arm/BootArch/ArmBootArchParser.c b/DynamicTablesPkg/Library/FdtHwInfoParserLib/Arm/BootArch/ArmBootArchParser.c index d217e33424b1..b5c42d88fcb8 100644 --- a/DynamicTablesPkg/Library/FdtHwInfoParserLib/Arm/BootArch/ArmBootArchParser.c +++ b/DynamicTablesPkg/Library/FdtHwInfoParserLib/Arm/BootArch/ArmBootArchParser.c @@ -8,6 +8,8 @@ - linux/Documentation/devicetree/bindings/arm/psci.yaml **/ +#include +#include #include "FdtHwInfoParser.h" #include "CmObjectDescUtility.h" #include "Arm/BootArch/ArmBootArchParser.h" diff --git a/DynamicTablesPkg/Library/FdtHwInfoParserLib/Arm/GenericTimer/ArmGenericTimerParser.c b/DynamicTablesPkg/Library/FdtHwInfoParserLib/Arm/GenericTimer/ArmGenericTimerParser.c index 6488399ed812..c79ad9213ae9 100644 --- a/DynamicTablesPkg/Library/FdtHwInfoParserLib/Arm/GenericTimer/ArmGenericTimerParser.c +++ b/DynamicTablesPkg/Library/FdtHwInfoParserLib/Arm/GenericTimer/ArmGenericTimerParser.c @@ -8,6 +8,7 @@ - linux/Documentation/devicetree/bindings/timer/arm,arch_timer.yaml **/ +#include #include "FdtHwInfoParser.h" #include "CmObjectDescUtility.h" #include "Arm/GenericTimer/ArmGenericTimerParser.h" diff --git a/DynamicTablesPkg/Library/FdtHwInfoParserLib/Arm/Gic/ArmGicDParser.c b/DynamicTablesPkg/Library/FdtHwInfoParserLib/Arm/Gic/ArmGicDParser.c index 906ef8b8585e..d59219f375a3 100644 --- a/DynamicTablesPkg/Library/FdtHwInfoParserLib/Arm/Gic/ArmGicDParser.c +++ b/DynamicTablesPkg/Library/FdtHwInfoParserLib/Arm/Gic/ArmGicDParser.c @@ -9,6 +9,7 @@ - linux/Documentation/devicetree/bindings/interrupt-controller/arm,gic-v3.yaml **/ +#include #include "CmObjectDescUtility.h" #include "FdtHwInfoParser.h" #include "Arm/Gic/ArmGicDispatcher.h" diff --git a/DynamicTablesPkg/Library/FdtHwInfoParserLib/Arm/Gic/ArmGicItsParser.c b/DynamicTablesPkg/Library/FdtHwInfoParserLib/Arm/Gic/ArmGicItsParser.c index 6d4bde6a141a..253c22105e12 100644 --- a/DynamicTablesPkg/Library/FdtHwInfoParserLib/Arm/Gic/ArmGicItsParser.c +++ b/DynamicTablesPkg/Library/FdtHwInfoParserLib/Arm/Gic/ArmGicItsParser.c @@ -8,6 +8,7 @@ - linux/Documentation/devicetree/bindings/interrupt-controller/arm,gic-v3.yaml **/ +#include #include "CmObjectDescUtility.h" #include "FdtHwInfoParser.h" #include "Arm/Gic/ArmGicDispatcher.h" diff --git a/DynamicTablesPkg/Library/FdtHwInfoParserLib/Arm/Gic/ArmGicMsiFrameParser.c b/DynamicTablesPkg/Library/FdtHwInfoParserLib/Arm/Gic/ArmGicMsiFrameParser.c index dff5beff91be..daadcec4e0d1 100644 --- a/DynamicTablesPkg/Library/FdtHwInfoParserLib/Arm/Gic/ArmGicMsiFrameParser.c +++ b/DynamicTablesPkg/Library/FdtHwInfoParserLib/Arm/Gic/ArmGicMsiFrameParser.c @@ -9,6 +9,7 @@ - linux/Documentation/devicetree/bindings/interrupt-controller/arm,gic-v3.yaml **/ +#include #include "CmObjectDescUtility.h" #include "FdtHwInfoParser.h" #include "Arm/Gic/ArmGicDispatcher.h" diff --git a/DynamicTablesPkg/Library/FdtHwInfoParserLib/Arm/Gic/ArmGicRParser.c b/DynamicTablesPkg/Library/FdtHwInfoParserLib/Arm/Gic/ArmGicRParser.c index de2e1dd1f1e3..1c5bc97d9836 100644 --- a/DynamicTablesPkg/Library/FdtHwInfoParserLib/Arm/Gic/ArmGicRParser.c +++ b/DynamicTablesPkg/Library/FdtHwInfoParserLib/Arm/Gic/ArmGicRParser.c @@ -8,6 +8,7 @@ - linux/Documentation/devicetree/bindings/interrupt-controller/arm,gic-v3.yaml **/ +#include #include "CmObjectDescUtility.h" #include "FdtHwInfoParser.h" #include "Arm/Gic/ArmGicDispatcher.h" diff --git a/DynamicTablesPkg/Library/FdtHwInfoParserLib/FdtHwInfoParserLib.inf b/DynamicTablesPkg/Library/FdtHwInfoParserLib/FdtHwInfoParserLib.inf index c8511ab4dd82..41d12443d43f 100644 --- a/DynamicTablesPkg/Library/FdtHwInfoParserLib/FdtHwInfoParserLib.inf +++ b/DynamicTablesPkg/Library/FdtHwInfoParserLib/FdtHwInfoParserLib.inf @@ -57,6 +57,8 @@ MdePkg/MdePkg.dec [LibraryClasses] + BaseLib + BaseMemoryLib DebugLib FdtLib MemoryAllocationLib diff --git a/DynamicTablesPkg/Library/FdtHwInfoParserLib/FdtUtility.c b/DynamicTablesPkg/Library/FdtHwInfoParserLib/FdtUtility.c index bab228575938..9d8bd3e7fb8c 100644 --- a/DynamicTablesPkg/Library/FdtHwInfoParserLib/FdtUtility.c +++ b/DynamicTablesPkg/Library/FdtHwInfoParserLib/FdtUtility.c @@ -10,6 +10,7 @@ - linux//Documentation/devicetree/bindings/interrupt-controller/arm%2Cgic.yaml **/ +#include #include #include "FdtUtility.h" diff --git a/DynamicTablesPkg/Library/FdtHwInfoParserLib/Pci/PciConfigSpaceParser.c b/DynamicTablesPkg/Library/FdtHwInfoParserLib/Pci/PciConfigSpaceParser.c index 7f536c0ac63e..466538ebc8e0 100644 --- a/DynamicTablesPkg/Library/FdtHwInfoParserLib/Pci/PciConfigSpaceParser.c +++ b/DynamicTablesPkg/Library/FdtHwInfoParserLib/Pci/PciConfigSpaceParser.c @@ -13,6 +13,7 @@ **/ #include "CmObjectDescUtility.h" +#include #include #include "FdtHwInfoParser.h" diff --git a/DynamicTablesPkg/Library/FdtHwInfoParserLib/Serial/SerialPortParser.c b/DynamicTablesPkg/Library/FdtHwInfoParserLib/Serial/SerialPortParser.c index 2d0dccea3d3a..34659001c3c6 100644 --- a/DynamicTablesPkg/Library/FdtHwInfoParserLib/Serial/SerialPortParser.c +++ b/DynamicTablesPkg/Library/FdtHwInfoParserLib/Serial/SerialPortParser.c @@ -12,6 +12,8 @@ **/ #include +#include +#include #include "CmObjectDescUtility.h" #include "FdtHwInfoParser.h" diff --git a/DynamicTablesPkg/Readme.md b/DynamicTablesPkg/Readme.md index 7a3d499af8ff..3d0859696384 100644 --- a/DynamicTablesPkg/Readme.md +++ b/DynamicTablesPkg/Readme.md @@ -498,6 +498,8 @@ The CM_OBJECT_ID type is used to identify the Configuration Manager | 24 | Pcc Subspace Type 5 Info | | | 25 | P-State Dependency (PSD) Info | | | 26 | TPM Interface Info | | +| 27 | SPMI Interface Info | | +| 28 | SPMI Interrupt and Device/Uid Info | | | `*` | All other values are reserved. | | #### Object ID's in the X64 Namespace: diff --git a/EmbeddedPkg/Drivers/ConsolePrefDxe/ConsolePrefDxe.c b/EmbeddedPkg/Drivers/ConsolePrefDxe/ConsolePrefDxe.c index 2c2e73e72076..e846394180d8 100644 --- a/EmbeddedPkg/Drivers/ConsolePrefDxe/ConsolePrefDxe.c +++ b/EmbeddedPkg/Drivers/ConsolePrefDxe/ConsolePrefDxe.c @@ -10,6 +10,7 @@ #include #include #include +#include #include #include #include diff --git a/EmbeddedPkg/Drivers/ConsolePrefDxe/ConsolePrefDxe.inf b/EmbeddedPkg/Drivers/ConsolePrefDxe/ConsolePrefDxe.inf index c0ea2ca821e0..050e00ca871d 100644 --- a/EmbeddedPkg/Drivers/ConsolePrefDxe/ConsolePrefDxe.inf +++ b/EmbeddedPkg/Drivers/ConsolePrefDxe/ConsolePrefDxe.inf @@ -32,6 +32,7 @@ [LibraryClasses] BaseLib + BaseMemoryLib DebugLib FdtLib HiiLib diff --git a/EmbeddedPkg/EmbeddedPkg.dsc b/EmbeddedPkg/EmbeddedPkg.dsc index 503d7cc6d506..d0254c106f6d 100644 --- a/EmbeddedPkg/EmbeddedPkg.dsc +++ b/EmbeddedPkg/EmbeddedPkg.dsc @@ -196,6 +196,7 @@ gEmbeddedTokenSpaceGuid.PcdTimerPeriod|100000 [BuildOptions] + RELEASE_*_*_CC_FLAGS = -DMDEPKG_NDEBUG *_*_*_CC_FLAGS = -DDISABLE_NEW_DEPRECATED_INTERFACES ################################################################################ diff --git a/EmbeddedPkg/Library/AndroidBootImgLib/AndroidBootImgLib.c b/EmbeddedPkg/Library/AndroidBootImgLib/AndroidBootImgLib.c index d16929f2bbdb..1a0c92d4de98 100644 --- a/EmbeddedPkg/Library/AndroidBootImgLib/AndroidBootImgLib.c +++ b/EmbeddedPkg/Library/AndroidBootImgLib/AndroidBootImgLib.c @@ -9,6 +9,7 @@ #include #include +#include #include #include #include diff --git a/EmbeddedPkg/Library/AndroidBootImgLib/AndroidBootImgLib.inf b/EmbeddedPkg/Library/AndroidBootImgLib/AndroidBootImgLib.inf index 9754664df555..0973315de7d2 100644 --- a/EmbeddedPkg/Library/AndroidBootImgLib/AndroidBootImgLib.inf +++ b/EmbeddedPkg/Library/AndroidBootImgLib/AndroidBootImgLib.inf @@ -26,6 +26,7 @@ AndroidBootImgLib.c [LibraryClasses] + BaseLib DebugLib FdtLib PrintLib diff --git a/EmbeddedPkg/Universal/MmcDxe/MmcDebug.c b/EmbeddedPkg/Universal/MmcDxe/MmcDebug.c index cf1b97fb9ed6..3cbd2b96554a 100644 --- a/EmbeddedPkg/Universal/MmcDxe/MmcDebug.c +++ b/EmbeddedPkg/Universal/MmcDxe/MmcDebug.c @@ -8,16 +8,14 @@ #include "Mmc.h" -#if !defined (MDEPKG_NDEBUG) -CONST CHAR8 *mStrUnit[] = { +STATIC CONST CHAR8 *mStrUnit[] = { "100kbit/s", "1Mbit/s", "10Mbit/s", "100MBit/s", "Unknown", "Unknown", "Unknown", "Unknown" }; -CONST CHAR8 *mStrValue[] = { +STATIC CONST CHAR8 *mStrValue[] = { "1.0", "1.2", "1.3", "1.5", "2.0", "2.5", "3.0", "3.5", "4.0", "4.5", "5.0", "Unknown", "Unknown", "Unknown", "Unknown" }; -#endif VOID PrintCID ( diff --git a/EmulatorPkg/Win/Host/WinGopInput.c b/EmulatorPkg/Win/Host/WinGopInput.c index 1c67a1cb4017..22f12f1448c7 100644 --- a/EmulatorPkg/Win/Host/WinGopInput.c +++ b/EmulatorPkg/Win/Host/WinGopInput.c @@ -404,6 +404,10 @@ WinNtWndRegisterKeyNotify ( Private = GRAPHICS_PRIVATE_DATA_FROM_THIS (GraphicsIo); + if (Private == NULL) { + return EFI_INVALID_PARAMETER; + } + Private->MakeRegisterdKeyCallback = MakeCallBack; Private->BreakRegisterdKeyCallback = BreakCallBack; Private->RegisterdKeyCallbackContext = Context; diff --git a/EmulatorPkg/Win/Host/WinGopScreen.c b/EmulatorPkg/Win/Host/WinGopScreen.c index 661573d7771c..bcbd153cfdb9 100644 --- a/EmulatorPkg/Win/Host/WinGopScreen.c +++ b/EmulatorPkg/Win/Host/WinGopScreen.c @@ -808,6 +808,7 @@ WinNtGraphicsWindowOpen ( GopPrivateCreateQ (Private, &Private->QueueForRead); + Private->Signature = GRAPHICS_PRIVATE_DATA_SIGNATURE; Private->GraphicsWindowIo.Size = WinNtWndSize; Private->GraphicsWindowIo.CheckKey = WinNtWndCheckKey; Private->GraphicsWindowIo.GetKey = WinNtWndGetKey; diff --git a/EmulatorPkg/Win/Host/WinHost.c b/EmulatorPkg/Win/Host/WinHost.c index 193a947fbdaa..ee834dd1a892 100644 --- a/EmulatorPkg/Win/Host/WinHost.c +++ b/EmulatorPkg/Win/Host/WinHost.c @@ -1131,15 +1131,9 @@ PeCoffLoaderRelocateImageExtraAction ( if ((Library != NULL) && (DllEntryPoint != NULL)) { Status = AddModHandle (ImageContext, Library); - if (Status == EFI_ALREADY_STARTED) { + if ((Status == EFI_SUCCESS) || (Status == EFI_ALREADY_STARTED)) { // - // If the DLL has already been loaded before, then this instance of the DLL can not be debugged. - // - ImageContext->PdbPointer = NULL; - SecPrint ("WARNING: DLL already loaded. No source level debug %S.\n\r", DllFileName); - } else { - // - // This DLL is not already loaded, so source level debugging is supported. + // This DLL is either not loaded or already started, so source level debugging is supported. // ImageContext->EntryPoint = (EFI_PHYSICAL_ADDRESS)(UINTN)DllEntryPoint; SecPrint ("LoadLibraryEx (\n\r %S,\n\r NULL, DONT_RESOLVE_DLL_REFERENCES)\n\r", DllFileName); diff --git a/FatPkg/EnhancedFatDxe/DiskCache.c b/FatPkg/EnhancedFatDxe/DiskCache.c index d1a34a6a646f..9ecb2ea5836a 100644 --- a/FatPkg/EnhancedFatDxe/DiskCache.c +++ b/FatPkg/EnhancedFatDxe/DiskCache.c @@ -8,6 +8,206 @@ SPDX-License-Identifier: BSD-2-Clause-Patent #include "Fat.h" +/** + Helper function to clear the dirty state of the cache line. + + @param[in] CacheTag - CacheTag to clear + +**/ +STATIC +VOID +ClearCacheTagDirtyState ( + IN CACHE_TAG *CacheTag + ) +{ + if (CacheTag == NULL) { + ASSERT (CacheTag != NULL); + return; + } + + ZeroMem (CacheTag->DirtyBlocks, sizeof (CacheTag->DirtyBlocks)); + CacheTag->Dirty = FALSE; +} + +/** + Helper function to set a bit in a dirty block. This is used to + track which blocks to later write to disk. + + @param[in] BitNumber - Which bit to set in DirtyBlocks + @param[in] DirtyBlocks - Array of bits + +**/ +STATIC +VOID +SetBitInDirtyBlock ( + IN UINTN BitNumber, + IN DIRTY_BLOCKS *DirtyBlocks + ) +{ + UINTN BlockIndex; + UINTN BitIndex; + + // + // ASSERTs checking BitNumber are DEBUG build only to verify the assumptions in the + // Fat.h defines (See Fat.h lines to describe DIRTY_BITS) + // + ASSERT (BitNumber < DIRTY_BITS); + + BlockIndex = BitNumber / DIRTY_BITS_PER_BLOCK; + BitIndex = BitNumber % DIRTY_BITS_PER_BLOCK; + DirtyBlocks[BlockIndex] |= LShiftU64 (1ull, BitIndex); +} + +/** + Helper function to check if a particular bit in a dirty block is marked dirty or not, + so that it can be written to the disk if it is dirty. + + @param[in] BitNumber - Which bit to check in DirtyBlocks + @param[in] DirtyBlocks - Array of bits + +**/ +STATIC +BOOLEAN +IsBitInBlockDirty ( + IN UINTN BitNumber, + IN DIRTY_BLOCKS *DirtyBlocks + ) +{ + UINTN BlockIndex; + UINTN BitIndex; + + ASSERT (BitNumber < DIRTY_BITS); + + BlockIndex = BitNumber / DIRTY_BITS_PER_BLOCK; + BitIndex = BitNumber % DIRTY_BITS_PER_BLOCK; + return (DirtyBlocks[BlockIndex] & LShiftU64 (1ull, BitIndex)) != 0; +} + +/** + Helper function to set a cache tag dirty for a given offset and length. Dirty blocks marked + here will be flushed to disk when the file is closed. + + @param[in] DiskCache - DiskCache + @param[in] CacheTag - CacheTag to update + @param[in] Offset - Offset in the cache line to be marked modified + @param[in] Length - Length of the data to be marked modified + +**/ +STATIC +VOID +SetCacheTagDirty ( + IN DISK_CACHE *DiskCache, + IN CACHE_TAG *CacheTag, + IN UINTN Offset, + IN UINTN Length + ) +{ + UINTN Bit; + UINTN LastBit; + + Bit = Offset / DiskCache->BlockSize; + LastBit = (Offset + Length - 1) / DiskCache->BlockSize; + + ASSERT (Bit <= LastBit); + ASSERT (LastBit <= DIRTY_BITS); + + do { + SetBitInDirtyBlock (Bit, CacheTag->DirtyBlocks); + } while (++Bit <= LastBit); + + CacheTag->Dirty = TRUE; +} + +/** + Cache version of FatDiskIo for writing only those LBA's with dirty data. + + Keep track of LBA blocks within a cache line. Allow reads from the disk to read the + full cache line, and all writes to the cache line will update which Lba is dirty in DIRTY_BITS. + + At flush time, when the cache line is written out, only write the blocks that are dirty, coalescing + adjacent writes to a single FatDiskIo write. + + @param[in] CacheTag - Cache line to check for dirty bits from + @param[in] DataType - Type of Cache. + @param[in] Volume - FAT file system volume. + @param[in] IoMode - The access mode (disk read/write or cache access). + @param[in] Offset - The starting byte offset to read from. + @param[in] BufferSize - Size of Buffer. + @param[in, out] Buffer - Buffer containing read data. + @param[in] Task point to task instance. + + @retval EFI_SUCCESS - The operation is performed successfully. + @retval EFI_VOLUME_CORRUPTED - The access is + @return Others - The status of read/write the disk + +**/ +STATIC +EFI_STATUS +CacheFatDiskIo ( + IN CACHE_TAG *CacheTag, + IN CACHE_DATA_TYPE DataType, + IN FAT_VOLUME *Volume, + IN IO_MODE IoMode, + IN UINT64 Offset, + IN UINTN BufferSize, + IN OUT VOID *Buffer, + IN FAT_TASK *Task + ) +{ + DISK_CACHE *DiskCache; + UINTN BlockIndexInTag; + VOID *WriteBuffer; + UINTN LastBit; + UINT64 StartPos; + EFI_STATUS Status; + UINTN WriteSize; + + Status = EFI_SUCCESS; + if ((IoMode == WriteDisk) && (CacheTag->RealSize != 0)) { + DiskCache = &Volume->DiskCache[DataType]; + WriteBuffer = Buffer; + LastBit = (CacheTag->RealSize - 1) / DiskCache->BlockSize; + StartPos = Offset; + BlockIndexInTag = 0; + WriteSize = 0; + + do { + if (IsBitInBlockDirty (BlockIndexInTag, CacheTag->DirtyBlocks)) { + do { + WriteSize += DiskCache->BlockSize; + BlockIndexInTag++; + if (BlockIndexInTag > LastBit) { + break; + } + } while (IsBitInBlockDirty (BlockIndexInTag, CacheTag->DirtyBlocks)); + + Status = FatDiskIo (Volume, IoMode, StartPos, WriteSize, WriteBuffer, Task); + if (EFI_ERROR (Status)) { + return Status; + } + + StartPos += WriteSize + DiskCache->BlockSize; + WriteBuffer = (VOID *)((UINTN)WriteBuffer + WriteSize + DiskCache->BlockSize); + WriteSize = 0; + BlockIndexInTag++; + } else { + StartPos += DiskCache->BlockSize; + WriteBuffer = (VOID *)((UINTN)WriteBuffer + DiskCache->BlockSize); + BlockIndexInTag++; + } + } while (BlockIndexInTag <= LastBit); + + ASSERT (WriteSize == 0); + } else { + Status = FatDiskIo (Volume, IoMode, Offset, BufferSize, Buffer, Task); + if (EFI_ERROR (Status)) { + return Status; + } + } + + return Status; +} + /** This function is used by the Data Cache. @@ -57,8 +257,8 @@ FatFlushDataCacheRange ( CacheTag = &DiskCache->CacheTag[GroupNo]; if ((CacheTag->RealSize > 0) && (CacheTag->PageNo == PageNo)) { // - // When reading data form disk directly, if some dirty data - // in cache is in this rang, this data in the Buffer need to + // When reading data from disk directly, if some dirty data + // in cache is in this range, this data in the Buffer needs to // be updated with the cache's dirty data. // if (IoMode == ReadDisk) { @@ -119,7 +319,7 @@ FatExchangeCachePage ( GroupNo = PageNo & DiskCache->GroupMask; PageAlignment = DiskCache->PageAlignment; PageAddress = DiskCache->CacheBase + (GroupNo << PageAlignment); - EntryPos = DiskCache->BaseAddress + LShiftU64 (PageNo, PageAlignment); + EntryPos = (DiskCache->BaseAddress + LShiftU64 (PageNo, PageAlignment)); RealSize = CacheTag->RealSize; if (IoMode == ReadDisk) { RealSize = (UINTN)1 << PageAlignment; @@ -139,7 +339,7 @@ FatExchangeCachePage ( // // Only fat table writing will execute more than once // - Status = FatDiskIo (Volume, IoMode, EntryPos, RealSize, PageAddress, Task); + Status = CacheFatDiskIo (CacheTag, DataType, Volume, IoMode, EntryPos, RealSize, PageAddress, Task); if (EFI_ERROR (Status)) { return Status; } @@ -147,7 +347,7 @@ FatExchangeCachePage ( EntryPos += Volume->FatSize; } while (--WriteCount > 0); - CacheTag->Dirty = FALSE; + ClearCacheTagDirtyState (CacheTag); CacheTag->RealSize = RealSize; return EFI_SUCCESS; } @@ -248,7 +448,7 @@ FatAccessUnalignedCachePage ( Source = DiskCache->CacheBase + (GroupNo << DiskCache->PageAlignment) + Offset; Destination = Buffer; if (IoMode != ReadDisk) { - CacheTag->Dirty = TRUE; + SetCacheTagDirty (DiskCache, CacheTag, Offset, Length); DiskCache->Dirty = TRUE; Destination = Source; Source = Buffer; @@ -489,5 +689,9 @@ FatInitializeDiskCache ( Volume->CacheBuffer = CacheBuffer; DiskCache[CacheFat].CacheBase = CacheBuffer; DiskCache[CacheData].CacheBase = CacheBuffer + FatCacheSize; + + DiskCache[CacheFat].BlockSize = Volume->BlockIo->Media->BlockSize; + DiskCache[CacheData].BlockSize = Volume->BlockIo->Media->BlockSize; + return EFI_SUCCESS; } diff --git a/FatPkg/EnhancedFatDxe/Fat.h b/FatPkg/EnhancedFatDxe/Fat.h index 356cdbdb51af..fb6699061e96 100644 --- a/FatPkg/EnhancedFatDxe/Fat.h +++ b/FatPkg/EnhancedFatDxe/Fat.h @@ -84,6 +84,19 @@ SPDX-License-Identifier: BSD-2-Clause-Patent #define FAT_FATCACHE_GROUP_MIN_COUNT 1 #define FAT_FATCACHE_GROUP_MAX_COUNT 16 +// For cache block bits, use a UINT64 +typedef UINT64 DIRTY_BLOCKS; +#define BITS_PER_BYTE 8 +#define DIRTY_BITS_PER_BLOCK ((sizeof (DIRTY_BLOCKS) * BITS_PER_BYTE)) + +// largest cache line (64KB) / MinLbaSize (512) = 128 bits +#define DIRTY_BITS ((1 << FAT_DATACACHE_PAGE_MAX_ALIGNMENT) / (1 << MIN_BLOCK_ALIGNMENT)) + +// Number of DIRTY_BLOCKS to hold DIRTY_BITS bits. +#define DIRTY_BLOCKS_SIZE (DIRTY_BITS / sizeof (DIRTY_BLOCKS)) + +STATIC_ASSERT ((((1 << FAT_DATACACHE_PAGE_MAX_ALIGNMENT) / (1 << MIN_BLOCK_ALIGNMENT)) % sizeof (DIRTY_BLOCKS)) == 0, "DIRTY_BLOCKS not a proper size"); + // // Used in 8.3 generation algorithm // @@ -143,15 +156,17 @@ typedef enum { // Disk cache tag // typedef struct { - UINTN PageNo; - UINTN RealSize; - BOOLEAN Dirty; + UINTN PageNo; + UINTN RealSize; + BOOLEAN Dirty; + DIRTY_BLOCKS DirtyBlocks[DIRTY_BLOCKS_SIZE]; } CACHE_TAG; typedef struct { UINT64 BaseAddress; UINT64 LimitAddress; UINT8 *CacheBase; + UINT32 BlockSize; BOOLEAN Dirty; UINT8 PageAlignment; UINTN GroupMask; diff --git a/FatPkg/EnhancedFatDxe/Info.c b/FatPkg/EnhancedFatDxe/Info.c index d17ce5b7eed9..ab0631196593 100644 --- a/FatPkg/EnhancedFatDxe/Info.c +++ b/FatPkg/EnhancedFatDxe/Info.c @@ -303,6 +303,8 @@ FatSetFileInfo ( UINT8 NewAttribute; BOOLEAN ReadOnly; + TempDirEnt = NULL; + ZeroMem (&ZeroTime, sizeof (EFI_TIME)); Parent = OFile->Parent; DirEnt = OFile->DirEnt; diff --git a/FatPkg/EnhancedFatDxe/Init.c b/FatPkg/EnhancedFatDxe/Init.c index 3a946199e78a..9c51ed5b7b98 100644 --- a/FatPkg/EnhancedFatDxe/Init.c +++ b/FatPkg/EnhancedFatDxe/Init.c @@ -61,6 +61,32 @@ FatAllocateVolume ( // Volume->RootDirEnt.FileString = Volume->RootFileString; Volume->RootDirEnt.Entry.Attributes = FAT_ATTRIBUTE_DIRECTORY; + + if ((BlockIo == NULL) || (BlockIo->Media == NULL)) { + DEBUG ((DEBUG_ERROR, "%a BlockIo or BlockIo is NULL!\n", __func__)); + Status = EFI_INVALID_PARAMETER; + goto Done; + } + + // + // Check to see if the underlying block device's BlockSize meets what the FAT spec requires + // + if ((BlockIo->Media->BlockSize != 512) && + (BlockIo->Media->BlockSize != SIZE_1KB) && + (BlockIo->Media->BlockSize != SIZE_2KB) && + (BlockIo->Media->BlockSize != SIZE_4KB)) + { + Status = EFI_UNSUPPORTED; + DEBUG (( + DEBUG_ERROR, + "%a invalid BlockIo BlockSize %u for FAT filesystem on MediaId %u. Must be 512B, 1KB, 2KB, or 4KB\n", + __func__, + BlockIo->Media->BlockSize, + BlockIo->Media->MediaId + )); + goto Done; + } + // // Check to see if there's a file system on the volume // diff --git a/FatPkg/FatPei/FatLiteApi.c b/FatPkg/FatPei/FatLiteApi.c index b89ab7009da0..49214a21b425 100644 --- a/FatPkg/FatPei/FatLiteApi.c +++ b/FatPkg/FatPei/FatLiteApi.c @@ -426,6 +426,8 @@ GetRecoveryCapsuleInfo ( PEI_FILE_HANDLE Handle; UINTN NumberRecoveryCapsules; + Handle = NULL; + Status = GetNumberRecoveryCapsules (PeiServices, This, &NumberRecoveryCapsules); if (EFI_ERROR (Status)) { @@ -551,6 +553,8 @@ LoadRecoveryCapsule ( PEI_FILE_HANDLE Handle; UINTN NumberRecoveryCapsules; + Handle = NULL; + Status = GetNumberRecoveryCapsules (PeiServices, This, &NumberRecoveryCapsules); if (EFI_ERROR (Status)) { diff --git a/FatPkg/FatPkg.ci.yaml b/FatPkg/FatPkg.ci.yaml index fe95f481b50c..d54e5bb40d25 100644 --- a/FatPkg/FatPkg.ci.yaml +++ b/FatPkg/FatPkg.ci.yaml @@ -59,7 +59,8 @@ "Lfnbuffer", "FFFFFFFFL", "CDVOL", - "DMDEPKG" + "DMDEPKG", + "lba's" ] } } diff --git a/FmpDevicePkg/Library/FmpDependencyLib/FmpDependencyLib.c b/FmpDevicePkg/Library/FmpDependencyLib/FmpDependencyLib.c index 50662e74e065..11ee83d3ea8a 100644 --- a/FmpDevicePkg/Library/FmpDependencyLib/FmpDependencyLib.c +++ b/FmpDevicePkg/Library/FmpDependencyLib/FmpDependencyLib.c @@ -228,7 +228,7 @@ EvaluateDependency ( { EFI_STATUS Status; UINT8 *Iterator; - UINT8 Index; + UINTN Index; DEPEX_ELEMENT Element1; DEPEX_ELEMENT Element2; GUID ImageTypeId; diff --git a/IntelFsp2Pkg/Library/BaseFspCommonLib/BaseFspCommonLib.inf b/IntelFsp2Pkg/Library/BaseFspCommonLib/BaseFspCommonLib.inf index 8badd924dc49..52fe0f8ec6a7 100644 --- a/IntelFsp2Pkg/Library/BaseFspCommonLib/BaseFspCommonLib.inf +++ b/IntelFsp2Pkg/Library/BaseFspCommonLib/BaseFspCommonLib.inf @@ -16,6 +16,7 @@ [Sources] FspCommonLib.c + ReturnStatus.c [Packages] MdePkg/MdePkg.dec diff --git a/IntelFsp2Pkg/Library/BaseFspCommonLib/FspCommonLib.c b/IntelFsp2Pkg/Library/BaseFspCommonLib/FspCommonLib.c index 3ecc5bd265b2..663f9b3c0ad9 100644 --- a/IntelFsp2Pkg/Library/BaseFspCommonLib/FspCommonLib.c +++ b/IntelFsp2Pkg/Library/BaseFspCommonLib/FspCommonLib.c @@ -551,33 +551,3 @@ SetPhaseStatusCode ( FspData = GetFspGlobalDataPointer (); FspData->StatusCode = StatusCode; } - -/** - This function updates the return status of the FSP API with requested reset type and returns to Boot Loader. - - @param[in] FspResetType Reset type that needs to returned as API return status - -**/ -VOID -EFIAPI -FspApiReturnStatusReset ( - IN EFI_STATUS FspResetType - ) -{ - volatile BOOLEAN LoopUntilReset; - - LoopUntilReset = TRUE; - DEBUG ((DEBUG_INFO, "FSP returning control to Bootloader with reset required return status %x\n", FspResetType)); - if (GetFspGlobalDataPointer ()->FspMode == FSP_IN_API_MODE) { - /// - /// Below code is not an infinite loop.The control will go back to API calling function in BootLoader each time BootLoader - /// calls the FSP API without honoring the reset request by FSP - /// - do { - SetFspApiReturnStatus (FspResetType); - Pei2LoaderSwitchStack (); - DEBUG ((DEBUG_ERROR, "!!!ERROR: FSP has requested BootLoader for reset. But BootLoader has not honored the reset\n")); - DEBUG ((DEBUG_ERROR, "!!!ERROR: Please add support in BootLoader to honor the reset request from FSP\n")); - } while (LoopUntilReset); - } -} diff --git a/IntelFsp2Pkg/Library/BaseFspCommonLib/ReturnStatus.c b/IntelFsp2Pkg/Library/BaseFspCommonLib/ReturnStatus.c new file mode 100644 index 000000000000..1854e8c99c36 --- /dev/null +++ b/IntelFsp2Pkg/Library/BaseFspCommonLib/ReturnStatus.c @@ -0,0 +1,42 @@ +/** @file + Copyright (c) 2014 - 2022, Intel Corporation. All rights reserved.
+ SPDX-License-Identifier: BSD-2-Clause-Patent +**/ + +#include +#include +#include +#include +#include +#include +#include + +/** + This function updates the return status of the FSP API with requested reset type and returns to Boot Loader. + + @param[in] FspResetType Reset type that needs to returned as API return status + +**/ +VOID +EFIAPI +FspApiReturnStatusReset ( + IN EFI_STATUS FspResetType + ) +{ + volatile BOOLEAN LoopUntilReset; + + LoopUntilReset = TRUE; + DEBUG ((DEBUG_INFO, "FSP returning control to Bootloader with reset required return status %x\n", FspResetType)); + if (GetFspGlobalDataPointer ()->FspMode == FSP_IN_API_MODE) { + /// + /// Below code is not an infinite loop.The control will go back to API calling function in BootLoader each time BootLoader + /// calls the FSP API without honoring the reset request by FSP + /// + do { + SetFspApiReturnStatus (FspResetType); + Pei2LoaderSwitchStack (); + DEBUG ((DEBUG_ERROR, "!!!ERROR: FSP has requested BootLoader for reset. But BootLoader has not honored the reset\n")); + DEBUG ((DEBUG_ERROR, "!!!ERROR: Please add support in BootLoader to honor the reset request from FSP\n")); + } while (LoopUntilReset); + } +} diff --git a/IntelFsp2WrapperPkg/FspsWrapperPeim/FspsWrapperPeim.c b/IntelFsp2WrapperPkg/FspsWrapperPeim/FspsWrapperPeim.c index 1d4dd605771d..62b5e4534833 100644 --- a/IntelFsp2WrapperPkg/FspsWrapperPeim/FspsWrapperPeim.c +++ b/IntelFsp2WrapperPkg/FspsWrapperPeim/FspsWrapperPeim.c @@ -421,13 +421,22 @@ FspsWrapperInitDispatchMode ( EFI_PEI_PPI_DESCRIPTOR *MeasurementExcludedPpiList; MeasurementExcludedFvPpi = AllocatePool (sizeof (*MeasurementExcludedFvPpi)); - ASSERT (MeasurementExcludedFvPpi != NULL); + if (MeasurementExcludedFvPpi == NULL) { + ASSERT (MeasurementExcludedFvPpi != NULL); + return EFI_OUT_OF_RESOURCES; + } + MeasurementExcludedFvPpi->Count = 1; MeasurementExcludedFvPpi->Fv[0].FvBase = PcdGet32 (PcdFspsBaseAddress); MeasurementExcludedFvPpi->Fv[0].FvLength = ((EFI_FIRMWARE_VOLUME_HEADER *)(UINTN)PcdGet32 (PcdFspsBaseAddress))->FvLength; MeasurementExcludedPpiList = AllocatePool (sizeof (*MeasurementExcludedPpiList)); - ASSERT (MeasurementExcludedPpiList != NULL); + if (MeasurementExcludedPpiList == NULL) { + ASSERT (MeasurementExcludedPpiList != NULL); + FreePool (MeasurementExcludedFvPpi); + return EFI_OUT_OF_RESOURCES; + } + MeasurementExcludedPpiList->Flags = EFI_PEI_PPI_DESCRIPTOR_PPI | EFI_PEI_PPI_DESCRIPTOR_TERMINATE_LIST; MeasurementExcludedPpiList->Guid = &gEfiPeiFirmwareVolumeInfoMeasurementExcludedPpiGuid; MeasurementExcludedPpiList->Ppi = MeasurementExcludedFvPpi; diff --git a/Maintainers.txt b/Maintainers.txt index a54eb17a6b0f..166c379a5ef9 100644 --- a/Maintainers.txt +++ b/Maintainers.txt @@ -85,6 +85,7 @@ ARM, AARCH64 F: */AArch64/ F: */Arm/ M: Leif Lindholm [leiflindholm] +M: Ard Biesheuvel [ardbiesheuvel] M: Sami Mujawar [samimujawar] RISCV64 @@ -137,17 +138,20 @@ ArmPkg F: ArmPkg/ W: https://github.com/tianocore/tianocore.github.io/wiki/ArmPkg M: Leif Lindholm [leiflindholm] +M: Ard Biesheuvel [ardbiesheuvel] M: Sami Mujawar [samimujawar] ArmPlatformPkg F: ArmPlatformPkg/ W: https://github.com/tianocore/tianocore.github.io/wiki/ArmPlatformPkg M: Leif Lindholm [leiflindholm] +M: Ard Biesheuvel [ardbiesheuvel] M: Sami Mujawar [samimujawar] ArmVirtPkg F: ArmVirtPkg/ W: https://github.com/tianocore/tianocore.github.io/wiki/ArmVirtPkg +M: Ard Biesheuvel [ardbiesheuvel] M: Sami Mujawar [samimujawar] R: Leif Lindholm [leiflindholm] R: Gerd Hoffmann [kraxel] @@ -155,7 +159,7 @@ R: Gerd Hoffmann [kraxel] BaseTools F: BaseTools/ W: https://github.com/tianocore/tianocore.github.io/wiki/BaseTools -M: Rebecca Cran [bcran] +M: Rebecca Cran [bexcran] M: Liming Gao [lgao4] R: Bob Feng [BobCF] R: Yuwei Chen [YuweiChen1110] @@ -183,6 +187,7 @@ EmbeddedPkg F: EmbeddedPkg/ W: https://github.com/tianocore/tianocore.github.io/wiki/EmbeddedPkg M: Leif Lindholm [leiflindholm] +M: Ard Biesheuvel [ardbiesheuvel] M: Abner Chang [changab] EmulatorPkg @@ -374,7 +379,7 @@ MdeModulePkg: USB Network modules F: MdeModulePkg/Bus/Usb/UsbNetwork F: MdeModulePkg/Include/Protocol/UsbEthernetProtocol.h M: Richard Ho [richardho] -R: Rebecca Cran [bcran] +R: Rebecca Cran [bexcran] MdeModulePkg: Manageability modules F: MdeModulePkg/Include/*Ipmi*.* @@ -405,9 +410,10 @@ M: Prakashan Krishnadas Veliyathuparambil [karthikkabbigere1] MdePkg: FDT related library instance -F: MdePkg/Library/BaseFdtLib/FdtLib.c +F: MdePkg/Library/BaseFdtLib/* F: MdePkg/Include/Library/FdtLib.h M: Benny Lin [Benny3345678] +M: Leif Lindholm [leiflindholm] R: Gua Guo [gguo11837463] R: Chasel Chiu [ChaselChiu] R: James Lu [jameslu8] @@ -429,6 +435,7 @@ R: Brit Chesley [BritChesley] MdePkg: ARM/AARCH64 standard interfaces F: MdePkg/Include/Library/ArmLib.h M: Leif Lindholm [leiflindholm] +M: Ard Biesheuvel [ardbiesheuvel] M: Sami Mujawar [samimujawar] NetworkPkg @@ -440,6 +447,7 @@ R: Zachary Clark-williams [Zclarkwilliams] OvmfPkg F: OvmfPkg/ W: http://www.tianocore.org/ovmf/ +M: Ard Biesheuvel [ardbiesheuvel] M: Jiewen Yao [jyao1] R: Gerd Hoffmann [kraxel] S: Maintained @@ -455,7 +463,7 @@ F: OvmfPkg/Library/PciHostBridgeLibScan/ F: OvmfPkg/Library/PlatformBootManagerLibBhyve/ F: OvmfPkg/Library/ResetSystemLib/BaseResetShutdownBhyve.c F: OvmfPkg/Library/ResetSystemLib/BaseResetSystemLibBhyve.inf -R: Rebecca Cran [bcran] +R: Rebecca Cran [bexcran] R: Corvin Köhne [corvink] OvmfPkg: cloudhv-related modules @@ -597,6 +605,7 @@ W: https://github.com/tianocore/tianocore.github.io/wiki/SourceLevelDebugPkg StandaloneMmPkg F: StandaloneMmPkg/ +M: Ard Biesheuvel [ardbiesheuvel] M: Sami Mujawar [samimujawar] M: Ray Ni [niruiyu] R: Jiaxin Wu [jiaxinwu] @@ -621,6 +630,7 @@ W: https://github.com/tianocore/tianocore.github.io/wiki/UefiPayloadPkg M: Guo Dong [gdong1] M: Sean Rhodes [Sean-StarLabs] M: James Lu [jameslu8] +M: Benjamin Doron [benjamindoron] R: Gua Guo [gguo11837463] S: Maintained diff --git a/MdeModulePkg/Bus/Pci/PciHostBridgeDxe/PciRootBridgeIo.c b/MdeModulePkg/Bus/Pci/PciHostBridgeDxe/PciRootBridgeIo.c index 157a0ada8027..419f47a4263e 100644 --- a/MdeModulePkg/Bus/Pci/PciHostBridgeDxe/PciRootBridgeIo.c +++ b/MdeModulePkg/Bus/Pci/PciHostBridgeDxe/PciRootBridgeIo.c @@ -1238,6 +1238,16 @@ RootBridgeIoPciAccess ( } } + // + // If the access was a PCI write, it might have side effects that impact how + // the PCI device decodes its MMIO regions. Issue a barrier to ensure that + // subsequent MMIO accesses to those regions will not be reordered, and will + // not arrive before the PCI write. + // + if (!Read) { + MemoryFence (); + } + return EFI_SUCCESS; } diff --git a/MdeModulePkg/Bus/Pci/SataControllerDxe/SataController.c b/MdeModulePkg/Bus/Pci/SataControllerDxe/SataController.c index ea0116071c6a..e38304cffdee 100644 --- a/MdeModulePkg/Bus/Pci/SataControllerDxe/SataController.c +++ b/MdeModulePkg/Bus/Pci/SataControllerDxe/SataController.c @@ -287,9 +287,35 @@ SataControllerSupported ( IN EFI_DEVICE_PATH_PROTOCOL *RemainingDevicePath ) { - EFI_STATUS Status; - EFI_PCI_IO_PROTOCOL *PciIo; - PCI_TYPE00 PciData; + EFI_STATUS Status; + EFI_PCI_IO_PROTOCOL *PciIo; + PCI_TYPE00 PciData; + EFI_DEVICE_PATH_PROTOCOL *ParentDevicePath; + + // + // Attempt to open DevicePath Protocol + // + Status = gBS->OpenProtocol ( + Controller, + &gEfiDevicePathProtocolGuid, + (VOID *)&ParentDevicePath, + This->DriverBindingHandle, + Controller, + EFI_OPEN_PROTOCOL_BY_DRIVER + ); + if (EFI_ERROR (Status)) { + return Status; + } + + /// + /// Close the protocol because we don't use it here + /// + gBS->CloseProtocol ( + Controller, + &gEfiDevicePathProtocolGuid, + This->DriverBindingHandle, + Controller + ); // // Attempt to open PCI I/O Protocol diff --git a/MdeModulePkg/Bus/Pci/SataControllerDxe/SataController.h b/MdeModulePkg/Bus/Pci/SataControllerDxe/SataController.h index 4d545fb1f958..91d10e155537 100644 --- a/MdeModulePkg/Bus/Pci/SataControllerDxe/SataController.h +++ b/MdeModulePkg/Bus/Pci/SataControllerDxe/SataController.h @@ -18,6 +18,7 @@ #include #include #include +#include #include #include diff --git a/MdeModulePkg/Bus/Pci/SataControllerDxe/SataControllerDxe.inf b/MdeModulePkg/Bus/Pci/SataControllerDxe/SataControllerDxe.inf index 488920a68c2e..e446058e34cb 100644 --- a/MdeModulePkg/Bus/Pci/SataControllerDxe/SataControllerDxe.inf +++ b/MdeModulePkg/Bus/Pci/SataControllerDxe/SataControllerDxe.inf @@ -45,6 +45,7 @@ [Protocols] gEfiPciIoProtocolGuid ## TO_START gEfiIdeControllerInitProtocolGuid ## BY_START + gEfiDevicePathProtocolGuid [UserExtensions.TianoCore."ExtraFiles"] SataControllerDxeExtra.uni diff --git a/MdeModulePkg/Bus/Ufs/UfsBlockIoPei/UfsBlockIoPei.c b/MdeModulePkg/Bus/Ufs/UfsBlockIoPei/UfsBlockIoPei.c index e04a93da6af1..4c7ec648ff7c 100644 --- a/MdeModulePkg/Bus/Ufs/UfsBlockIoPei/UfsBlockIoPei.c +++ b/MdeModulePkg/Bus/Ufs/UfsBlockIoPei/UfsBlockIoPei.c @@ -1082,13 +1082,17 @@ InitializeUfsBlockIoPeim ( IN CONST EFI_PEI_SERVICES **PeiServices ) { - EFI_STATUS Status; - UFS_PEIM_HC_PRIVATE_DATA *Private; - EDKII_UFS_HOST_CONTROLLER_PPI *UfsHcPpi; - UINT32 Index; - UINTN MmioBase; - UINT8 Controller; - UFS_UNIT_DESC UnitDescriptor; + EFI_STATUS Status; + UFS_PEIM_HC_PRIVATE_DATA *Private; + EDKII_UFS_HOST_CONTROLLER_PPI *UfsHcPpi; + UINT32 Index; + UINTN MmioBase; + UINT8 Controller; + UFS_UNIT_DESC UnitDescriptor; + EDKII_UFS_HC_PLATFORM_PPI *UfsHcPlatformPpi = NULL; + UFS_DEV_DESC DeviceDescriptor; + UINT8 RefClkAttr; + EDKII_UFS_CARD_REF_CLK_FREQ_ATTRIBUTE Attributes; // // Shadow this PEIM to run from memory @@ -1110,6 +1114,19 @@ InitializeUfsBlockIoPeim ( return EFI_DEVICE_ERROR; } + // + // Locate ufs host controller platform PPI + // + Status = PeiServicesLocatePpi ( + &gEdkiiUfsHcPlatformPpiGuid, + 0, + NULL, + (VOID **)&UfsHcPlatformPpi + ); + if (EFI_ERROR (Status)) { + DEBUG ((DEBUG_ERROR, "LocatePpi gEdkiiUfsHcPlatformPpiGuid Status :%r\n", Status)); + } + IoMmuInit (); Controller = 0; @@ -1145,7 +1162,7 @@ InitializeUfsBlockIoPeim ( // // Initialize UFS Host Controller H/W. // - Status = UfsControllerInit (Private); + Status = UfsControllerInit (UfsHcPlatformPpi, Private); if (EFI_ERROR (Status)) { DEBUG ((DEBUG_ERROR, "UfsDevicePei: Host Controller Initialization Error, Status = %r\n", Status)); Controller++; @@ -1174,25 +1191,87 @@ InitializeUfsBlockIoPeim ( continue; } - // - // Check if 8 common luns are active and set corresponding bit mask. - // - for (Index = 0; Index < UFS_PEIM_MAX_LUNS; Index++) { - Status = UfsRwDeviceDesc (Private, TRUE, UfsUnitDesc, (UINT8)Index, 0, &UnitDescriptor, sizeof (UFS_UNIT_DESC)); + if ((UfsHcPlatformPpi != NULL) && + ((UfsHcPlatformPpi->RefClkFreq == EdkiiUfsCardRefClkFreq19p2Mhz) || + (UfsHcPlatformPpi->RefClkFreq == EdkiiUfsCardRefClkFreq26Mhz) || + (UfsHcPlatformPpi->RefClkFreq == EdkiiUfsCardRefClkFreq38p4Mhz))) + { + RefClkAttr = UfsAttrRefClkFreq; + Attributes = EdkiiUfsCardRefClkFreqObsolete; + + Status = UfsRwAttributes (Private, TRUE, RefClkAttr, 0, 0, (UINT32 *)&Attributes); + DEBUG ((DEBUG_INFO, "UfsRwAttributes #1 Status = %r \n", Status)); + if (!EFI_ERROR (Status)) { + if (Attributes != UfsHcPlatformPpi->RefClkFreq) { + Attributes = UfsHcPlatformPpi->RefClkFreq; + DEBUG ( + (DEBUG_INFO, + "Setting bRefClkFreq attribute(%x) to %x\n 0 -> 19.2 Mhz\n 1 -> 26 Mhz\n 2 -> 38.4 Mhz\n 3 -> Obsolete\n", + RefClkAttr, + Attributes) + ); + Status = UfsRwAttributes (Private, FALSE, RefClkAttr, 0, 0, (UINT32 *)&Attributes); + DEBUG ((DEBUG_INFO, "UfsRwAttributes #2 Status = %r \n", Status)); + if (EFI_ERROR (Status)) { + DEBUG ( + (DEBUG_ERROR, + "Failed to Change Reference Clock Attribute to, Status = %r \n", + Status) + ); + } + } + } else { + DEBUG ( + (DEBUG_ERROR, + "Failed to Read Reference Clock Attribute, Status = %r \n", + Status) + ); + } + } + + if ((UfsHcPlatformPpi != NULL) && (UfsHcPlatformPpi->Callback != NULL)) { + Status = UfsHcPlatformPpi->Callback (&Private->UfsHcBase, EdkiiUfsHcPostLinkStartup); if (EFI_ERROR (Status)) { - DEBUG ((DEBUG_ERROR, "Fail to read UFS Unit Descriptor, Index = %X, Status = %r\n", Index, Status)); + DEBUG ((DEBUG_ERROR, "Failure from platform driver during EdkiiUfsHcPostLinkStartup, Status = %r\n", Status)); + Controller++; continue; } - if (UnitDescriptor.LunEn == 0x1) { - DEBUG ((DEBUG_INFO, "Ufs %d Lun %d is enabled\n", Controller, Index)); - Private->Luns.BitMask |= (BIT0 << Index); + // + // Check if 8 common luns are active and set corresponding bit mask. + // + for (Index = 0; Index < UFS_PEIM_MAX_LUNS; Index++) { + Status = UfsRwDeviceDesc (Private, TRUE, UfsUnitDesc, (UINT8)Index, 0, &UnitDescriptor, sizeof (UFS_UNIT_DESC)); + if (EFI_ERROR (Status)) { + DEBUG ((DEBUG_ERROR, "Fail to read UFS Unit Descriptor, Index = %X, Status = %r\n", Index, Status)); + continue; + } + + if (UnitDescriptor.LunEn == 0x1) { + DEBUG ((DEBUG_INFO, "Ufs %d Lun %d is enabled\n", Controller, Index)); + Private->Luns.BitMask |= (BIT0 << Index); + } } - } - PeiServicesInstallPpi (&Private->BlkIoPpiList); - PeiServicesNotifyPpi (&Private->EndOfPeiNotifyList); - Controller++; + // + // Get Ufs Device's Lun Info by reading Configuration Descriptor + // + Status = UfsRwDeviceDesc (Private, TRUE, UfsConfigDesc, 0, 0, &DeviceDescriptor, sizeof (UFS_DEV_DESC)); + if (EFI_ERROR (Status)) { + DEBUG ((DEBUG_ERROR, "Ufs Get Configuration Descriptor Error, Status = %r\n", Status)); + Controller++; + continue; + } + + if (DeviceDescriptor.SecurityLun == 0x1) { + DEBUG ((DEBUG_INFO, "UFS WLUN RPMB is supported\n")); + Private->Luns.BitMask |= BIT11; + } + + PeiServicesInstallPpi (&Private->BlkIoPpiList); + PeiServicesNotifyPpi (&Private->EndOfPeiNotifyList); + Controller++; + } } return EFI_SUCCESS; diff --git a/MdeModulePkg/Bus/Ufs/UfsBlockIoPei/UfsBlockIoPei.h b/MdeModulePkg/Bus/Ufs/UfsBlockIoPei/UfsBlockIoPei.h index 869332fbe349..7815e101e2bc 100644 --- a/MdeModulePkg/Bus/Ufs/UfsBlockIoPei/UfsBlockIoPei.h +++ b/MdeModulePkg/Bus/Ufs/UfsBlockIoPei/UfsBlockIoPei.h @@ -11,6 +11,7 @@ #include #include +#include #include #include #include @@ -156,6 +157,33 @@ typedef struct _UFS_DEVICE_MANAGEMENT_REQUEST_PACKET { UINT8 Ocs; } UFS_DEVICE_MANAGEMENT_REQUEST_PACKET; +/** + Read or write specified attribute of a UFS device. + + @param[in] Private The pointer to the UFS_PASS_THRU_PRIVATE_DATA data structure. + @param[in] Read The boolean variable to show r/w direction. + @param[in] AttrId The ID of Attribute. + @param[in] Index The Index of Attribute. + @param[in] Selector The Selector of Attribute. + @param[in, out] Attributes The value of Attribute to be read or written. + + @retval EFI_SUCCESS The Attribute was read/written successfully. + @retval EFI_INVALID_PARAMETER AttrId, Index and Selector are invalid combination to point to a + type of UFS device descriptor. + @retval EFI_DEVICE_ERROR A device error occurred while attempting to r/w the Attribute. + @retval EFI_TIMEOUT A timeout occurred while waiting for the completion of r/w the Attribute. + +**/ +EFI_STATUS +UfsRwAttributes ( + IN UFS_PEIM_HC_PRIVATE_DATA *Private, + IN BOOLEAN Read, + IN UINT8 AttrId, + IN UINT8 Index, + IN UINT8 Selector, + IN OUT UINT32 *Attributes + ); + /** Sends a UFS-supported SCSI Request Packet to a UFS device that is attached to the UFS host controller. @@ -193,7 +221,8 @@ UfsExecScsiCmds ( **/ EFI_STATUS UfsControllerInit ( - IN UFS_PEIM_HC_PRIVATE_DATA *Private + IN EDKII_UFS_HC_PLATFORM_PPI *UfsHcPlatformPpi, + IN UFS_PEIM_HC_PRIVATE_DATA *Private ); /** diff --git a/MdeModulePkg/Bus/Ufs/UfsBlockIoPei/UfsBlockIoPei.inf b/MdeModulePkg/Bus/Ufs/UfsBlockIoPei/UfsBlockIoPei.inf index 5da906e24dd7..1d4850a42bfa 100644 --- a/MdeModulePkg/Bus/Ufs/UfsBlockIoPei/UfsBlockIoPei.inf +++ b/MdeModulePkg/Bus/Ufs/UfsBlockIoPei/UfsBlockIoPei.inf @@ -52,6 +52,7 @@ gEdkiiPeiUfsHostControllerPpiGuid ## CONSUMES gEdkiiIoMmuPpiGuid ## CONSUMES gEfiEndOfPeiSignalPpiGuid ## CONSUMES + gEdkiiUfsHcPlatformPpiGuid ## SOMETIMES CONSUMES [Pcd] gEfiMdeModulePkgTokenSpaceGuid.PcdUfsInitialCompletionTimeout ## CONSUMES diff --git a/MdeModulePkg/Bus/Ufs/UfsBlockIoPei/UfsHci.c b/MdeModulePkg/Bus/Ufs/UfsBlockIoPei/UfsHci.c index 360b642611b9..88798919af44 100644 --- a/MdeModulePkg/Bus/Ufs/UfsBlockIoPei/UfsHci.c +++ b/MdeModulePkg/Bus/Ufs/UfsBlockIoPei/UfsHci.c @@ -552,8 +552,8 @@ UfsCreateDMCommandDesc ( } if (((Opcode != UtpQueryFuncOpcodeRdFlag) && (Opcode != UtpQueryFuncOpcodeSetFlag) && - (Opcode != UtpQueryFuncOpcodeClrFlag) && (Opcode != UtpQueryFuncOpcodeTogFlag)) && - ((DataSize == 0) || (Data == NULL))) + (Opcode != UtpQueryFuncOpcodeClrFlag) && (Opcode != UtpQueryFuncOpcodeTogFlag) && + (Opcode != UtpQueryFuncOpcodeRdAttr)) && ((DataSize == 0) || (Data == NULL))) { return EFI_INVALID_PARAMETER; } @@ -759,6 +759,7 @@ UfsGetReturnDataFromQueryResponse ( ) { UINT16 ReturnDataSize; + UINT32 ReturnData; ReturnDataSize = 0; @@ -799,6 +800,16 @@ UfsGetReturnDataFromQueryResponse ( // *((UINT8 *)(Packet->OutDataBuffer)) = *((UINT8 *)&(QueryResp->Tsf.Value) + 3); break; + case UtpQueryFuncOpcodeRdAttr: + ReturnData = QueryResp->Tsf.Value; + SwapLittleEndianToBigEndian ((UINT8 *)&ReturnData, sizeof (UINT32)); + CopyMem (Packet->InDataBuffer, &ReturnData, sizeof (UINT32)); + break; + case UtpQueryFuncOpcodeWrAttr: + ReturnData = QueryResp->Tsf.Value; + SwapLittleEndianToBigEndian ((UINT8 *)&ReturnData, sizeof (UINT32)); + CopyMem (Packet->OutDataBuffer, &ReturnData, sizeof (UINT32)); + break; default: return EFI_INVALID_PARAMETER; } @@ -833,7 +844,9 @@ UfsSendDmRequestRetry ( UINT8 *CmdDescBase; UINT32 CmdDescSize; - // + // Workaround: Adding this one second for reading descriptor + MicroSecondDelay (1 * 1000 * 1000); // delay 1 seconds + // Find out which slot of transfer request list is available. // Status = UfsFindAvailableSlotInTrl (Private, &Slot); @@ -980,6 +993,56 @@ UfsRwDeviceDesc ( return Status; } +/** + Read or write specified attribute of a UFS device. + + @param[in] Private The pointer to the UFS_PASS_THRU_PRIVATE_DATA data structure. + @param[in] Read The boolean variable to show r/w direction. + @param[in] AttrId The ID of Attribute. + @param[in] Index The Index of Attribute. + @param[in] Selector The Selector of Attribute. + @param[in, out] Attributes The value of Attribute to be read or written. + + @retval EFI_SUCCESS The Attribute was read/written successfully. + @retval EFI_INVALID_PARAMETER AttrId, Index and Selector are invalid combination to point to a + type of UFS device descriptor. + @retval EFI_DEVICE_ERROR A device error occurred while attempting to r/w the Attribute. + @retval EFI_TIMEOUT A timeout occurred while waiting for the completion of r/w the Attribute. + +**/ +EFI_STATUS +UfsRwAttributes ( + IN UFS_PEIM_HC_PRIVATE_DATA *Private, + IN BOOLEAN Read, + IN UINT8 AttrId, + IN UINT8 Index, + IN UINT8 Selector, + IN OUT UINT32 *Attributes + ) +{ + UFS_DEVICE_MANAGEMENT_REQUEST_PACKET Packet; + + ZeroMem (&Packet, sizeof (UFS_DEVICE_MANAGEMENT_REQUEST_PACKET)); + + if (Read) { + Packet.DataDirection = UfsDataIn; + Packet.Opcode = UtpQueryFuncOpcodeRdAttr; + Packet.InDataBuffer = Attributes; + } else { + Packet.DataDirection = UfsDataOut; + Packet.Opcode = UtpQueryFuncOpcodeWrAttr; + Packet.OutDataBuffer = Attributes; + Packet.OutTransferLength = sizeof (UINT32); + } + + Packet.DescId = AttrId; + Packet.Index = Index; + Packet.Selector = Selector; + Packet.Timeout = UFS_TIMEOUT; + + return UfsSendDmRequest (Private, &Packet); +} + /** Read or write specified flag of a UFS device. @@ -1387,6 +1450,7 @@ UfsExecUicCommands ( /** Enable the UFS host controller for accessing. + @param[in] UfsHcPlatformPpi The pointer to the EDKII_UFS_HC_PLATFORM_PPI data structure @param[in] Private The pointer to the UFS_PEIM_HC_PRIVATE_DATA data structure. @retval EFI_SUCCESS The UFS host controller enabling was executed successfully. @@ -1395,13 +1459,22 @@ UfsExecUicCommands ( **/ EFI_STATUS UfsEnableHostController ( - IN UFS_PEIM_HC_PRIVATE_DATA *Private + IN EDKII_UFS_HC_PLATFORM_PPI *UfsHcPlatformPpi, + IN UFS_PEIM_HC_PRIVATE_DATA *Private ) { EFI_STATUS Status; UINTN Address; UINT32 Data; + if ((UfsHcPlatformPpi != NULL) && (UfsHcPlatformPpi->Callback != NULL)) { + Status = UfsHcPlatformPpi->Callback (&Private->UfsHcBase, EdkiiUfsHcPreHce); + if (EFI_ERROR (Status)) { + DEBUG ((DEBUG_ERROR, "Failure from platform driver during EdkiiUfsHcPreHce, Status = %r\n", Status)); + return Status; + } + } + // // UFS 2.0 spec section 7.1.1 - Host Controller Initialization // @@ -1435,6 +1508,14 @@ UfsEnableHostController ( return EFI_DEVICE_ERROR; } + if ((UfsHcPlatformPpi != NULL) && (UfsHcPlatformPpi->Callback != NULL)) { + Status = UfsHcPlatformPpi->Callback (&Private->UfsHcBase, EdkiiUfsHcPostHce); + if (EFI_ERROR (Status)) { + DEBUG ((DEBUG_ERROR, "Failure from platform driver during EdkiiUfsHcPostHce, Status = %r\n", Status)); + return Status; + } + } + return EFI_SUCCESS; } @@ -1450,7 +1531,8 @@ UfsEnableHostController ( **/ EFI_STATUS UfsDeviceDetection ( - IN UFS_PEIM_HC_PRIVATE_DATA *Private + IN EDKII_UFS_HC_PLATFORM_PPI *UfsHcPlatformPpi, + IN UFS_PEIM_HC_PRIVATE_DATA *Private ) { UINTN Retry; @@ -1458,6 +1540,14 @@ UfsDeviceDetection ( UINT32 Data; EFI_STATUS Status; + if ((UfsHcPlatformPpi != NULL) && (UfsHcPlatformPpi->Callback != NULL)) { + Status = UfsHcPlatformPpi->Callback (&Private->UfsHcBase, EdkiiUfsHcPreLinkStartup); + if (EFI_ERROR (Status)) { + DEBUG ((DEBUG_ERROR, "Failure from platform driver during EdkiiUfsHcPreLinkStartup, Status = %r\n", Status)); + return Status; + } + } + // // Start UFS device detection. // Try up to 3 times for establishing data link with device. @@ -1625,6 +1715,7 @@ UfsInitTransferRequestList ( /** Initialize the UFS host controller. + @param[in] UfsHcPlatformPpi The pointer to the EDKII_UFS_HC_PLATFORM_PPI data structure. // APTIOV_OVERRIDE @param[in] Private The pointer to the UFS_PEIM_HC_PRIVATE_DATA data structure. @retval EFI_SUCCESS The Ufs Host Controller is initialized successfully. @@ -1633,18 +1724,19 @@ UfsInitTransferRequestList ( **/ EFI_STATUS UfsControllerInit ( - IN UFS_PEIM_HC_PRIVATE_DATA *Private + IN EDKII_UFS_HC_PLATFORM_PPI *UfsHcPlatformPpi, + IN UFS_PEIM_HC_PRIVATE_DATA *Private ) { EFI_STATUS Status; - Status = UfsEnableHostController (Private); + Status = UfsEnableHostController (UfsHcPlatformPpi, Private); if (EFI_ERROR (Status)) { DEBUG ((DEBUG_ERROR, "UfsDevicePei: Enable Host Controller Fails, Status = %r\n", Status)); return Status; } - Status = UfsDeviceDetection (Private); + Status = UfsDeviceDetection (UfsHcPlatformPpi, Private); if (EFI_ERROR (Status)) { DEBUG ((DEBUG_ERROR, "UfsDevicePei: Device Detection Fails, Status = %r\n", Status)); return Status; diff --git a/MdeModulePkg/Bus/Usb/UsbNetwork/UsbCdcEcm/UsbEcmFunction.c b/MdeModulePkg/Bus/Usb/UsbNetwork/UsbCdcEcm/UsbEcmFunction.c index 0c1f252b85df..dc78466e0d33 100644 --- a/MdeModulePkg/Bus/Usb/UsbNetwork/UsbCdcEcm/UsbEcmFunction.c +++ b/MdeModulePkg/Bus/Usb/UsbNetwork/UsbCdcEcm/UsbEcmFunction.c @@ -111,7 +111,7 @@ GetFunctionalDescriptor ( for (Offset = 0; NextDescriptor (Config, &Offset);) { Interface = (EFI_USB_INTERFACE_DESCRIPTOR *)((UINT8 *)Config + Offset); - if (Interface->DescriptorType == CS_INTERFACE) { + if (Interface->DescriptorType == USB_DESC_TYPE_CS_INTERFACE) { if (((USB_HEADER_FUN_DESCRIPTOR *)Interface)->DescriptorSubtype == FunDescriptorType) { switch (FunDescriptorType) { case HEADER_FUN_DESCRIPTOR: diff --git a/MdeModulePkg/Bus/Usb/UsbNetwork/UsbCdcNcm/UsbNcmFunction.c b/MdeModulePkg/Bus/Usb/UsbNetwork/UsbCdcNcm/UsbNcmFunction.c index ef01a6f5458c..4b6e0d254798 100644 --- a/MdeModulePkg/Bus/Usb/UsbNetwork/UsbCdcNcm/UsbNcmFunction.c +++ b/MdeModulePkg/Bus/Usb/UsbNetwork/UsbCdcNcm/UsbNcmFunction.c @@ -111,7 +111,7 @@ GetFunctionalDescriptor ( for (Offset = 0; NextDescriptor (Config, &Offset);) { Interface = (EFI_USB_INTERFACE_DESCRIPTOR *)((UINT8 *)Config + Offset); - if (Interface->DescriptorType == CS_INTERFACE) { + if (Interface->DescriptorType == USB_DESC_TYPE_CS_INTERFACE) { if (((USB_HEADER_FUN_DESCRIPTOR *)Interface)->DescriptorSubtype == FunDescriptorType) { switch (FunDescriptorType) { case HEADER_FUN_DESCRIPTOR: diff --git a/MdeModulePkg/Bus/Usb/UsbNetwork/UsbRndis/UsbRndisFunction.c b/MdeModulePkg/Bus/Usb/UsbNetwork/UsbRndis/UsbRndisFunction.c index 6d45a1b775ba..8723a8221fe5 100644 --- a/MdeModulePkg/Bus/Usb/UsbNetwork/UsbRndis/UsbRndisFunction.c +++ b/MdeModulePkg/Bus/Usb/UsbNetwork/UsbRndis/UsbRndisFunction.c @@ -123,7 +123,7 @@ GetFunctionalDescriptor ( for (Offset = 0; NextDescriptor (Config, &Offset);) { Interface = (EFI_USB_INTERFACE_DESCRIPTOR *)((UINT8 *)Config + Offset); - if (Interface->DescriptorType == CS_INTERFACE) { + if (Interface->DescriptorType == USB_DESC_TYPE_CS_INTERFACE) { if (((USB_HEADER_FUN_DESCRIPTOR *)Interface)->DescriptorSubtype == FunDescriptorType) { switch (FunDescriptorType) { case HEADER_FUN_DESCRIPTOR: diff --git a/MdeModulePkg/Core/Pei/Dispatcher/Dispatcher.c b/MdeModulePkg/Core/Pei/Dispatcher/Dispatcher.c index 79ff8d1cf9f3..5e8d5b8e779b 100644 --- a/MdeModulePkg/Core/Pei/Dispatcher/Dispatcher.c +++ b/MdeModulePkg/Core/Pei/Dispatcher/Dispatcher.c @@ -3,14 +3,382 @@ Copyright (c) 2006 - 2024, Intel Corporation. All rights reserved.
(C) Copyright 2016 Hewlett Packard Enterprise Development LP
+Copyright (c) Microsoft Corporation. SPDX-License-Identifier: BSD-2-Clause-Patent **/ #include "PeiMain.h" +// +// Utility global variables +// + +/** + DelayedDispatchDispatcher + + Delayed Dispach cycle (ie one pass) through each entry, calling functions when their + time has expired. When DelayedGroupId is specified, if there are any of the specified entries + in the dispatch queue during dispatch, repeat the DelayedDispatch cycle. + + @param DelayedDispatchTable Pointer to dispatch table + @param OPTIONAL DelayedGroupId used to insure particular time is met. + + @return BOOLEAN +**/ +BOOLEAN +DelayedDispatchDispatcher ( + IN DELAYED_DISPATCH_TABLE *DelayedDispatchTable, + IN EFI_GUID *DelayedGroupId OPTIONAL + ); + +/** + DelayedDispatch End of PEI callback function. Insure that all of the delayed dispatch + entries are complete before exiting PEI. + + @param[in] PeiServices - Pointer to PEI Services Table. + @param[in] NotifyDesc - Pointer to the descriptor for the Notification event that + caused this function to execute. + @param[in] Ppi - Pointer to the PPI data associated with this function. + + @retval EFI_STATUS - Always return EFI_SUCCESS +**/ +EFI_STATUS +EFIAPI +PeiDelayedDispatchOnEndOfPei ( + IN EFI_PEI_SERVICES **PeiServices, + IN EFI_PEI_NOTIFY_DESCRIPTOR *NotifyDesc, + IN VOID *Ppi + ); + +EFI_DELAYED_DISPATCH_PPI mDelayedDispatchPpi = { PeiDelayedDispatchRegister, PeiDelayedDispatchWaitOnEvent }; +EFI_PEI_PPI_DESCRIPTOR mDelayedDispatchDesc = { + (EFI_PEI_PPI_DESCRIPTOR_PPI | EFI_PEI_PPI_DESCRIPTOR_TERMINATE_LIST), + &gEfiPeiDelayedDispatchPpiGuid, + &mDelayedDispatchPpi +}; + +EFI_PEI_NOTIFY_DESCRIPTOR mDelayedDispatchNotifyDesc = { + EFI_PEI_PPI_DESCRIPTOR_NOTIFY_CALLBACK | EFI_PEI_PPI_DESCRIPTOR_TERMINATE_LIST, + &gEfiEndOfPeiSignalPpiGuid, + PeiDelayedDispatchOnEndOfPei +}; + +/** + Helper function to look up DELAYED_DISPATCH_TABLE published in HOB. + + @return Pointer to DELAYED_DISPATCH_TABLE from HOB +**/ +DELAYED_DISPATCH_TABLE * +GetDelayedDispatchTable ( + VOID + ) +{ + EFI_HOB_GUID_TYPE *GuidHob; + + GuidHob = GetFirstGuidHob (&gEfiDelayedDispatchTableGuid); + if (GuidHob == NULL) { + // There is something off about the build if this happens. We do want to + // assert here to catch it during development. + DEBUG ((DEBUG_ERROR, "%a - Delayed Dispatch Hob not available.\n", __func__)); + ASSERT (FALSE); + return NULL; + } + + return (DELAYED_DISPATCH_TABLE *)GET_GUID_HOB_DATA (GuidHob); +} + +/** + Register a callback to be called after a minimum delay has occurred. + + This service is the single member function of the EFI_DELAYED_DISPATCH_PPI + + @param[in] This Pointer to the EFI_DELAYED_DISPATCH_PPI instance + @param[in] Function Function to call back + @param[in] Context Context data + @param[in] DelayedGroupId GUID for this Delayed Dispatch request. + @param[in] Delay Delay interval + + @retval EFI_SUCCESS Function successfully loaded + @retval EFI_INVALID_PARAMETER One of the Arguments is not supported + @retval EFI_OUT_OF_RESOURCES No more entries + +**/ +EFI_STATUS +EFIAPI +PeiDelayedDispatchRegister ( + IN EFI_DELAYED_DISPATCH_PPI *This, + IN EFI_DELAYED_DISPATCH_FUNCTION Function, + IN UINT64 Context, + IN EFI_GUID *DelayedGroupId OPTIONAL, + IN UINT32 Delay + ) +{ + DELAYED_DISPATCH_TABLE *DelayedDispatchTable; + DELAYED_DISPATCH_ENTRY *Entry; + EFI_STATUS Status; + + // Check input parameters + if ((Function == NULL) || (Delay > FixedPcdGet32 (PcdDelayedDispatchMaxDelayUs)) || (This == NULL)) { + DEBUG ((DEBUG_ERROR, "%a Invalid parameter. Function: %Lx, Delay: %u, This: %p\n", __func__, (UINT64)(UINTN)Function, Delay, This)); + Status = EFI_INVALID_PARAMETER; + goto Exit; + } + + // Get delayed dispatch table + DelayedDispatchTable = GetDelayedDispatchTable (); + if (DelayedDispatchTable == NULL) { + DEBUG ((DEBUG_ERROR, "%a Unable to locate dispatch table\n", __func__)); + Status = EFI_UNSUPPORTED; + goto Exit; + } + + // Check for available entry slots + ASSERT (DelayedDispatchTable->Count <= DELAYED_DISPATCH_MAX_ENTRIES); + if (DelayedDispatchTable->Count == DELAYED_DISPATCH_MAX_ENTRIES) { + DEBUG ((DEBUG_ERROR, "%a Too many entries requested\n", __func__)); + Status = EFI_OUT_OF_RESOURCES; + goto Exit; + } + + Entry = &DelayedDispatchTable->Entry[DelayedDispatchTable->Count]; + Entry->Function = Function; + Entry->Context = Context; + Status = SafeUint64Add (GET_TIME_IN_US (), Delay, &Entry->DispatchTime); + if (EFI_ERROR (Status)) { + DEBUG ((DEBUG_ERROR, "%a Delay overflow\n", __func__)); + Status = EFI_INVALID_PARAMETER; + goto Exit; + } + + if (DelayedGroupId == NULL) { + ZeroMem (&Entry->DelayedGroupId, sizeof (EFI_GUID)); + } else { + CopyGuid (&Entry->DelayedGroupId, DelayedGroupId); + } + + Entry->MicrosecondDelay = Delay; + DelayedDispatchTable->Count++; + + DEBUG ((DEBUG_INFO, "%a Adding dispatch Entry\n", __func__)); + DEBUG ((DEBUG_INFO, " Requested Delay = %d\n", Delay)); + DEBUG ((DEBUG_INFO, " Trigger Time = %d\n", Entry->DispatchTime)); + DEBUG ((DEBUG_INFO, " Context = 0x%016lx\n", Entry->Context)); + DEBUG ((DEBUG_INFO, " Function = %Lx\n", (UINT64)(UINTN)Entry->Function)); + DEBUG ((DEBUG_INFO, " DelayedGroupId = %g\n", &Entry->DelayedGroupId)); + + if (Delay == 0) { + // Force early dispatch point + DelayedDispatchDispatcher (DelayedDispatchTable, NULL); + } + + Status = EFI_SUCCESS; + +Exit: + return Status; +} + +/** + DelayedDispatchDispatcher + + Delayed Dispach cycle (ie one pass) through each entry, calling functions when their + time has expired. When DelayedGroupId is specified, if there are any of the specified entries + in the dispatch queue during dispatch, repeat the DelayedDispatch cycle. + + @param DelayedDispatchTable Pointer to dispatch table + @param OPTIONAL DelayedGroupId used to insure particular time is met. + + @return BOOLEAN +**/ +BOOLEAN +DelayedDispatchDispatcher ( + IN DELAYED_DISPATCH_TABLE *DelayedDispatchTable, + IN EFI_GUID *DelayedGroupId OPTIONAL + ) +{ + BOOLEAN Dispatched; + UINT64 TimeCurrent; + UINT64 MaxDispatchTime; + UINTN Index1; + BOOLEAN DelayedGroupIdPresent; + DELAYED_DISPATCH_ENTRY *Entry; + EFI_STATUS Status; + + Dispatched = FALSE; + DelayedGroupIdPresent = TRUE; + Status = SafeUint64Add (GET_TIME_IN_US (), FixedPcdGet32 (PcdDelayedDispatchCompletionTimeoutUs), &MaxDispatchTime); + if (EFI_ERROR (Status)) { + DEBUG ((DEBUG_ERROR, "%a Delay overflow\n", __func__)); + return FALSE; + } + + while ((DelayedDispatchTable->Count > 0) && (DelayedGroupIdPresent)) { + DelayedGroupIdPresent = FALSE; + DelayedDispatchTable->DispCount++; + + // If dispatching is messed up, clear DelayedDispatchTable and exit. + TimeCurrent = GET_TIME_IN_US (); + if (TimeCurrent > MaxDispatchTime) { + DEBUG ((DEBUG_ERROR, "%a - DelayedDispatch Completion timeout!\n", __func__)); + ReportStatusCode ((EFI_ERROR_MAJOR | EFI_ERROR_CODE), (EFI_SOFTWARE_PEI_CORE | EFI_SW_EC_ABORTED)); + ASSERT (FALSE); + DelayedDispatchTable->Count = 0; + break; + } + + // Check each entry in the table for possible dispatch + for (Index1 = 0; Index1 < DelayedDispatchTable->Count;) { + Entry = &DelayedDispatchTable->Entry[Index1]; + // If DelayedGroupId is present, insure there is an additional check of the table. + if (DelayedGroupId != NULL) { + if (CompareGuid (DelayedGroupId, &Entry->DelayedGroupId)) { + DelayedGroupIdPresent = TRUE; + } + } + + TimeCurrent = GET_TIME_IN_US (); + if (TimeCurrent >= Entry->DispatchTime) { + // Time expired, invoked the function + DEBUG (( + DEBUG_ERROR, + "Delayed dispatch entry %d @ %p, Target=%d, Act=%d Disp=%d\n", + Index1, + Entry->Function, + Entry->DispatchTime, + TimeCurrent, + DelayedDispatchTable->DispCount + )); + Dispatched = TRUE; + Entry->MicrosecondDelay = 0; + Entry->Function ( + &Entry->Context, + &Entry->MicrosecondDelay + ); + DEBUG ((DEBUG_ERROR, "Delayed dispatch Function returned delay=%d\n", Entry->MicrosecondDelay)); + if (Entry->MicrosecondDelay == 0) { + // NewTime = 0 = delete this entry from the table + DelayedDispatchTable->Count--; + CopyMem (Entry, Entry+1, sizeof (DELAYED_DISPATCH_ENTRY) * (DelayedDispatchTable->Count - Index1)); + } else { + if (Entry->MicrosecondDelay > FixedPcdGet32 (PcdDelayedDispatchMaxDelayUs)) { + DEBUG ((DEBUG_ERROR, "%a Illegal new delay %d requested\n", __func__, Entry->MicrosecondDelay)); + ASSERT (FALSE); + Entry->MicrosecondDelay = FixedPcdGet32 (PcdDelayedDispatchMaxDelayUs); + } + + // NewTime != 0 - update the time from us to Dispatch time + Status = SafeUint64Add (GET_TIME_IN_US (), Entry->MicrosecondDelay, &Entry->DispatchTime); + if (EFI_ERROR (Status)) { + DEBUG ((DEBUG_ERROR, "%a Delay overflow, this event will likely never be fired...\n", __func__)); + Entry->DispatchTime = MAX_UINT64; + } + + Index1++; + } + } else { + Index1++; + } + } + } + + return Dispatched; +} + +/** + Wait on a registered Delayed Dispatch unit that has a DelayedGroupId. Continue + to dispatch all registered delayed dispatch entries until *ALL* entries with + DelayedGroupId have completed. + + Example usage: + 1. Register a Delayed Dispatch entry with a DelayedGroupId. + 2. Call this function with the DelayedGroupId + 3. The registered function in #1 will be called after the specified delay. + 4. This function will wait until all entries with the DelayedGroupId have completed. + + @param[in] This The Delayed Dispatch PPI pointer. + @param[in] DelayedGroupId Delayed dispatch request ID the caller will wait on + + @retval EFI_SUCCESS The operation succeeds. + @retval EFI_INVALID_PARAMETER The parameters are invalid. + +**/ +EFI_STATUS +EFIAPI +PeiDelayedDispatchWaitOnEvent ( + IN EFI_DELAYED_DISPATCH_PPI *This, + IN EFI_GUID DelayedGroupId + ) +{ + PERF_FUNCTION_BEGIN (); + EFI_STATUS Status; + DELAYED_DISPATCH_TABLE *DelayedDispatchTable; + + // Get delayed dispatch table + DelayedDispatchTable = GetDelayedDispatchTable (); + if (DelayedDispatchTable == NULL) { + DEBUG ((DEBUG_ERROR, "%a Unable to locate dispatch table\n", __func__)); + Status = EFI_UNSUPPORTED; + goto Exit; + } + + if (IsZeroGuid (&DelayedGroupId)) { + DEBUG ((DEBUG_ERROR, "%a Delayed Group ID is a null GUID\n", __func__)); + Status = EFI_UNSUPPORTED; + goto Exit; + } + + DEBUG ((DEBUG_INFO, "Delayed dispatch on %g. Count=%d, DispatchCount=%d\n", &DelayedGroupId, DelayedDispatchTable->Count, DelayedDispatchTable->DispCount)); + PERF_EVENT_SIGNAL_BEGIN (&DelayedGroupId); + DelayedDispatchDispatcher (DelayedDispatchTable, &DelayedGroupId); + PERF_EVENT_SIGNAL_END (&DelayedGroupId); + + Status = EFI_SUCCESS; + +Exit: + PERF_FUNCTION_END (); + return Status; +} + /** + DelayedDispatch End of PEI callback function. Insure that all of the delayed dispatch + entries are complete before exiting PEI. + + @param[in] PeiServices - Pointer to PEI Services Table. + @param[in] NotifyDesc - Pointer to the descriptor for the Notification event that + caused this function to execute. + @param[in] Ppi - Pointer to the PPI data associated with this function. + + @retval EFI_STATUS - Always return EFI_SUCCESS +**/ +EFI_STATUS +EFIAPI +PeiDelayedDispatchOnEndOfPei ( + IN EFI_PEI_SERVICES **PeiServices, + IN EFI_PEI_NOTIFY_DESCRIPTOR *NotifyDesc, + IN VOID *Ppi + ) +{ + DELAYED_DISPATCH_TABLE *DelayedDispatchTable; + + // Get delayed dispatch table + DelayedDispatchTable = GetDelayedDispatchTable (); + if (DelayedDispatchTable == NULL) { + DEBUG ((DEBUG_ERROR, "%a Unable to locate dispatch table\n", __func__)); + return EFI_UNSUPPORTED; + } + + PERF_INMODULE_BEGIN ("PerfDelayedDispatchEndOfPei"); + while (DelayedDispatchTable->Count > 0) { + DelayedDispatchDispatcher (DelayedDispatchTable, NULL); + } + + DEBUG ((DEBUG_ERROR, "%a Count of dispatch cycles is %d\n", __func__, DelayedDispatchTable->DispCount)); + PERF_INMODULE_END ("PerfDelayedDispatchEndOfPei"); + return EFI_SUCCESS; +} + +/** Discover all PEIMs and optional Apriori file in one FV. There is at most one Apriori file in one FV. @@ -347,7 +715,7 @@ PeiLoadFixAddressHook ( // Note: Here is a assumption that system memory should always be healthy even without test. // if ((NextResourceHob->ResourceType == EFI_RESOURCE_SYSTEM_MEMORY) && - (((NextResourceHob->ResourceAttribute^ResourceHob->ResourceAttribute)&(~EFI_RESOURCE_ATTRIBUTE_TESTED)) == 0)) + (((NextResourceHob->ResourceAttribute^ResourceHob->ResourceAttribute) & (~EFI_RESOURCE_ATTRIBUTE_TESTED)) == 0)) { // // See if the memory range described in ResourceHob and NextResourceHob is adjacent @@ -1426,12 +1794,38 @@ PeiDispatcher ( EFI_PEI_FILE_HANDLE SaveCurrentFileHandle; EFI_FV_FILE_INFO FvFileInfo; PEI_CORE_FV_HANDLE *CoreFvHandle; + EFI_HOB_GUID_TYPE *GuidHob; + UINT32 TableSize; PeiServices = (CONST EFI_PEI_SERVICES **)&Private->Ps; PeimEntryPoint = NULL; PeimFileHandle = NULL; EntryPoint = 0; + if (Private->DelayedDispatchTable == NULL) { + GuidHob = GetFirstGuidHob (&gEfiDelayedDispatchTableGuid); + if (GuidHob != NULL) { + Private->DelayedDispatchTable = (DELAYED_DISPATCH_TABLE *)(GET_GUID_HOB_DATA (GuidHob)); + } else { + TableSize = sizeof (DELAYED_DISPATCH_TABLE) + ((DELAYED_DISPATCH_MAX_ENTRIES - 1) * sizeof (DELAYED_DISPATCH_ENTRY)); + Private->DelayedDispatchTable = BuildGuidHob (&gEfiDelayedDispatchTableGuid, TableSize); + if (Private->DelayedDispatchTable != NULL) { + ZeroMem (Private->DelayedDispatchTable, TableSize); + Status = PeiServicesInstallPpi (&mDelayedDispatchDesc); + if (EFI_ERROR (Status)) { + DEBUG ((DEBUG_ERROR, "%a Failed to install Delayed Dispatch PPI: %r!\n", __func__, Status)); + ASSERT_EFI_ERROR (Status); + } else { + Status = PeiServicesNotifyPpi (&mDelayedDispatchNotifyDesc); + if (EFI_ERROR (Status)) { + DEBUG ((DEBUG_ERROR, "%a Failed to notify Delayed Dispatch on End of Pei: %r!\n", __func__, Status)); + ASSERT_EFI_ERROR (Status); + } + } + } + } + } + if ((Private->PeiMemoryInstalled) && (PcdGetBool (PcdMigrateTemporaryRamFirmwareVolumes) || (Private->HobList.HandoffInformationTable->BootMode != BOOT_ON_S3_RESUME) || @@ -1682,6 +2076,13 @@ PeiDispatcher ( } } } + + // Dispatch pending delalyed dispatch requests + if (Private->DelayedDispatchTable != NULL) { + if (DelayedDispatchDispatcher (Private->DelayedDispatchTable, NULL)) { + ProcessDispatchNotifyList (Private); + } + } } // @@ -1708,7 +2109,10 @@ PeiDispatcher ( // pass. If we did not dispatch a PEIM/FV there is no point in trying again // as it will fail the next time too (nothing has changed). // - } while (Private->PeimNeedingDispatch && Private->PeimDispatchOnThisPass); + // Also continue dispatch loop if there are outstanding delay- + // dispatch registrations still running. + } while ((Private->PeimNeedingDispatch && Private->PeimDispatchOnThisPass) || + (Private->DelayedDispatchTable->Count > 0)); } /** diff --git a/MdeModulePkg/Core/Pei/Memory/MemoryServices.c b/MdeModulePkg/Core/Pei/Memory/MemoryServices.c index 59613e5131c3..562092df7094 100644 --- a/MdeModulePkg/Core/Pei/Memory/MemoryServices.c +++ b/MdeModulePkg/Core/Pei/Memory/MemoryServices.c @@ -555,6 +555,7 @@ PeiAllocatePages ( EFI_PHYSICAL_ADDRESS *FreeMemoryTop; EFI_PHYSICAL_ADDRESS *FreeMemoryBottom; UINTN RemainingPages; + UINTN RemainingMemory; UINTN Granularity; UINTN Padding; @@ -636,24 +637,18 @@ PeiAllocatePages ( // // Verify that there is sufficient memory to satisfy the allocation. // - RemainingPages = (UINTN)(*FreeMemoryTop - *FreeMemoryBottom) >> EFI_PAGE_SHIFT; + RemainingMemory = (UINTN)(*FreeMemoryTop - *FreeMemoryBottom); + RemainingPages = (UINTN)(RShiftU64 (RemainingMemory, EFI_PAGE_SHIFT)); // - // The number of remaining pages needs to be greater than or equal to that of the request pages. + // The number of remaining pages needs to be greater than or equal to that of + // the request pages. In addition, there should be enough space left to hold a + // Memory Allocation HOB. // Pages = ALIGN_VALUE (Pages, EFI_SIZE_TO_PAGES (Granularity)); - if (RemainingPages < Pages) { - // - // Try to find free memory by searching memory allocation HOBs. - // - Status = FindFreeMemoryFromMemoryAllocationHob (MemoryType, Pages, Granularity, Memory); - if (!EFI_ERROR (Status)) { - return Status; - } - - DEBUG ((DEBUG_ERROR, "AllocatePages failed: No 0x%lx Pages is available.\n", (UINT64)Pages)); - DEBUG ((DEBUG_ERROR, "There is only left 0x%lx pages memory resource to be allocated.\n", (UINT64)RemainingPages)); - return EFI_OUT_OF_RESOURCES; - } else { + if ((RemainingPages > Pages) || + ((RemainingPages == Pages) && + ((RemainingMemory & EFI_PAGE_MASK) >= sizeof (EFI_HOB_MEMORY_ALLOCATION)))) + { // // Update the PHIT to reflect the memory usage // @@ -674,6 +669,18 @@ PeiAllocatePages ( ); return EFI_SUCCESS; + } else { + // + // Try to find free memory by searching memory allocation HOBs. + // + Status = FindFreeMemoryFromMemoryAllocationHob (MemoryType, Pages, Granularity, Memory); + if (!EFI_ERROR (Status)) { + return Status; + } + + DEBUG ((DEBUG_ERROR, "AllocatePages failed: No 0x%lx Pages is available.\n", (UINT64)Pages)); + DEBUG ((DEBUG_ERROR, "There is only left 0x%lx pages memory resource to be allocated.\n", (UINT64)RemainingPages)); + return EFI_OUT_OF_RESOURCES; } } diff --git a/MdeModulePkg/Core/Pei/PeiMain.h b/MdeModulePkg/Core/Pei/PeiMain.h index 8df0c2d561f7..3f73da01f41b 100644 --- a/MdeModulePkg/Core/Pei/PeiMain.h +++ b/MdeModulePkg/Core/Pei/PeiMain.h @@ -11,6 +11,8 @@ SPDX-License-Identifier: BSD-2-Clause-Patent #include #include +#include +#include #include #include #include @@ -42,10 +44,13 @@ SPDX-License-Identifier: BSD-2-Clause-Patent #include #include #include +#include +#include #include #include #include #include +#include /// /// It is an FFS type extension used for PeiFindFileEx. It indicates current @@ -208,6 +213,23 @@ EFI_STATUS #define PEI_CORE_HANDLE_SIGNATURE SIGNATURE_32('P','e','i','C') +// +// Converts elapsed ticks of performance counter to time in microseconds. +// This macro converts the elapsed ticks of running performance counter to +// time value in unit of microseconds. +// +// NOTE: To support Delayed Dispatch functionality, the timer ticks are required +// to be: +// 1. A 64bit register; +// 2. Guaranteed to be monotonically increasing from 0; +// 3. Not wrapped throughout the duration of a boot; +// +// The requirement above is set to avoid the timer overflow issue to keep the +// Delayed Dispatch meet the PI specification with minimal change (instead of +// implementing a control-yielding multi-threaded PEI core). +// +#define GET_TIME_IN_US() ((UINT32)DivU64x32(GetTimeInNanoSecond(GetPerformanceCounter ()), 1000)) + /// /// Pei Core private data structure instance /// @@ -308,6 +330,11 @@ struct _PEI_CORE_INSTANCE { // Those Memory Range will be migrated into physical memory. // HOLE_MEMORY_DATA HoleData[HOLE_MAX_NUMBER]; + + // + // Table of delayed dispatch requests + // + DELAYED_DISPATCH_TABLE *DelayedDispatchTable; }; /// @@ -2028,4 +2055,47 @@ PeiReinitializeFv ( IN PEI_CORE_INSTANCE *PrivateData ); +/** + Register a callback to be called after a minimum delay has occurred. + + @param[in] This Pointer to the EFI_DELAYED_DISPATCH_PPI instance + @param[in] Function Function to call back + @param[in] Context Context data + @param[in] DelayedGroupId Delayed dispatch request ID the caller will wait on + @param[in] Delay Delay interval + + @retval EFI_SUCCESS Function successfully loaded + @retval EFI_INVALID_PARAMETER One of the Arguments is not supported + @retval EFI_OUT_OF_RESOURCES No more entries + +**/ +EFI_STATUS +EFIAPI +PeiDelayedDispatchRegister ( + IN EFI_DELAYED_DISPATCH_PPI *This, + IN EFI_DELAYED_DISPATCH_FUNCTION Function, + IN UINT64 Context, + IN EFI_GUID *DelayedGroupId OPTIONAL, + IN UINT32 Delay + ); + +/** + Wait on a registered Delayed Dispatch unit that has a DelayedGroupId. Continue + to dispatch all registered delayed dispatch entries until *ALL* entries with + DelayedGroupId have completed. + + @param[in] This The Delayed Dispatch PPI pointer. + @param[in] DelayedGroupId Delayed dispatch request ID the caller will wait on + + @retval EFI_SUCCESS Function successfully invoked + @retval EFI_INVALID_PARAMETER One of the Arguments is not supported + +**/ +EFI_STATUS +EFIAPI +PeiDelayedDispatchWaitOnEvent ( + IN EFI_DELAYED_DISPATCH_PPI *This, + IN EFI_GUID DelayedGroupId + ); + #endif diff --git a/MdeModulePkg/Core/Pei/PeiMain.inf b/MdeModulePkg/Core/Pei/PeiMain.inf index 4e545ddab2ab..4cd58ee3aaee 100644 --- a/MdeModulePkg/Core/Pei/PeiMain.inf +++ b/MdeModulePkg/Core/Pei/PeiMain.inf @@ -66,6 +66,8 @@ PeCoffLib PeiServicesTablePointerLib PcdLib + TimerLib + SafeIntLib [Guids] gPeiAprioriFileNameGuid ## SOMETIMES_CONSUMES ## File @@ -79,6 +81,7 @@ gStatusCodeCallbackGuid gEdkiiMigratedFvInfoGuid ## SOMETIMES_PRODUCES ## HOB gEdkiiMigrationInfoGuid ## SOMETIMES_CONSUMES ## HOB + gEfiDelayedDispatchTableGuid ## SOMETIMES_PRODUCES ## HOB [Ppis] gEfiPeiStatusCodePpiGuid ## SOMETIMES_CONSUMES # PeiReportStatusService is not ready if this PPI doesn't exist @@ -102,6 +105,8 @@ gEfiSecHobDataPpiGuid ## SOMETIMES_CONSUMES gEfiPeiCoreFvLocationPpiGuid ## SOMETIMES_CONSUMES gEdkiiPeiMigrateTempRamPpiGuid ## PRODUCES + gEfiPeiDelayedDispatchPpiGuid ## PRODUCES + gEfiEndOfPeiSignalPpiGuid ## CONSUMES [Pcd] gEfiMdeModulePkgTokenSpaceGuid.PcdPeiCoreMaxPeiStackSize ## CONSUMES @@ -114,6 +119,8 @@ gEfiMdeModulePkgTokenSpaceGuid.PcdShadowPeimOnBoot ## CONSUMES gEfiMdeModulePkgTokenSpaceGuid.PcdInitValueInTempStack ## CONSUMES gEfiMdeModulePkgTokenSpaceGuid.PcdMigrateTemporaryRamFirmwareVolumes ## CONSUMES + gEfiMdeModulePkgTokenSpaceGuid.PcdDelayedDispatchMaxDelayUs ## CONSUMES + gEfiMdeModulePkgTokenSpaceGuid.PcdDelayedDispatchCompletionTimeoutUs ## CONSUMES # [BootMode] # S3_RESUME ## SOMETIMES_CONSUMES diff --git a/MdeModulePkg/Core/Pei/PeiMain/PeiMain.c b/MdeModulePkg/Core/Pei/PeiMain/PeiMain.c index 61f5699e1f27..ff65e69f520c 100644 --- a/MdeModulePkg/Core/Pei/PeiMain/PeiMain.c +++ b/MdeModulePkg/Core/Pei/PeiMain/PeiMain.c @@ -282,6 +282,9 @@ PeiCore ( OldCoreData->TempFileHandles = (EFI_PEI_FILE_HANDLE *)((UINT8 *)OldCoreData->TempFileHandles - OldCoreData->HeapOffset); } + // Force relocating the dispatch table + OldCoreData->DelayedDispatchTable = NULL; + // // Fixup for PeiService's address // diff --git a/MdeModulePkg/Include/Guid/DelayedDispatch.h b/MdeModulePkg/Include/Guid/DelayedDispatch.h new file mode 100644 index 000000000000..9be5444e3600 --- /dev/null +++ b/MdeModulePkg/Include/Guid/DelayedDispatch.h @@ -0,0 +1,47 @@ +/** @file + Definition for structure & defines exported by Delayed Dispatch PPI + + Copyright (c), Microsoft Corporation. + + SPDX-License-Identifier: BSD-2-Clause-Patent + +**/ + +#ifndef DELAYED_DISPATCH_H_ +#define DELAYED_DISPATCH_H_ + +// Delayed Dispatch table GUID +#define EFI_DELAYED_DISPATCH_TABLE_GUID {\ + 0x4b733449, 0x8eff, 0x488c, { 0x92, 0x1a, 0x15, 0x4a, 0xda, 0x25, 0x18, 0x07 } \ + } + +// +// Maximal number of Delayed Dispatch entries supported +// +#define DELAYED_DISPATCH_MAX_ENTRIES 8 + +// +// Internal structure for delayed dispatch entries. +// Packing the structures here to save space as they will be stored as HOBs. +// +#pragma pack (push, 1) + +typedef struct { + EFI_GUID DelayedGroupId; + UINT64 Context; + EFI_DELAYED_DISPATCH_FUNCTION Function; + UINT64 DispatchTime; + UINT32 MicrosecondDelay; +} DELAYED_DISPATCH_ENTRY; + +typedef struct { + UINT32 Count; + UINT32 DispCount; + DELAYED_DISPATCH_ENTRY Entry[DELAYED_DISPATCH_MAX_ENTRIES]; +} DELAYED_DISPATCH_TABLE; + +#pragma pack (pop) + +extern EFI_GUID gEfiDelayedDispatchTableGuid; + +#endif diff --git a/MdeModulePkg/Include/Ppi/UfsHostControllerPlatformPpi.h b/MdeModulePkg/Include/Ppi/UfsHostControllerPlatformPpi.h new file mode 100644 index 000000000000..9384a4e4c63a --- /dev/null +++ b/MdeModulePkg/Include/Ppi/UfsHostControllerPlatformPpi.h @@ -0,0 +1,97 @@ +/** @file + EDKII_UFS_HC_PLATFORM_PPI definition. + +Copyright (c) 2024, American Megatrends International LLC. All rights reserved.
+SPDX-License-Identifier: BSD-2-Clause-Patent + +**/ + +#ifndef _EDKII_PEI_UFS_HC_PLATFORM_PPI_H_ +#define _EDKII_PEI_UFS_HC_PLATFORM_PPI_H_ + +#define EDKII_UFS_HC_PLATFORM_PPI_VERSION 1 + +extern EFI_GUID gEdkiiUfsHcPlatformPpiGuid; + +/// +/// Forward declaration for the UFS_HOST_CONTROLLER_PPI. +/// +typedef struct _EDKII_UFS_HC_PLATFORM_PPI EDKII_UFS_HC_PLATFORM_PPI; + +typedef struct { + UINT32 Capabilities; + UINT32 Version; +} EDKII_UFS_HC_INFO; + +/** + Allows platform PPI to override host controller information + + @param[in] ControllerHandle Handle of the UFS controller. + @param[in, out] HcInfo Pointer EDKII_UFS_HC_INFO associated with host controller. + + @retval EFI_SUCCESS Function completed successfully. + @retval EFI_INVALID_PARAMETER HcInfo is NULL. + @retval Others Function failed to complete. +**/ +typedef +EFI_STATUS +(EFIAPI *EDKII_UFS_HC_PLATFORM_OVERRIDE_HC_INFO)( + IN EFI_HANDLE ControllerHandle, + IN OUT EDKII_UFS_HC_INFO *HcInfo + ); + +typedef enum { + EdkiiUfsHcPreHce, + EdkiiUfsHcPostHce, + EdkiiUfsHcPreLinkStartup, + EdkiiUfsHcPostLinkStartup +} EDKII_UFS_HC_PLATFORM_CALLBACK_PHASE; + +typedef enum { + EdkiiUfsCardRefClkFreq19p2Mhz, + EdkiiUfsCardRefClkFreq26Mhz, + EdkiiUfsCardRefClkFreq38p4Mhz, + EdkiiUfsCardRefClkFreqObsolete +} EDKII_UFS_CARD_REF_CLK_FREQ_ATTRIBUTE; + +/** + Callback function for platform driver. + + @param[in] UfsHcBaseddr The pointer to UfsHcBase address. + @param[in] CallbackPhase Specifies when the platform ppi is called + + @retval EFI_SUCCESS Override function completed successfully. + @retval EFI_INVALID_PARAMETER CallbackPhase is invalid or CallbackData is NULL when phase expects valid data. + @retval Others Function failed to complete. +**/ +typedef +EFI_STATUS +(EFIAPI *EDKII_UFS_HC_PLATFORM_PEI_CALLBACK)( + IN UINTN *UfsHcBaseAddr, + IN EDKII_UFS_HC_PLATFORM_CALLBACK_PHASE CallbackPhase + ); + +/// +/// This PPI contains a set of services to interact with the UFS host controller. +/// +struct _EDKII_UFS_HC_PLATFORM_PPI { + /// + /// Version of the PPI. + /// + UINT32 Version; + /// + /// Allows platform driver to override host controller information. + /// + EDKII_UFS_HC_PLATFORM_OVERRIDE_HC_INFO OverrideHcInfo; + /// + /// Allows platform driver to implement platform specific flows + /// for host controller. + /// + EDKII_UFS_HC_PLATFORM_PEI_CALLBACK Callback; + /// + /// Reference Clock Frequency Ufs Card Attribute that need to be set in this Ufs Host Environment. + /// + EDKII_UFS_CARD_REF_CLK_FREQ_ATTRIBUTE RefClkFreq; +}; + +#endif diff --git a/MdeModulePkg/Include/Protocol/UsbEthernetProtocol.h b/MdeModulePkg/Include/Protocol/UsbEthernetProtocol.h index 250de0b59110..43ccca398f1d 100644 --- a/MdeModulePkg/Include/Protocol/UsbEthernetProtocol.h +++ b/MdeModulePkg/Include/Protocol/UsbEthernetProtocol.h @@ -28,10 +28,6 @@ typedef struct _EDKII_USB_ETHERNET_PROTOCOL EDKII_USB_ETHERNET_PROTOCOL; #define USB_RNDIS_SUBCLASS 0x04 #define USB_RNDIS_ETHERNET_PROTOCOL 0x01 -// Type Values for the DescriptorType Field -#define CS_INTERFACE 0x24 -#define CS_ENDPOINT 0x25 - // Descriptor SubType in Functional Descriptors #define HEADER_FUN_DESCRIPTOR 0x00 #define UNION_FUN_DESCRIPTOR 0x06 diff --git a/MdeModulePkg/Library/UefiBootManagerLib/BmBootDescription.c b/MdeModulePkg/Library/UefiBootManagerLib/BmBootDescription.c index 030b2ee3ec25..435d57bdaef5 100644 --- a/MdeModulePkg/Library/UefiBootManagerLib/BmBootDescription.c +++ b/MdeModulePkg/Library/UefiBootManagerLib/BmBootDescription.c @@ -17,6 +17,64 @@ SPDX-License-Identifier: BSD-2-Clause-Patent CONST UINT16 mBmUsbLangId = 0x0409; // English CHAR16 mBmUefiPrefix[] = L"UEFI "; +CHAR16 mBootDescGenericManufacturer[] = L"Generic"; +CHAR16 mBootDescSd[] = L"SD Device"; +CHAR16 mBootDescEmmc[] = L"eMMC Device"; +CHAR16 mBootDescEmmcUserData[] = L"eMMC User Data"; +CHAR16 mBootDescEmmcBoot1[] = L"eMMC Boot 1"; +CHAR16 mBootDescEmmcBoot2[] = L"eMMC Boot 2"; +CHAR16 mBootDescEmmcGp1[] = L"eMMC GP 1"; +CHAR16 mBootDescEmmcGp2[] = L"eMMC GP 2"; +CHAR16 mBootDescEmmcGp3[] = L"eMMC GP 3"; +CHAR16 mBootDescEmmcGp4[] = L"eMMC GP 4"; + +typedef struct { + UINT8 Id; + CHAR16 *Name; +} BM_SDMMC_MANUFACTURER; + +BM_SDMMC_MANUFACTURER mSdManufacturers[] = { + { 0x01, L"Panasonic" }, + { 0x02, L"Toshiba/Kingston/Viking" }, + { 0x03, L"SanDisk" }, + { 0x08, L"Silicon Power" }, + { 0x18, L"Infineon" }, + { 0x1b, L"Transcend/Samsung" }, + { 0x1c, L"Transcend" }, + { 0x1d, L"Corsair/AData" }, + { 0x1e, L"Transcend" }, + { 0x1f, L"Kingston" }, + { 0x27, L"Delkin/Phison" }, + { 0x28, L"Lexar" }, + { 0x30, L"SanDisk" }, + { 0x31, L"Silicon Power" }, + { 0x33, L"STMicroelectronics" }, + { 0x41, L"Kingston" }, + { 0x6f, L"STMicroelectronics" }, + { 0x74, L"Transcend" }, + { 0x76, L"Patriot" }, + { 0x82, L"Gobe/Sony" }, + { 0x9c, L"Angelbird/Hoodman" }, +}; + +BM_SDMMC_MANUFACTURER mMmcManufacturers[] = { + { 0x00, L"SanDisk" }, + { 0x02, L"Kingston/SanDisk" }, + { 0x03, L"Toshiba" }, + { 0x11, L"Toshiba" }, + { 0x13, L"Micron" }, + { 0x15, L"Samsung" }, + { 0x37, L"KingMax" }, + { 0x44, L"ATP" }, + { 0x45, L"SanDisk" }, + { 0x2c, L"Kingston" }, + { 0x70, L"Kingston" }, + { 0x88, L"Foresee" }, + { 0x9b, L"YMTC" }, + { 0xd6, L"Foresee" }, + { 0xfe, L"Micron" }, +}; + LIST_ENTRY mPlatformBootDescriptionHandlers = INITIALIZE_LIST_HEAD_VARIABLE (mPlatformBootDescriptionHandlers); /** @@ -127,6 +185,150 @@ BmEliminateExtraSpaces ( Str[ActualIndex] = L'\0'; } +/** + Swap a byte array. + + @param Source Input byte array. + @param Length The size of Source in bytes. +**/ +VOID +BmSwapBytes ( + IN UINT8 *Source, + IN UINTN Length + ) +{ + UINTN Index; + UINT8 Temp; + UINTN Count; + + Count = Length / 2; + for (Index = 0; Index < Count; ++Index) { + Temp = Source[Index]; + Source[Index] = Source[Length - 1 - Index]; + Source[Length - 1 - Index] = Temp; + } +} + +/** + Get the SD/MMC manufacturer name from an ID. + + @param Id Manufacturer ID. + @param IsMmc Boolean indicating whether the ID is for SD or eMMC. + + @return The manufacturer string. +**/ +CHAR16 * +BmGetSdMmcManufacturerName ( + IN UINT8 Id, + IN BOOLEAN IsMmc + ) +{ + BM_SDMMC_MANUFACTURER *List; + UINT8 Count; + UINTN Index; + + List = IsMmc ? mMmcManufacturers : mSdManufacturers; + Count = IsMmc ? ARRAY_SIZE (mMmcManufacturers) + : ARRAY_SIZE (mSdManufacturers); + + for (Index = 0; Index < Count; ++Index) { + if (List[Index].Id == Id) { + return List[Index].Name; + } + } + + return mBootDescGenericManufacturer; +} + +/** + Get the eMMC partition type from a controller path. + + @param DevicePath Pointer to a CONTROLLER_DEVICE_PATH. + + @return The description string. +**/ +CHAR16 * +BmGetEmmcTypeDescription ( + CONTROLLER_DEVICE_PATH *DevicePath + ) +{ + switch (DevicePath->ControllerNumber) { + case EmmcPartitionUserData: + return mBootDescEmmcUserData; + case EmmcPartitionBoot1: + return mBootDescEmmcBoot1; + case EmmcPartitionBoot2: + return mBootDescEmmcBoot2; + case EmmcPartitionGP1: + return mBootDescEmmcGp1; + case EmmcPartitionGP2: + return mBootDescEmmcGp2; + case EmmcPartitionGP3: + return mBootDescEmmcGp3; + case EmmcPartitionGP4: + return mBootDescEmmcGp4; + default: + break; + } + + return mBootDescEmmc; +} + +/** + Get an SD/MMC boot description. + + @param ManufacturerName Manufacturer name string. + @param ProductName Product name from CID. + @param ProductNameLength Length of ProductName. + @param SerialNumber Serial number from CID. + @param DeviceType Device type string (e.g. SD or an eMMC partition). + + @return The description string. +**/ +CHAR16 * +BmGetSdMmcDescription ( + IN CHAR16 *ManufacturerName, + IN UINT8 *ProductName, + IN UINT8 ProductNameLength, + IN UINT8 SerialNumber[4], + IN CHAR16 *DeviceType + ) +{ + CHAR16 *Desc; + UINTN DescSize; + + DescSize = StrSize (ManufacturerName) - sizeof (CHAR16) // "Samsung" + + sizeof (CHAR16) // " " + + ProductNameLength * sizeof (CHAR16) // "BJTD4R" + + sizeof (CHAR16) // " " + + sizeof (UINT32) * 2 * sizeof (CHAR16) // "00000000" + + sizeof (CHAR16) // " " + + StrSize (DeviceType); // "eMMC User Data\0" + + Desc = AllocateZeroPool (DescSize); + if (Desc == NULL) { + return NULL; + } + + BmSwapBytes (ProductName, ProductNameLength); + + UnicodeSPrint ( + Desc, + DescSize, + L"%s %.*a %02x%02x%02x%02x %s", + ManufacturerName, + ProductNameLength, + ProductName, + SerialNumber[0], + SerialNumber[1], + SerialNumber[2], + SerialNumber[3], + DeviceType + ); + + return Desc; +} + /** Try to get the controller's ATA/ATAPI description. @@ -145,6 +347,8 @@ BmGetDescriptionFromDiskInfo ( UINT32 BufferSize; EFI_ATAPI_IDENTIFY_DATA IdentifyData; EFI_SCSI_INQUIRY_DATA InquiryData; + SD_CID SdCid; + EMMC_CID EmmcCid; CHAR16 *Description; UINTN Length; CONST UINTN ModelNameLength = 40; @@ -245,9 +449,40 @@ BmGetDescriptionFromDiskInfo ( } if (DevicePathSubType (DevicePath) == MSG_SD_DP) { - Description = L"SD Device"; + BufferSize = sizeof (SD_CID); + Status = DiskInfo->Inquiry (DiskInfo, &SdCid, &BufferSize); + if (EFI_ERROR (Status)) { + return NULL; + } + + Description = BmGetSdMmcDescription ( + BmGetSdMmcManufacturerName (SdCid.ManufacturerId, FALSE), + SdCid.ProductName, + ARRAY_SIZE (SdCid.ProductName), + SdCid.ProductSerialNumber, + mBootDescSd + ); } else if (DevicePathSubType (DevicePath) == MSG_EMMC_DP) { - Description = L"eMMC Device"; + BufferSize = sizeof (EMMC_CID); + Status = DiskInfo->Inquiry (DiskInfo, &EmmcCid, &BufferSize); + if (EFI_ERROR (Status)) { + return NULL; + } + + Description = mBootDescEmmc; + + DevicePath = NextDevicePathNode (DevicePath); + if (DevicePath->SubType == HW_CONTROLLER_DP) { + Description = BmGetEmmcTypeDescription ((CONTROLLER_DEVICE_PATH *)DevicePath); + } + + Description = BmGetSdMmcDescription ( + BmGetSdMmcManufacturerName (EmmcCid.ManufacturerId, TRUE), + EmmcCid.ProductName, + ARRAY_SIZE (EmmcCid.ProductName), + EmmcCid.ProductSerialNumber, + Description + ); } else { return NULL; } diff --git a/MdeModulePkg/Library/UefiBootManagerLib/InternalBm.h b/MdeModulePkg/Library/UefiBootManagerLib/InternalBm.h index b7dfe2a7e0bd..76ee0a83bf20 100644 --- a/MdeModulePkg/Library/UefiBootManagerLib/InternalBm.h +++ b/MdeModulePkg/Library/UefiBootManagerLib/InternalBm.h @@ -18,6 +18,8 @@ SPDX-License-Identifier: BSD-2-Clause-Patent #include #include #include +#include +#include #include #include diff --git a/MdeModulePkg/Library/VariablePolicyLib/VariablePolicyLib.c b/MdeModulePkg/Library/VariablePolicyLib/VariablePolicyLib.c index 053b48d90e4d..f5b9418a3834 100644 --- a/MdeModulePkg/Library/VariablePolicyLib/VariablePolicyLib.c +++ b/MdeModulePkg/Library/VariablePolicyLib/VariablePolicyLib.c @@ -918,7 +918,7 @@ GetLockOnVariableStateVariablePolicyInfo ( LocalLockOnVarStatePolicy = (VARIABLE_LOCK_ON_VAR_STATE_POLICY *)(MatchPolicy + 1); CopyMem (VariablePolicy, LocalLockOnVarStatePolicy, sizeof (*LocalLockOnVarStatePolicy)); - if ((VariableLockPolicyVariableNameBufferSize == NULL)) { + if (VariableLockPolicyVariableNameBufferSize == NULL) { if (VariableLockPolicyVariableName != NULL) { return EFI_INVALID_PARAMETER; } diff --git a/MdeModulePkg/MdeModulePkg.dec b/MdeModulePkg/MdeModulePkg.dec index 1324b6d1000c..b9bc7041f2ca 100644 --- a/MdeModulePkg/MdeModulePkg.dec +++ b/MdeModulePkg/MdeModulePkg.dec @@ -488,6 +488,9 @@ ## Include/Guid/MmCommBuffer.h gMmCommBufferHobGuid = { 0x6c2a2520, 0x0131, 0x4aee, { 0xa7, 0x50, 0xcc, 0x38, 0x4a, 0xac, 0xe8, 0xc6 }} + ## Include/Guid/DelayedDispatch.h + gEfiDelayedDispatchTableGuid = { 0x4b733449, 0x8eff, 0x488c, { 0x92, 0x1a, 0x15, 0x4a, 0xda, 0x25, 0x18, 0x07 }} + [Ppis] ## Include/Ppi/FirmwareVolumeShadowPpi.h gEdkiiPeiFirmwareVolumeShadowPpiGuid = { 0x7dfe756c, 0xed8d, 0x4d77, {0x9e, 0xc4, 0x39, 0x9a, 0x8a, 0x81, 0x51, 0x16 } } @@ -528,6 +531,9 @@ ## Include/Ppi/UfsHostController.h gEdkiiPeiUfsHostControllerPpiGuid = { 0xdc54b283, 0x1a77, 0x4cd6, { 0x83, 0xbb, 0xfd, 0xda, 0x46, 0x9a, 0x2e, 0xc6 }} + ## Include/Ppi/UfsHostControllerPlatformPpi.h + gEdkiiUfsHcPlatformPpiGuid = { 0x9e2bde17, 0x7df0, 0x42ea, {0x98, 0xa3, 0xf6, 0x9a, 0xf3, 0xfb, 0x2b, 0xb9 }} + ## Include/Ppi/IpmiPpi.h gPeiIpmiPpiGuid = { 0xa9731431, 0xd968, 0x4277, { 0xb7, 0x52, 0xa3, 0xa9, 0xa6, 0xae, 0x18, 0x98 }} @@ -1041,6 +1047,14 @@ # @ValidList 0x80000006 | 0x03058002 gEfiMdeModulePkgTokenSpaceGuid.PcdErrorCodeSetVariable|0x03058002|UINT32|0x30001040 + ## Delayed Dispatch Maximum Delay in us (microseconds) + # Maximum delay for any particular delay request - 5 seconds + gEfiMdeModulePkgTokenSpaceGuid.PcdDelayedDispatchMaxDelayUs|5000000|UINT32|0x3000104A + + ## Delayed Dispatch timeout in us (microseconds) + # Maximum delay when waiting for completion (ie EndOfPei) - 10 seconds + gEfiMdeModulePkgTokenSpaceGuid.PcdDelayedDispatchCompletionTimeoutUs|10000000|UINT32|0x3000104B + ## Mask to control the NULL address detection in code for different phases. # If enabled, accessing NULL address in UEFI or SMM code can be caught.

# BIT0 - Enable NULL pointer detection for UEFI.
diff --git a/MdeModulePkg/Universal/Console/TerminalDxe/TerminalConIn.c b/MdeModulePkg/Universal/Console/TerminalDxe/TerminalConIn.c index dd313474027c..f1d0a3466e95 100644 --- a/MdeModulePkg/Universal/Console/TerminalDxe/TerminalConIn.c +++ b/MdeModulePkg/Universal/Console/TerminalDxe/TerminalConIn.c @@ -97,6 +97,9 @@ TerminalConInReset ( if (!EFI_ERROR (Status)) { Status = TerminalDevice->SerialIo->SetControl (TerminalDevice->SerialIo, EFI_SERIAL_DATA_TERMINAL_READY|EFI_SERIAL_REQUEST_TO_SEND); + if (Status == EFI_UNSUPPORTED) { + Status = EFI_SUCCESS; + } } return Status; diff --git a/MdeModulePkg/Universal/HiiDatabaseDxe/Database.c b/MdeModulePkg/Universal/HiiDatabaseDxe/Database.c index 0b09c24d52a4..ac0cb7e77374 100644 --- a/MdeModulePkg/Universal/HiiDatabaseDxe/Database.c +++ b/MdeModulePkg/Universal/HiiDatabaseDxe/Database.c @@ -564,6 +564,45 @@ IsEfiVarStoreQuestion ( return EfiVarStoreNumber; } +/** + Find the matched variable from the input variable storage. + + @param[in] VariableStorage Point to the variable storage header. + @param[in] VarGuid A unique identifier for the variable. + @param[in] VarAttribute The attributes bitmask for the variable. + @param[in] VarName A Null-terminated ascii string that is the name of the variable. + + @return Pointer to the matched variable header or NULL if not found. +**/ +AUTHENTICATED_VARIABLE_HEADER * +AuthFindVariableData ( + IN VARIABLE_STORE_HEADER *VariableStorage, + IN EFI_GUID *VarGuid, + IN UINT32 VarAttribute, + IN CHAR16 *VarName + ) +{ + AUTHENTICATED_VARIABLE_HEADER *VariableHeader; + AUTHENTICATED_VARIABLE_HEADER *VariableEnd; + + VariableEnd = (AUTHENTICATED_VARIABLE_HEADER *)((UINT8 *)VariableStorage + VariableStorage->Size); + VariableHeader = (AUTHENTICATED_VARIABLE_HEADER *)(VariableStorage + 1); + VariableHeader = (AUTHENTICATED_VARIABLE_HEADER *)HEADER_ALIGN (VariableHeader); + while (VariableHeader < VariableEnd) { + if (CompareGuid (&VariableHeader->VendorGuid, VarGuid) && + (VariableHeader->Attributes == VarAttribute) && + (StrCmp (VarName, (CHAR16 *)(VariableHeader + 1)) == 0)) + { + return VariableHeader; + } + + VariableHeader = (AUTHENTICATED_VARIABLE_HEADER *)((UINT8 *)VariableHeader + sizeof (AUTHENTICATED_VARIABLE_HEADER) + VariableHeader->NameSize + VariableHeader->DataSize); + VariableHeader = (AUTHENTICATED_VARIABLE_HEADER *)HEADER_ALIGN (VariableHeader); + } + + return NULL; +} + /** Find the matched variable from the input variable storage. @@ -626,25 +665,27 @@ FindQuestionDefaultSetting ( IN BOOLEAN BitFieldQuestion ) { - VARIABLE_HEADER *VariableHeader; - VARIABLE_STORE_HEADER *VariableStorage; - LIST_ENTRY *Link; - VARSTORAGE_DEFAULT_DATA *Entry; - VARIABLE_STORE_HEADER *NvStoreBuffer; - UINT8 *DataBuffer; - UINT8 *BufferEnd; - BOOLEAN IsFound; - UINTN Index; - UINT32 BufferValue; - UINT32 BitFieldVal; - UINTN BitOffset; - UINTN ByteOffset; - UINTN BitWidth; - UINTN StartBit; - UINTN EndBit; - PCD_DEFAULT_DATA *DataHeader; - PCD_DEFAULT_INFO *DefaultInfo; - PCD_DATA_DELTA *DeltaData; + AUTHENTICATED_VARIABLE_HEADER *AuthVariableHeader; + VARIABLE_HEADER *VariableHeader; + VARIABLE_STORE_HEADER *VariableStorage; + LIST_ENTRY *Link; + VARSTORAGE_DEFAULT_DATA *Entry; + VARIABLE_STORE_HEADER *NvStoreBuffer; + UINT8 *DataBuffer; + UINT8 *BufferEnd; + BOOLEAN IsFound; + UINTN Index; + UINT32 BufferValue; + UINT32 BitFieldVal; + UINTN BitOffset; + UINTN ByteOffset; + UINTN BitWidth; + UINTN StartBit; + UINTN EndBit; + PCD_DEFAULT_DATA *DataHeader; + PCD_DEFAULT_INFO *DefaultInfo; + PCD_DATA_DELTA *DeltaData; + BOOLEAN VarCheck; if (gSkuId == 0xFFFFFFFFFFFFFFFF) { gSkuId = LibPcdGetSku (); @@ -750,40 +791,81 @@ FindQuestionDefaultSetting ( return EFI_NOT_FOUND; } - // - // Find the question default value from the variable storage - // - VariableHeader = FindVariableData (VariableStorage, &EfiVarStore->Guid, EfiVarStore->Attributes, (CHAR16 *)EfiVarStore->Name); - if (VariableHeader == NULL) { - return EFI_NOT_FOUND; - } + VarCheck = (BOOLEAN)(CompareGuid (&VariableStorage->Signature, &gEfiAuthenticatedVariableGuid)); - StartBit = 0; - EndBit = 0; - ByteOffset = IfrQuestionHdr->VarStoreInfo.VarOffset; - if (BitFieldQuestion) { - BitOffset = IfrQuestionHdr->VarStoreInfo.VarOffset; - ByteOffset = BitOffset / 8; - BitWidth = Width; - StartBit = BitOffset % 8; - EndBit = StartBit + BitWidth - 1; - Width = EndBit / 8 + 1; - } + if (VarCheck) { + // + // Find the question default value from the variable storage + // + AuthVariableHeader = AuthFindVariableData (VariableStorage, &EfiVarStore->Guid, EfiVarStore->Attributes, (CHAR16 *)EfiVarStore->Name); + if (AuthVariableHeader == NULL) { + return EFI_NOT_FOUND; + } - if (VariableHeader->DataSize < ByteOffset + Width) { - return EFI_INVALID_PARAMETER; - } + StartBit = 0; + EndBit = 0; + ByteOffset = IfrQuestionHdr->VarStoreInfo.VarOffset; + if (BitFieldQuestion) { + BitOffset = IfrQuestionHdr->VarStoreInfo.VarOffset; + ByteOffset = BitOffset / 8; + BitWidth = Width; + StartBit = BitOffset % 8; + EndBit = StartBit + BitWidth - 1; + Width = EndBit / 8 + 1; + } - // - // Copy the question value - // - if (ValueBuffer != NULL) { + if (AuthVariableHeader->DataSize < ByteOffset + Width) { + return EFI_INVALID_PARAMETER; + } + + // + // Copy the question value + // + if (ValueBuffer != NULL) { + if (BitFieldQuestion) { + CopyMem (&BufferValue, (UINT8 *)AuthVariableHeader + sizeof (AUTHENTICATED_VARIABLE_HEADER) + AuthVariableHeader->NameSize + ByteOffset, Width); + BitFieldVal = BitFieldRead32 (BufferValue, StartBit, EndBit); + CopyMem (ValueBuffer, &BitFieldVal, Width); + } else { + CopyMem (ValueBuffer, (UINT8 *)AuthVariableHeader + sizeof (AUTHENTICATED_VARIABLE_HEADER) + AuthVariableHeader->NameSize + IfrQuestionHdr->VarStoreInfo.VarOffset, Width); + } + } + } else { + // + // Find the question default value from the variable storage + // + VariableHeader = FindVariableData (VariableStorage, &EfiVarStore->Guid, EfiVarStore->Attributes, (CHAR16 *)EfiVarStore->Name); + if (VariableHeader == NULL) { + return EFI_NOT_FOUND; + } + + StartBit = 0; + EndBit = 0; + ByteOffset = IfrQuestionHdr->VarStoreInfo.VarOffset; if (BitFieldQuestion) { - CopyMem (&BufferValue, (UINT8 *)VariableHeader + sizeof (VARIABLE_HEADER) + VariableHeader->NameSize + ByteOffset, Width); - BitFieldVal = BitFieldRead32 (BufferValue, StartBit, EndBit); - CopyMem (ValueBuffer, &BitFieldVal, Width); - } else { - CopyMem (ValueBuffer, (UINT8 *)VariableHeader + sizeof (VARIABLE_HEADER) + VariableHeader->NameSize + IfrQuestionHdr->VarStoreInfo.VarOffset, Width); + BitOffset = IfrQuestionHdr->VarStoreInfo.VarOffset; + ByteOffset = BitOffset / 8; + BitWidth = Width; + StartBit = BitOffset % 8; + EndBit = StartBit + BitWidth - 1; + Width = EndBit / 8 + 1; + } + + if (VariableHeader->DataSize < ByteOffset + Width) { + return EFI_INVALID_PARAMETER; + } + + // + // Copy the question value + // + if (ValueBuffer != NULL) { + if (BitFieldQuestion) { + CopyMem (&BufferValue, (UINT8 *)VariableHeader + sizeof (VARIABLE_HEADER) + VariableHeader->NameSize + ByteOffset, Width); + BitFieldVal = BitFieldRead32 (BufferValue, StartBit, EndBit); + CopyMem (ValueBuffer, &BitFieldVal, Width); + } else { + CopyMem (ValueBuffer, (UINT8 *)VariableHeader + sizeof (VARIABLE_HEADER) + VariableHeader->NameSize + IfrQuestionHdr->VarStoreInfo.VarOffset, Width); + } } } diff --git a/MdeModulePkg/Universal/HiiDatabaseDxe/HiiDatabaseDxe.inf b/MdeModulePkg/Universal/HiiDatabaseDxe/HiiDatabaseDxe.inf index 0116fb6ecb10..51233327f346 100644 --- a/MdeModulePkg/Universal/HiiDatabaseDxe/HiiDatabaseDxe.inf +++ b/MdeModulePkg/Universal/HiiDatabaseDxe/HiiDatabaseDxe.inf @@ -86,6 +86,7 @@ gEfiHiiImageDecoderNameJpegGuid |gEfiMdeModulePkgTokenSpaceGuid.PcdSupportHiiImageProtocol ## SOMETIMES_CONSUMES ## GUID gEfiHiiImageDecoderNamePngGuid |gEfiMdeModulePkgTokenSpaceGuid.PcdSupportHiiImageProtocol ## SOMETIMES_CONSUMES ## GUID gEdkiiIfrBitVarstoreGuid ## SOMETIMES_CONSUMES ## GUID + gEfiAuthenticatedVariableGuid ## CONSUMES ## GUID [Depex] TRUE diff --git a/MdePkg/Include/Guid/Cper.h b/MdePkg/Include/Guid/Cper.h index deb96d4af982..be6b86382703 100644 --- a/MdePkg/Include/Guid/Cper.h +++ b/MdePkg/Include/Guid/Cper.h @@ -1208,6 +1208,104 @@ typedef struct { UINT64 PteL1; } EFI_IOMMU_DMAR_ERROR_DATA; +/// +/// CXL Cachemem Event Log Valid bits +///@{ +#define EFI_CXL_CACHMEM_AGENT_TYPE BIT0 // CXL Agent Type field is valid +#define EFI_CXL_CACHMEM_AGENT_ADDRESS BIT1 // CXL Agent Address field is valid +#define EFI_CXL_CACHMEM_DEVICE_ID BIT2 // Device ID field is valid +#define EFI_CXL_CACHMEM_DEVICE_SER_NUM BIT3 // Device Serial Number field is valid +#define EFI_CXL_CACHMEM_CAP_STRUCT BIT4 // Capability structure field is valid +#define EFI_CXL_CACHMEM_DVSEC BIT5 // CXL DVSET field is valid +#define EFI_CXL_CACHMEM_ERROR_LOG BIT6 // CXL Error Log field is valid +///@} + +// +// CXL Agent Types +///@{ +#define EFI_CXL_AGENT_CXL11_DEV 0 // CXL 1.1 Device +#define EFI_CXL_AGENT_CXL11_DSP 1 // CXL 1.1 Downstream Port +#define EFI_CXL_AGENT_CXL20_DEV 2 // CXL 2.0 Device +#define EFI_CXL_AGENT_CXL20_LOGICAL_DEV 3 // CXL 2.0 Logical Device +#define EFI_CXL_AGENT_CXL20_FMLD 4 // CXL 2.0 Fabric Manager managed Logical device +#define EFI_CXL_AGENT_CXL20_RP 5 // CXL 2.0 Root Port +#define EFI_CXL_AGENT_CXL20_DSP 6 // CXL 2.0 Downstream Switch Port +#define EFI_CXL_AGENT_CXL20_USP 7 // CXL 2.0 Upstream Switch Port +///@} + +// +// CXL Mem Event Log Valid bits +///@{ +#define EFI_CXL_MEM_DEVICE_ID BIT0 // Device ID field is valid +#define EFI_CXL_MEM_DEVICE_SER_NUM BIT1 // Device Serial Number field is valid +#define EFI_CXL_MEM_COMP_ERROR_LOG BIT2 // CXL Component Error Log field is valid +///@} + +// +// CXL Agent Address +// +typedef union { + struct { + UINT64 Function : 8; + UINT64 Device : 8; + UINT64 Bus : 8; + UINT64 Segment : 16; + UINT64 Rsvd : 24; + } Bits; + struct { + UINT32 Low; + UINT32 High; + } RcrbBase; +} EFI_CXL_AGENT_ADDRESS; + +// +// CXL Device ID +// +typedef struct { + UINT16 VendorId; + UINT16 DeviceId; + UINT16 Svid; + UINT16 Sid; + UINT16 ClassCode; + struct { + UINT16 Rsvd : 3; + UINT16 Num : 13; + } Slot; + UINT32 Rsvd; +} EFI_CXL_AGENT_DEVICE_ID; + +// +// CXL Device Serial Number +// +typedef struct { + UINT32 Lower; + UINT32 Upper; +} EFI_CXL_DEVICE_SERIAL_NUM; + +// +// PCIe device identifiers of CXL Component +// +typedef struct { + UINT16 VendorId; + UINT16 DeviceId; + UINT8 Function; + UINT8 Device; + UINT8 Bus; + UINT16 Segment; + EFI_GENERIC_ERROR_PCI_SLOT Slot; + UINT8 Resvd; +} EFI_CXL_ERROR_PCIE_DEV_ID; + +// +// CXL Component Events Section +// +typedef struct { + UINT32 Length; + UINT64 ValidFields; + EFI_CXL_ERROR_PCIE_DEV_ID CxlDeviceId; + UINT64 DeviceSerialNo; +} EFI_CXL_COMPONENT_EVENT_LOG; + #pragma pack() extern EFI_GUID gEfiEventNotificationTypeCmcGuid; diff --git a/MdePkg/Include/Guid/DxeServices.h b/MdePkg/Include/Guid/DxeServices.h index e7b6b19eb017..358c08d72a5c 100644 --- a/MdePkg/Include/Guid/DxeServices.h +++ b/MdePkg/Include/Guid/DxeServices.h @@ -12,6 +12,10 @@ #ifndef __DXE_SERVICES_GUID_H__ #define __DXE_SERVICES_GUID_H__ +// +// The DXE Services Table shall be stored in memory of type +// EfiBootServicesData +// #define DXE_SERVICES_TABLE_GUID \ { \ 0x5ad34ba, 0x6f02, 0x4214, {0x95, 0x2e, 0x4d, 0xa0, 0x39, 0x8e, 0x2b, 0xb9 } \ diff --git a/MdePkg/Include/Guid/HobList.h b/MdePkg/Include/Guid/HobList.h index 435f010c1a80..6195fa926001 100644 --- a/MdePkg/Include/Guid/HobList.h +++ b/MdePkg/Include/Guid/HobList.h @@ -14,6 +14,10 @@ #ifndef __HOB_LIST_GUID_H__ #define __HOB_LIST_GUID_H__ +// +// The HOB List Table shall be stored in memory of type +// EfiBootServicesData +// #define HOB_LIST_GUID \ { \ 0x7739f24c, 0x93d7, 0x11d4, {0x9a, 0x3a, 0x0, 0x90, 0x27, 0x3f, 0xc1, 0x4d } \ diff --git a/MdePkg/Include/Guid/VectorHandoffTable.h b/MdePkg/Include/Guid/VectorHandoffTable.h index ef9841e324c3..68353e826c79 100644 --- a/MdePkg/Include/Guid/VectorHandoffTable.h +++ b/MdePkg/Include/Guid/VectorHandoffTable.h @@ -19,6 +19,9 @@ // in case an entity in DXE wishes to update/change the vector // table contents. // +// The table shall be stored in memory of type +// EfiBootServicesData +// #define EFI_VECTOR_HANDOF_TABLE_GUID \ { 0x996ec11c, 0x5397, 0x4e73, { 0xb5, 0x8f, 0x82, 0x7e, 0x52, 0x90, 0x6d, 0xef }} diff --git a/MdePkg/Include/IndustryStandard/PciExpress21.h b/MdePkg/Include/IndustryStandard/PciExpress21.h index b437ca5c1e8b..c6faa9425be0 100644 --- a/MdePkg/Include/IndustryStandard/PciExpress21.h +++ b/MdePkg/Include/IndustryStandard/PciExpress21.h @@ -714,9 +714,7 @@ typedef struct { UINT16 DpaControl; UINT8 DpaPowerAllocationArray[1]; } PCI_EXPRESS_EXTENDED_CAPABILITIES_DYNAMIC_POWER_ALLOCATION; - -#define PCI_EXPRESS_EXTENDED_CAPABILITY_DYNAMIC_POWER_ALLOCATION_GET_SUBSTATE_MAX(POWER) (UINT16)(((POWER->DpaCapability)&0x0000000F)) - +#define PCI_EXPRESS_EXTENDED_CAPABILITY_DYNAMIC_POWER_ALLOCATION_GET_SUBSTATE_MAX(POWER) (UINT32)(((POWER->DpaCapability)&0x0000000F)) #define PCI_EXPRESS_EXTENDED_CAPABILITY_LATENCE_TOLERANCE_REPORTING_ID 0x0018 #define PCI_EXPRESS_EXTENDED_CAPABILITY_LATENCE_TOLERANCE_REPORTING_VER1 0x1 diff --git a/MdePkg/Include/IndustryStandard/ServiceProcessorManagementInterfaceTable.h b/MdePkg/Include/IndustryStandard/ServiceProcessorManagementInterfaceTable.h old mode 100644 new mode 100755 index 15f47f1535eb..131cf40acc65 --- a/MdePkg/Include/IndustryStandard/ServiceProcessorManagementInterfaceTable.h +++ b/MdePkg/Include/IndustryStandard/ServiceProcessorManagementInterfaceTable.h @@ -3,6 +3,8 @@ Intelligent Platform Management Interface Specification Second Generation. Copyright (c) 2018, Intel Corporation. All rights reserved.
+ Copyright (c) 2024 Advanced Micro Devices, Inc. All rights reserved. + SPDX-License-Identifier: BSD-2-Clause-Patent @par Revision Reference: @@ -95,4 +97,17 @@ typedef struct { #pragma pack() +/// +/// SPMI Revision (defined in spec) +/// +#define EFI_ACPI_SERVICE_PROCESSOR_MANAGEMENT_INTERFACE_5_TABLE_REVISION 0x05 + +/// +/// SPMI Interface Type +/// +#define EFI_ACPI_SPMI_INTERFACE_TYPE_KCS 0x01 +#define EFI_ACPI_SPMI_INTERFACE_TYPE_SMIC 0x02 +#define EFI_ACPI_SPMI_INTERFACE_TYPE_BT 0x03 +#define EFI_ACPI_SPMI_INTERFACE_TYPE_SSIF 0x04 + #endif diff --git a/MdePkg/Include/IndustryStandard/SmBios.h b/MdePkg/Include/IndustryStandard/SmBios.h index 8ba61297e860..d82d04b595f9 100644 --- a/MdePkg/Include/IndustryStandard/SmBios.h +++ b/MdePkg/Include/IndustryStandard/SmBios.h @@ -706,6 +706,7 @@ typedef enum { ProcessorFamilyIntelCoreI5 = 0xCD, ProcessorFamilyIntelCoreI3 = 0xCE, ProcessorFamilyIntelCoreI9 = 0xCF, + ProcessorFamilyIntelXeonD = 0xD0, /// Smbios spec 3.8 updated this value ProcessorFamilyViaC7M = 0xD2, ProcessorFamilyViaC7D = 0xD3, ProcessorFamilyViaC7 = 0xD4, diff --git a/MdePkg/Include/IndustryStandard/Usb.h b/MdePkg/Include/IndustryStandard/Usb.h index 7df6466a7d35..8013d209c88a 100644 --- a/MdePkg/Include/IndustryStandard/Usb.h +++ b/MdePkg/Include/IndustryStandard/Usb.h @@ -2,6 +2,8 @@ Support for USB 2.0 standard. Copyright (c) 2006 - 2014, Intel Corporation. All rights reserved.
+ Copyright (c) 2024, American Megatrends International LLC. All rights reserved.
+ SPDX-License-Identifier: BSD-2-Clause-Patent **/ @@ -131,6 +133,21 @@ typedef struct { UINT8 MaxPower; } USB_CONFIG_DESCRIPTOR; +/// +/// Standard Interface Association Descriptor +/// USB 3.0 spec, Section 9.6.4 +/// +typedef struct { + UINT8 Length; + UINT8 DescriptorType; + UINT8 FirstInterface; + UINT8 InterfaceCount; + UINT8 FunctionClass; + UINT8 FunctionSubclass; + UINT8 FunctionProtocol; + UINT8 FunctionDescriptionStringIndex; +} USB_INTERFACE_ASSOCIATION_DESCRIPTOR; + /// /// Standard Interface Descriptor /// USB 2.0 spec, Section 9.6.5 @@ -207,13 +224,16 @@ typedef enum { // // USB Descriptor types // - USB_DESC_TYPE_DEVICE = 0x01, - USB_DESC_TYPE_CONFIG = 0x02, - USB_DESC_TYPE_STRING = 0x03, - USB_DESC_TYPE_INTERFACE = 0x04, - USB_DESC_TYPE_ENDPOINT = 0x05, - USB_DESC_TYPE_HID = 0x21, - USB_DESC_TYPE_REPORT = 0x22, + USB_DESC_TYPE_DEVICE = 0x01, + USB_DESC_TYPE_CONFIG = 0x02, + USB_DESC_TYPE_STRING = 0x03, + USB_DESC_TYPE_INTERFACE = 0x04, + USB_DESC_TYPE_ENDPOINT = 0x05, + USB_DESC_TYPE_INTERFACE_ASSOCIATION = 0x0b, + USB_DESC_TYPE_HID = 0x21, + USB_DESC_TYPE_REPORT = 0x22, + USB_DESC_TYPE_CS_INTERFACE = 0x24, + USB_DESC_TYPE_CS_ENDPOINT = 0x25, // // Features to be cleared by CLEAR_FEATURE requests diff --git a/MdePkg/Include/Library/DebugLib.h b/MdePkg/Include/Library/DebugLib.h index fc5c83463d4a..b48e08a7e42b 100644 --- a/MdePkg/Include/Library/DebugLib.h +++ b/MdePkg/Include/Library/DebugLib.h @@ -8,6 +8,13 @@ of size reduction when compiler optimization is disabled. If MDEPKG_NDEBUG is defined, then debug and assert related macros wrapped by it are the NULL implementations. + The implementations of the macros used when MDEPKG_NDEBUG is defined rely on the fact that + directly unreachable code is pruned, even with compiler optimization disabled (which has + been confirmed by generated code size tests on supported compilers). The advantage of + implementations which consume their arguments within directly unreachable code is that + compilers understand this, and stop warning about variables which would become unused when + MDEPKG_NDEBUG is defined if the macros had completely empty definitions. + Copyright (c) 2006 - 2020, Intel Corporation. All rights reserved.
SPDX-License-Identifier: BSD-2-Clause-Patent @@ -403,7 +410,12 @@ UnitTestDebugAssert ( } \ } while (FALSE) #else -#define ASSERT(Expression) +#define ASSERT(Expression) \ + do { \ + if (FALSE) { \ + (VOID) (Expression); \ + } \ + } while (FALSE) #endif /** @@ -426,7 +438,12 @@ UnitTestDebugAssert ( } \ } while (FALSE) #else -#define DEBUG(Expression) +#define DEBUG(Expression) \ + do { \ + if (FALSE) { \ + _DEBUGLIB_DEBUG (Expression); \ + } \ + } while (FALSE) #endif /** @@ -452,7 +469,12 @@ UnitTestDebugAssert ( } \ } while (FALSE) #else -#define ASSERT_EFI_ERROR(StatusParameter) +#define ASSERT_EFI_ERROR(StatusParameter) \ + do { \ + if (FALSE) { \ + (VOID) (StatusParameter); \ + } \ + } while (FALSE) #endif /** @@ -479,7 +501,12 @@ UnitTestDebugAssert ( } \ } while (FALSE) #else -#define ASSERT_RETURN_ERROR(StatusParameter) +#define ASSERT_RETURN_ERROR(StatusParameter) \ + do { \ + if (FALSE) { \ + (VOID) (StatusParameter); \ + } \ + } while (FALSE) #endif /** @@ -534,7 +561,10 @@ UnitTestDebugAssert ( are not included in a module. **/ -#define DEBUG_CODE_BEGIN() do { if (DebugCodeEnabled ()) { UINT8 __DebugCodeLocal +#define DEBUG_CODE_BEGIN() \ + do { \ + if (DebugCodeEnabled ()) { \ + do { } while (FALSE) /** The macro that marks the end of debug source code. @@ -545,7 +575,9 @@ UnitTestDebugAssert ( are not included in a module. **/ -#define DEBUG_CODE_END() __DebugCodeLocal = 0; __DebugCodeLocal++; } } while (FALSE) +#define DEBUG_CODE_END() \ + } \ + } while (FALSE) /** The macro that declares a section of debug source code. @@ -588,8 +620,12 @@ UnitTestDebugAssert ( If MDEPKG_NDEBUG is defined or the DEBUG_PROPERTY_DEBUG_ASSERT_ENABLED bit of PcdDebugProperyMask is clear, then this macro computes the offset, in bytes, of the field specified by Field from the beginning of the data structure specified - by TYPE. This offset is subtracted from Record, and is used to return a pointer - to a data structure of the type specified by TYPE. + by TYPE. This offset is subtracted from Record, and is used to compute a pointer + to a data structure of the type specified by TYPE. The Signature field of the + data structure specified by TYPE is compared to TestSignature. If the signatures + match, then a pointer to the pointer to a data structure of the type specified by + TYPE is returned. If the signatures do not match, then NULL is returned to + signify that the passed in data structure is invalid. If MDEPKG_NDEBUG is not defined and the DEBUG_PROPERTY_DEBUG_ASSERT_ENABLED bit of PcdDebugProperyMask is set, then this macro computes the offset, in bytes, @@ -623,9 +659,13 @@ UnitTestDebugAssert ( #define CR(Record, TYPE, Field, TestSignature) \ (DebugAssertEnabled () && (BASE_CR (Record, TYPE, Field)->Signature != TestSignature)) ? \ (TYPE *) (_ASSERT (CR has Bad Signature), Record) : \ + (BASE_CR (Record, TYPE, Field)->Signature != TestSignature) ? \ + NULL : \ BASE_CR (Record, TYPE, Field) #else #define CR(Record, TYPE, Field, TestSignature) \ + (BASE_CR (Record, TYPE, Field)->Signature != TestSignature) ? \ + NULL : \ BASE_CR (Record, TYPE, Field) #endif diff --git a/MdePkg/Include/Library/FdtLib.h b/MdePkg/Include/Library/FdtLib.h index ffff40d8fe27..a7d26f765d39 100644 --- a/MdePkg/Include/Library/FdtLib.h +++ b/MdePkg/Include/Library/FdtLib.h @@ -19,6 +19,115 @@ #ifndef FDT_LIB_H_ #define FDT_LIB_H_ +/* Error codes: informative error codes */ +#define FDT_ERR_NOTFOUND 1 +/* FDT_ERR_NOTFOUND: The requested node or property does not exist */ +#define FDT_ERR_EXISTS 2 + +/* FDT_ERR_EXISTS: Attempted to create a node or property which + * already exists */ +#define FDT_ERR_NOSPACE 3 + +/* FDT_ERR_NOSPACE: Operation needed to expand the device + * tree, but its buffer did not have sufficient space to + * contain the expanded tree. Use fdt_open_into() to move the + * device tree to a buffer with more space. */ + +/* Error codes: codes for bad parameters */ +#define FDT_ERR_BADOFFSET 4 + +/* FDT_ERR_BADOFFSET: Function was passed a structure block + * offset which is out-of-bounds, or which points to an + * unsuitable part of the structure for the operation. */ +#define FDT_ERR_BADPATH 5 + +/* FDT_ERR_BADPATH: Function was passed a badly formatted path + * (e.g. missing a leading / for a function which requires an + * absolute path) */ +#define FDT_ERR_BADPHANDLE 6 + +/* FDT_ERR_BADPHANDLE: Function was passed an invalid phandle. + * This can be caused either by an invalid phandle property + * length, or the phandle value was either 0 or -1, which are + * not permitted. */ +#define FDT_ERR_BADSTATE 7 + +/* FDT_ERR_BADSTATE: Function was passed an incomplete device + * tree created by the sequential-write functions, which is + * not sufficiently complete for the requested operation. */ + +/* Error codes: codes for bad device tree blobs */ +#define FDT_ERR_TRUNCATED 8 + +/* FDT_ERR_TRUNCATED: FDT or a sub-block is improperly + * terminated (overflows, goes outside allowed bounds, or + * isn't properly terminated). */ +#define FDT_ERR_BADMAGIC 9 + +/* FDT_ERR_BADMAGIC: Given "device tree" appears not to be a + * device tree at all - it is missing the flattened device + * tree magic number. */ +#define FDT_ERR_BADVERSION 10 + +/* FDT_ERR_BADVERSION: Given device tree has a version which + * can't be handled by the requested operation. For + * read-write functions, this may mean that fdt_open_into() is + * required to convert the tree to the expected version. */ +#define FDT_ERR_BADSTRUCTURE 11 + +/* FDT_ERR_BADSTRUCTURE: Given device tree has a corrupt + * structure block or other serious error (e.g. misnested + * nodes, or subnodes preceding properties). */ +#define FDT_ERR_BADLAYOUT 12 + +/* FDT_ERR_BADLAYOUT: For read-write functions, the given + * device tree has it's sub-blocks in an order that the + * function can't handle (memory reserve map, then structure, + * then strings). Use fdt_open_into() to reorganize the tree + * into a form suitable for the read-write operations. */ + +/* "Can't happen" error indicating a bug in libfdt */ +#define FDT_ERR_INTERNAL 13 + +/* FDT_ERR_INTERNAL: libfdt has failed an internal assertion. + * Should never be returned, if it is, it indicates a bug in + * libfdt itself. */ + +/* Errors in device tree content */ +#define FDT_ERR_BADNCELLS 14 + +/* FDT_ERR_BADNCELLS: Device tree has a #address-cells, #size-cells + * or similar property with a bad format or value */ + +#define FDT_ERR_BADVALUE 15 + +/* FDT_ERR_BADVALUE: Device tree has a property with an unexpected + * value. For example: a property expected to contain a string list + * is not NUL-terminated within the length of its value. */ + +#define FDT_ERR_BADOVERLAY 16 + +/* FDT_ERR_BADOVERLAY: The device tree overlay, while + * correctly structured, cannot be applied due to some + * unexpected or missing value, property or node. */ + +#define FDT_ERR_NOPHANDLES 17 + +/* FDT_ERR_NOPHANDLES: The device tree doesn't have any + * phandle available anymore without causing an overflow */ + +#define FDT_ERR_BADFLAGS 18 + +/* FDT_ERR_BADFLAGS: The function was passed a flags field that + * contains invalid flags or an invalid combination of flags. */ + +#define FDT_ERR_ALIGNMENT 19 + +/* FDT_ERR_ALIGNMENT: The device tree base address is not 8-byte + * aligned. */ + +#define FDT_ERR_MAX 19 + /** Flattened Device Tree definition @@ -63,6 +172,22 @@ typedef struct { CHAR8 Data[]; } FDT_PROPERTY; +#ifndef FDT_TAGSIZE +#define FDT_TAGSIZE sizeof(UINT32) +#endif +#ifndef FDT_MAX_NCELLS +#define FDT_MAX_NCELLS 4 +#endif + +#define FdtGetHeader(Fdt, Field) \ + (Fdt32ToCpu (((const FDT_HEADER *)(Fdt))->Field)) +#define FdtTotalSize(Fdt) (FdtGetHeader ((Fdt), TotalSize)) + +#define FdtForEachSubnode(Node, Fdt, Parent) \ + for (Node = FdtFirstSubnode (Fdt, Parent); \ + Node >= 0; \ + Node = FdtNextSubnode (Fdt, Node)) + /** Convert UINT16 data of the FDT blob to little-endian @@ -161,6 +286,37 @@ FdtCheckHeader ( IN CONST VOID *Fdt ); +/** + Unpack FDT blob into new buffer + + @param[in] Fdt The pointer to FDT blob. + @param[out] Buffer Pointer to destination buffer. + @param[in] BufferSize The size of destination buffer. + + @return Zero for successfully, otherwise failed. + + **/ +INT32 +EFIAPI +FdtOpenInto ( + IN CONST VOID *Fdt, + OUT VOID *Buffer, + IN INT32 BufferSize + ); + +/** + Pack FDT blob in place. + + @param[in][out] Fdt The pointer to FDT blob. + + @return Zero. +**/ +INT32 +EFIAPI +FdtPack ( + IN OUT VOID *Fdt + ); + /** Create a empty Flattened Device Tree. @@ -177,6 +333,23 @@ FdtCreateEmptyTree ( IN UINT32 BufferSize ); +/** + Returns a pointer to the node at a given offset. + + @param[in] Fdt The pointer to FDT blob. + @param[in] Offset The offset to node. + @param[in] Length Maximum length of node. + + @return pointer to node. +**/ +CONST VOID * +EFIAPI +FdtOffsetPointer ( + IN CONST VOID *Fdt, + IN INT32 Offset, + IN UINT32 Length + ); + /** Returns a offset of next node from the given node. @@ -248,39 +421,54 @@ FdtSubnodeOffsetNameLen ( ); /** - Returns number of reserved ranges. + Returns the number of memory reserve map entries. @param[in] Fdt The pointer to FDT blob. - @return The number of reserved ranges. + @return The number of entries in the reserve map. **/ INTN EFIAPI -FdtNumRsv ( +FdtGetNumberOfReserveMapEntries ( IN CONST VOID *Fdt ); /** - Returns reserved ranges. + Returns a memory reserve map entry. @param[in] *Fdt The pointer to FDT blob. - @param[in] Index Reserved entry index in the table. - @param[out] Addr Address returned - @param[out] *Size Pointer to size of the address range + @param[in] Index Index of reserve map entry. + @param[out] Addr Pointer to 64-bit variable to hold the start address + @param[out] *Size Pointer to 64-bit variable to hold size of reservation - @return Returns reserved range. + @return 0 on success, or negative error code. **/ INTN EFIAPI -FdtGetMemRsv ( +FdtGetReserveMapEntry ( IN CONST VOID *Fdt, IN INTN Index, OUT UINT64 *Addr, OUT UINT64 *Size ); +/** + Find the parent of a given node. + + @param[in] Fdt The pointer to FDT blob. + @param[in] NodeOffset The offset to the node to find the parent for. + + @return Structure block offset, or negative return value. +**/ +INT32 +EFIAPI +FdtParentOffset ( + IN CONST VOID *Fdt, + IN INT32 NodeOffset + ); + /** Returns a offset of first node which includes the given property name and value. @@ -295,7 +483,7 @@ FdtGetMemRsv ( **/ INT32 EFIAPI -FdtNodeOffsetByPropValue ( +FdtNodeOffsetByPropertyValue ( IN CONST VOID *Fdt, IN INT32 StartOffset, IN CONST CHAR8 *PropertyName, @@ -303,6 +491,38 @@ FdtNodeOffsetByPropValue ( IN INT32 PropertyLength ); +/** + Returns a offset of first node which includes the given property name and value. + + @param[in] Fdt The pointer to FDT blob. + @param[in] Phandle Phandle value to search for. + + @return The offset to node with matching Phandle value. +**/ +INT32 +EFIAPI +FdtNodeOffsetByPhandle ( + IN CONST VOID *Fdt, + IN UINT32 Phandle + ); + +/** + Look for a string in a stringlist + + @param[in] StringList Pointer to stringlist to search. + @param[in] ListLength Length of StringList. + @param[in] String Pointer to string to search for. + + @return 1 if found. +**/ +INT32 +EFIAPI +FdtStringListContains ( + IN CONST CHAR8 *StringList, + IN INT32 ListLength, + IN CONST CHAR8 *String + ); + /** Returns a property with the given name from the given node. @@ -324,6 +544,25 @@ FdtGetProperty ( IN INT32 *Length ); +/** + Returns a pointer to a node mapped to an alias matching a substring. + + @param[in] Fdt The pointer to FDT blob. + @param[in] Name The alias name string. + @param[in] Length The length to the size of the property found. + + @return A pointer to the expansion of the alias matching the substring, + or NULL if alias not found. + +**/ +CONST CHAR8 * +EFIAPI +FdtGetAliasNameLen ( + IN CONST VOID *Fdt, + IN CONST CHAR8 *Name, + IN INT32 Length + ); + /** Returns a offset of first property in the given node. @@ -424,7 +663,7 @@ FdtAddSubnode ( **/ INT32 EFIAPI -FdtSetProp ( +FdtSetProperty ( IN VOID *Fdt, IN INT32 NodeOffset, IN CONST CHAR8 *Name, @@ -432,6 +671,100 @@ FdtSetProp ( IN UINT32 Length ); +/** + Set a property to a 64-bit integer. + + @param[in] Fdt The pointer to FDT blob. + @param[in] NodeOffset The offset to the node offset which want to add in. + @param[in] Name The name to name the property. + @param[in] Value The value (big-endian) to the property value. + + @return Zero for successfully, otherwise failed. + + **/ +INT32 +EFIAPI +FdtSetPropU64 ( + IN VOID *Fdt, + IN INT32 NodeOffset, + IN CONST CHAR8 *Name, + IN UINT64 Value + ); + +/** + Append or create a property in the given node. + + @param[in] Fdt The pointer to FDT blob. + @param[in] NodeOffset The offset to the node offset which want to add in. + @param[in] Name The name to name the property. + @param[in] Value The value (big-endian) to the property value. + @param[in] Length The length to the size of the property. + + @return Zero for successfully, otherwise failed. + + **/ +INT32 +EFIAPI +FdtAppendProp ( + IN VOID *Fdt, + IN INT32 NodeOffset, + IN CONST CHAR8 *Name, + IN CONST VOID *Value, + IN UINT32 Length + ); + +/** + Delete a property. + + This function will delete data from the blob, and will therefore + change the offsets of some existing nodes. + + @param[in][out] Fdt Pointer to the device tree blob. + @param[in] NodeOffset Offset of the node whose property to nop. + @param[in] Name Name of the property to nop. + + @return Zero for successfully, otherwise failed. + +**/ +INT32 +FdtDelProp ( + IN OUT VOID *Fdt, + IN INT32 NodeOffset, + IN CONST CHAR8 *Name + ); + +/** + Finds a tree node by substring + + @param[in] Fdt The pointer to FDT blob. + @param[in] Path Full path of the node to locate. + @param[in] NameLength The length of the name to check only. + + @return structure block offset of the node with the requested path (>=0), on success +**/ +INT32 +EFIAPI +FdtPathOffsetNameLen ( + IN CONST VOID *Fdt, + IN CONST CHAR8 *Path, + IN INT32 NameLength + ); + +/** + Finds a tree node by its full path. + + @param[in] Fdt The pointer to FDT blob. + @param[in] Path Full path of the node to locate. + + @return structure block offset of the node with the requested path (>=0), on success +**/ +INT32 +EFIAPI +FdtPathOffset ( + IN CONST VOID *Fdt, + IN CONST CHAR8 *Path + ); + /** Returns the name of a given node. @@ -483,4 +816,42 @@ FdtNodeOffsetByCompatible ( IN CONST CHAR8 *Compatible ); +/** + Retrieve address size for a bus represented in the tree + + @param[in] Fdt The pointer to FDT blob. + @param[in] NodeOffset Offset of node to check. + + @return Number of cells in the bus address, or negative error. +**/ +INT32 +EFIAPI +FdtAddressCells ( + IN CONST VOID *Fdt, + IN INT32 NodeOffset + ); + +/** + Retrieve address range size for a bus represented in the tree + + @param[in] Fdt The pointer to FDT blob. + @param[in] NodeOffset Offset of node to check. + + @return Number of cells in the bus size, or negative error. +**/ +INT32 +EFIAPI +FdtSizeCells ( + IN CONST VOID *Fdt, + IN INT32 NodeOffset + ); + +/* Debug functions. */ +CONST +CHAR8 +* +FdtStrerror ( + IN INT32 ErrVal + ); + #endif /* FDT_LIB_H_ */ diff --git a/MdePkg/Include/Library/PerformanceLib.h b/MdePkg/Include/Library/PerformanceLib.h index d0f2dfb070d5..40e99d0c4a16 100644 --- a/MdePkg/Include/Library/PerformanceLib.h +++ b/MdePkg/Include/Library/PerformanceLib.h @@ -734,7 +734,10 @@ LogPerformanceMeasurement ( Otherwise, the source lines between PERF_CODE_BEGIN() and PERF_CODE_END() are not included in a module. **/ -#define PERF_CODE_BEGIN() do { if (PerformanceMeasurementEnabled ()) { UINT8 __PerformanceCodeLocal +#define PERF_CODE_BEGIN() \ + do { \ + if (PerformanceMeasurementEnabled ()) { \ + do { } while (FALSE) /** Macro that marks the end of performance measurement source code. @@ -744,7 +747,9 @@ LogPerformanceMeasurement ( Otherwise, the source lines between PERF_CODE_BEGIN() and PERF_CODE_END() are not included in a module. **/ -#define PERF_CODE_END() __PerformanceCodeLocal = 0; __PerformanceCodeLocal++; } } while (FALSE) +#define PERF_CODE_END() \ + } \ + } while (FALSE) /** Macro that declares a section of performance measurement source code. diff --git a/MdePkg/Include/Pi/PiDxeCis.h b/MdePkg/Include/Pi/PiDxeCis.h index 04410c5a1a72..bb903f045cb0 100644 --- a/MdePkg/Include/Pi/PiDxeCis.h +++ b/MdePkg/Include/Pi/PiDxeCis.h @@ -5,7 +5,7 @@ Copyright (c) 2006 - 2018, Intel Corporation. All rights reserved.
SPDX-License-Identifier: BSD-2-Clause-Patent @par Revision Reference: - PI Version 1.7 + PI Version 1.8.A **/ @@ -691,8 +691,8 @@ EFI_STATUS // DXE Services Table // #define DXE_SERVICES_SIGNATURE 0x565245535f455844ULL -#define DXE_SPECIFICATION_MAJOR_REVISION 1 -#define DXE_SPECIFICATION_MINOR_REVISION 70 +#define DXE_SPECIFICATION_MAJOR_REVISION PI_SPECIFICATION_MAJOR_REVISION +#define DXE_SPECIFICATION_MINOR_REVISION PI_SPECIFICATION_MINOR_REVISION #define DXE_SERVICES_REVISION ((DXE_SPECIFICATION_MAJOR_REVISION<<16) | (DXE_SPECIFICATION_MINOR_REVISION)) typedef struct { diff --git a/MdePkg/Include/Pi/PiMmCis.h b/MdePkg/Include/Pi/PiMmCis.h index 01340952d89b..9adffffd7166 100644 --- a/MdePkg/Include/Pi/PiMmCis.h +++ b/MdePkg/Include/Pi/PiMmCis.h @@ -18,12 +18,9 @@ typedef struct _EFI_MM_SYSTEM_TABLE EFI_MM_SYSTEM_TABLE; /// /// The Management Mode System Table (MMST) signature /// -#define MM_MMST_SIGNATURE SIGNATURE_32 ('S', 'M', 'S', 'T') -/// -/// The Management Mode System Table (MMST) revision is 1.6 -/// -#define MM_SPECIFICATION_MAJOR_REVISION 1 -#define MM_SPECIFICATION_MINOR_REVISION 60 +#define MM_MMST_SIGNATURE SIGNATURE_32 ('S', 'M', 'S', 'T') +#define MM_SPECIFICATION_MAJOR_REVISION PI_SPECIFICATION_MAJOR_REVISION +#define MM_SPECIFICATION_MINOR_REVISION PI_SPECIFICATION_MINOR_REVISION #define EFI_MM_SYSTEM_TABLE_REVISION ((MM_SPECIFICATION_MAJOR_REVISION<<16) | (MM_SPECIFICATION_MINOR_REVISION)) /** diff --git a/MdePkg/Include/Pi/PiMultiPhase.h b/MdePkg/Include/Pi/PiMultiPhase.h index a7e95820ef65..1c7332e7332c 100644 --- a/MdePkg/Include/Pi/PiMultiPhase.h +++ b/MdePkg/Include/Pi/PiMultiPhase.h @@ -5,7 +5,7 @@ Copyright (c) 2006 - 2018, Intel Corporation. All rights reserved.
SPDX-License-Identifier: BSD-2-Clause-Patent @par Revision Reference: - These elements are defined in UEFI Platform Initialization Specification 1.2. + These elements are defined in UEFI Platform Initialization Specification 1.8.A **/ @@ -20,6 +20,13 @@ SPDX-License-Identifier: BSD-2-Clause-Patent #include #include +// +// PI Specification Version Information +// +#define PI_SPECIFICATION_MAJOR_REVISION 1 +#define PI_SPECIFICATION_MINOR_REVISION 80 +#define PI_SPECIFICATION_VERSION ((PI_SPECIFICATION_MAJOR_REVISION << 16) | (PI_SPECIFICATION_MINOR_REVISION)) + /** Produces an error code in the range reserved for use by the Platform Initialization Architecture Specification. diff --git a/MdePkg/Include/Pi/PiPeiCis.h b/MdePkg/Include/Pi/PiPeiCis.h index 69eec2c47333..ad4be384bc5d 100644 --- a/MdePkg/Include/Pi/PiPeiCis.h +++ b/MdePkg/Include/Pi/PiPeiCis.h @@ -5,7 +5,7 @@ Copyright (c) 2006 - 2019, Intel Corporation. All rights reserved.
SPDX-License-Identifier: BSD-2-Clause-Patent @par Revision Reference: - PI Version 1.7. + PI Version 1.8.A **/ @@ -846,8 +846,8 @@ EFI_STATUS // // PEI Specification Revision information // -#define PEI_SPECIFICATION_MAJOR_REVISION 1 -#define PEI_SPECIFICATION_MINOR_REVISION 70 +#define PEI_SPECIFICATION_MAJOR_REVISION PI_SPECIFICATION_MAJOR_REVISION +#define PEI_SPECIFICATION_MINOR_REVISION PI_SPECIFICATION_MINOR_REVISION /// /// Specification inconsistency here: /// In the PI1.0 spec, PEI_SERVICES_SIGNATURE is defined as 0x5652455320494550. But diff --git a/MdePkg/Include/Ppi/DelayedDispatch.h b/MdePkg/Include/Ppi/DelayedDispatch.h index 1c2068404c22..4ef263a7834e 100644 --- a/MdePkg/Include/Ppi/DelayedDispatch.h +++ b/MdePkg/Include/Ppi/DelayedDispatch.h @@ -1,9 +1,10 @@ /** @file - EFI Delayed Dispatch PPI as defined in the PI 1.7 Specification + EFI Delayed Dispatch PPI as defined in the PI 1.8A Specification Provide timed event service in PEI Copyright (c) 2020, American Megatrends International LLC. All rights reserved. + Copyright (c) Microsoft Corporation. SPDX-License-Identifier: BSD-2-Clause-Patent **/ @@ -15,7 +16,7 @@ /// #define EFI_DELAYED_DISPATCH_PPI_GUID \ { \ - 0x869c711d, 0x649c, 0x44fe, { 0x8b, 0x9e, 0x2c, 0xbb, 0x29, 0x11, 0xc3, 0xe6} } \ + 0x869c711d, 0x649c, 0x44fe, { 0x8b, 0x9e, 0x2c, 0xbb, 0x29, 0x11, 0xc3, 0xe6} \ } /** @@ -31,8 +32,8 @@ typedef VOID (EFIAPI *EFI_DELAYED_DISPATCH_FUNCTION)( - IN OUT UINT64 *Context, - OUT UINT32 *NewDelay + IN OUT UINT64 *Context, + OUT UINT32 *NewDelay ); /// @@ -44,13 +45,11 @@ typedef struct _EFI_DELAYED_DISPATCH_PPI EFI_DELAYED_DISPATCH_PPI; /** Register a callback to be called after a minimum delay has occurred. -This service is the single member function of the EFI_DELAYED_DISPATCH_PPI - - @param This Pointer to the EFI_DELAYED_DISPATCH_PPI instance - @param Function Function to call back - @param Context Context data - @param UniqueId UniqueId - @param Delay Delay interval + @param[in] This Pointer to the EFI_DELAYED_DISPATCH_PPI instance + @param[in] Function Function to call back + @param[in] Context Context data + @param[in] DelayedGroupId Delayed dispatch request ID the caller will wait on + @param[in] Delay Delay interval @retval EFI_SUCCESS Function successfully loaded @retval EFI_INVALID_PARAMETER One of the Arguments is not supported @@ -62,17 +61,18 @@ EFI_STATUS (EFIAPI *EFI_DELAYED_DISPATCH_REGISTER)( IN EFI_DELAYED_DISPATCH_PPI *This, IN EFI_DELAYED_DISPATCH_FUNCTION Function, - IN UINT64 Context, - IN EFI_GUID *UniqueId OPTIONAL, - OUT UINT32 Delay + IN UINT64 Context, + IN EFI_GUID *DelayedGroupId OPTIONAL, + IN UINT32 Delay ); /** -Function invoked by a PEIM to wait until all specified UniqueId events have been dispatched. The other events -will continue to dispatch while this process is being paused + Wait on a registered Delayed Dispatch unit that has a DelayedGroupId. Continue + to dispatch all registered delayed dispatch entries until *ALL* entries with + DelayedGroupId have completed. - @param This Pointer to the EFI_DELAYED_DISPATCH_PPI instance - @param UniqueId Delayed dispatch request ID the caller will wait on + @param[in] This The Delayed Dispatch PPI pointer. + @param[in] DelayedGroupId Delayed dispatch request ID the caller will wait on @retval EFI_SUCCESS Function successfully invoked @retval EFI_INVALID_PARAMETER One of the Arguments is not supported @@ -82,8 +82,8 @@ will continue to dispatch while this process is being paused typedef EFI_STATUS (EFIAPI *EFI_DELAYED_DISPATCH_WAIT_ON_EVENT)( - IN EFI_DELAYED_DISPATCH_PPI *This, - IN EFI_GUID UniqueId + IN EFI_DELAYED_DISPATCH_PPI *This, + IN EFI_GUID DelayedGroupId ); /// diff --git a/MdePkg/Include/Protocol/MmSxDispatch.h b/MdePkg/Include/Protocol/MmSxDispatch.h index f9f74a288574..3fca3220456e 100644 --- a/MdePkg/Include/Protocol/MmSxDispatch.h +++ b/MdePkg/Include/Protocol/MmSxDispatch.h @@ -67,11 +67,7 @@ typedef struct _EFI_MM_SX_DISPATCH_PROTOCOL EFI_MM_SX_DISPATCH_PROTOCOL; The caller fills this context in before calling the register function to indicate to the register function which Sx state type and phase the caller - wishes to be called back on. For this intertace, - the Sx driver will call the registered handlers for - all Sx type and phases, so the Sx state handler(s) - must check the Type and Phase field of the Dispatch - context and act accordingly. + wishes to be called back on. @param[out] DispatchHandle Handle of dispatch function, for when interfacing with the parent Sx state MM driver. diff --git a/MdePkg/Include/Register/RiscV64/RiscVEncoding.h b/MdePkg/Include/Register/RiscV64/RiscVEncoding.h index a656d443a57c..ea148f78108b 100644 --- a/MdePkg/Include/Register/RiscV64/RiscVEncoding.h +++ b/MdePkg/Include/Register/RiscV64/RiscVEncoding.h @@ -20,6 +20,7 @@ #define MSTATUS_SPP (1UL << MSTATUS_SPP_SHIFT) #define MSTATUS_MPP_SHIFT 11 #define MSTATUS_MPP (3UL << MSTATUS_MPP_SHIFT) +#define MSTATUS_FS 0x00006000UL #define SSTATUS_SIE MSTATUS_SIE #define SSTATUS_SPIE_SHIFT MSTATUS_SPIE_SHIFT @@ -76,6 +77,9 @@ #define CSR_CYCLE 0xc00 #define CSR_TIME 0xc01 +/* Floating-Point */ +#define CSR_FCSR 0x003 + /* Supervisor Trap Setup */ #define CSR_SSTATUS 0x100 #define CSR_SEDELEG 0x102 diff --git a/MdePkg/Library/BaseFdtLib/FdtLib.c b/MdePkg/Library/BaseFdtLib/FdtLib.c index 5ff06111b7f4..ebddf4a00fde 100644 --- a/MdePkg/Library/BaseFdtLib/FdtLib.c +++ b/MdePkg/Library/BaseFdtLib/FdtLib.c @@ -7,6 +7,7 @@ **/ #include +#include #include /** @@ -147,6 +148,63 @@ FdtCreateEmptyTree ( return fdt_create_empty_tree (Buffer, (int)BufferSize); } +/** + Unpack FDT blob into new buffer + + @param[in] Fdt The pointer to FDT blob. + @param[out] Buffer Pointer to destination buffer. + @param[in] BufferSize The size of destination buffer. + + @return Zero for successfully, otherwise failed. + + **/ +INT32 +EFIAPI +FdtOpenInto ( + IN CONST VOID *Fdt, + OUT VOID *Buffer, + IN INT32 BufferSize + ) +{ + return fdt_open_into (Fdt, Buffer, BufferSize); +} + +/** + Pack FDT blob in place. + + @param[in][out] Fdt The pointer to FDT blob. + + @return Zero. +**/ +INT32 +EFIAPI +FdtPack ( + IN OUT VOID *Fdt + ) +{ + return fdt_pack (Fdt); +} + +/** + Returns a pointer to the node at a given offset. + + @param[in] Fdt The pointer to FDT blob. + @param[in] Offset The offset to node. + @param[in] Length Maximum length of node. + + @return pointer to node. +**/ +CONST VOID * +EFIAPI +FdtOffsetPointer ( + IN CONST VOID *Fdt, + IN INT32 Offset, + IN UINT32 Length + ) +{ + return fdt_offset_ptr (Fdt, Offset, Length); +} + /** Returns a offset of next node from the given node. @@ -207,16 +265,16 @@ FdtNextSubnode ( } /** - Returns number of reserved mem nodes + Returns the number of memory reserve map entries. - @param[in] Fdt The pointer to FDT blob. + @param[in] Fdt The pointer to FDT blob. - @return total reserved mem nodes + @return The number of entries in the reserve map. **/ INTN EFIAPI -FdtNumRsv ( +FdtGetNumberOfReserveMapEntries ( IN CONST VOID *Fdt ) { @@ -224,19 +282,19 @@ FdtNumRsv ( } /** - Returns reserved ranges. + Returns a memory reserve map entry. @param[in] *Fdt The pointer to FDT blob. - @param[in] Index Reserved entry index in the table. - @param[out] Addr Address returned - @param[out] *Size Pointer to size of the address range + @param[in] Index Index of reserve map entry. + @param[out] Addr Pointer to 64-bit variable to hold the start address + @param[out] *Size Pointer to 64-bit variable to hold size of reservation - @return Returns reserved range. + @return 0 on success, or negative error code. **/ INTN EFIAPI -FdtGetMemRsv ( +FdtGetReserveMapEntry ( IN CONST VOID *Fdt, IN INTN Index, OUT EFI_PHYSICAL_ADDRESS *Addr, @@ -269,6 +327,45 @@ FdtSubnodeOffsetNameLen ( return fdt_subnode_offset_namelen (Fdt, ParentOffset, Name, NameLength); } +/** + Returns a offset of first node which matches the given name. + + @param[in] Fdt The pointer to FDT blob. + @param[in] ParentOffset The offset to the node which start find under. + @param[in] Name The name to search the node with the name. + + @return The offset to node offset with given node name. + + **/ +INT32 +EFIAPI +FdtSubnodeOffset ( + IN CONST VOID *Fdt, + IN INT32 ParentOffset, + IN CONST CHAR8 *Name + ) +{ + return fdt_subnode_offset (Fdt, ParentOffset, Name); +} + +/** + Find the parent of a given node. + + @param[in] Fdt The pointer to FDT blob. + @param[in] NodeOffset The offset to the node to find the parent for. + + @return Structure block offset, or negative return value. +**/ +INT32 +EFIAPI +FdtParentOffset ( + IN CONST VOID *Fdt, + IN INT32 NodeOffset + ) +{ + return fdt_parent_offset (Fdt, NodeOffset); +} + /** Returns a offset of first node which includes the given property name and value. @@ -283,7 +380,7 @@ FdtSubnodeOffsetNameLen ( **/ INT32 EFIAPI -FdtNodeOffsetByPropValue ( +FdtNodeOffsetByPropertyValue ( IN CONST VOID *Fdt, IN INT32 StartOffset, IN CONST CHAR8 *PropertyName, @@ -294,6 +391,44 @@ FdtNodeOffsetByPropValue ( return fdt_node_offset_by_prop_value (Fdt, StartOffset, PropertyName, PropertyValue, PropertyLength); } +/** + Returns a offset of first node which includes the given property name and value. + + @param[in] Fdt The pointer to FDT blob. + @param[in] Phandle Phandle value to search for. + + @return The offset to node with matching Phandle value. +**/ +INT32 +EFIAPI +FdtNodeOffsetByPhandle ( + IN CONST VOID *Fdt, + IN UINT32 Phandle + ) +{ + return fdt_node_offset_by_phandle (Fdt, Phandle); +} + +/** + Look for a string in a stringlist + + @param[in] StringList Pointer to stringlist to search. + @param[in] ListLength Length of StringList. + @param[in] String Pointer to string to search for. + + @return 1 if found. +**/ +INT32 +EFIAPI +FdtStringListContains ( + IN CONST CHAR8 *StringList, + IN INT32 ListLength, + IN CONST CHAR8 *String + ) +{ + return fdt_stringlist_contains (StringList, ListLength, String); +} + /** Returns a property with the given name from the given node. @@ -306,7 +441,7 @@ FdtNodeOffsetByPropValue ( come from FDT blob, it's encoding with big-endian. **/ -CONST struct fdt_property * +CONST FDT_PROPERTY * EFIAPI FdtGetProperty ( IN CONST VOID *Fdt, @@ -315,7 +450,29 @@ FdtGetProperty ( IN INT32 *Length ) { - return fdt_get_property (Fdt, NodeOffset, Name, Length); + return (FDT_PROPERTY *)fdt_get_property (Fdt, NodeOffset, Name, Length); +} + +/** + Returns a pointer to a node mapped to an alias matching a substring. + + @param[in] Fdt The pointer to FDT blob. + @param[in] Name The alias name string. + @param[in] Length The length to the size of the property found. + + @return A pointer to the expansion of the alias matching the substring, + or NULL if alias not found. + +**/ +CONST CHAR8 * +EFIAPI +FdtGetAliasNameLen ( + IN CONST VOID *Fdt, + IN CONST CHAR8 *Name, + IN INT32 Length + ) +{ + return fdt_get_alias_namelen (Fdt, Name, Length); } /** @@ -366,7 +523,7 @@ FdtNextPropertyOffset ( @return The property to the structure of the given property offset. **/ -CONST struct fdt_property * +CONST FDT_PROPERTY * EFIAPI FdtGetPropertyByOffset ( IN CONST VOID *Fdt, @@ -374,7 +531,7 @@ FdtGetPropertyByOffset ( IN INT32 *Length ) { - return fdt_get_property_by_offset (Fdt, Offset, Length); + return (FDT_PROPERTY *)fdt_get_property_by_offset (Fdt, Offset, Length); } /** @@ -433,7 +590,7 @@ FdtAddSubnode ( **/ INT32 EFIAPI -FdtSetProp ( +FdtSetProperty ( IN VOID *Fdt, IN INT32 NodeOffset, IN CONST CHAR8 *Name, @@ -444,6 +601,119 @@ FdtSetProp ( return fdt_setprop (Fdt, NodeOffset, Name, Value, (int)Length); } +/** + Set a property to a 64-bit integer. + + @param[in] Fdt The pointer to FDT blob. + @param[in] NodeOffset The offset to the node offset which want to add in. + @param[in] Name The name to name the property. + @param[in] Value The value (big-endian) to the property value. + + @return Zero for successfully, otherwise failed. + + **/ +INT32 +EFIAPI +FdtSetPropU64 ( + IN VOID *Fdt, + IN INT32 NodeOffset, + IN CONST CHAR8 *Name, + IN UINT64 Value + ) +{ + UINT64 Tmp; + + Tmp = cpu_to_fdt64 (Value); + + return fdt_setprop (Fdt, NodeOffset, Name, &Tmp, sizeof (Tmp)); +} + +/** + Append or create a property in the given node. + + @param[in] Fdt The pointer to FDT blob. + @param[in] NodeOffset The offset to the node offset which want to add in. + @param[in] Name The name to name the property. + @param[in] Value The value (big-endian) to the property value. + @param[in] Length The length to the size of the property. + + @return Zero for successfully, otherwise failed. + + **/ +INT32 +EFIAPI +FdtAppendProp ( + IN VOID *Fdt, + IN INT32 NodeOffset, + IN CONST CHAR8 *Name, + IN CONST VOID *Value, + IN UINT32 Length + ) +{ + return fdt_appendprop (Fdt, NodeOffset, Name, Value, (int)Length); +} + +/** + Delete a property. + + This function will delete data from the blob, and will therefore + change the offsets of some existing nodes. + + @param[in][out] Fdt Pointer to the device tree blob. + @param[in] NodeOffset Offset of the node whose property to nop. + @param[in] Name Name of the property to nop. + + @return Zero for successfully, otherwise failed. + +**/ +INT32 +FdtDelProp ( + IN OUT VOID *Fdt, + IN INT32 NodeOffset, + IN CONST CHAR8 *Name + ) +{ + return fdt_delprop (Fdt, NodeOffset, Name); +} + +/** + Finds a tree node by substring + + @param[in] Fdt The pointer to FDT blob. + @param[in] Path Full path of the node to locate. + @param[in] NameLength The length of the name to check only. + + @return structure block offset of the node with the requested path (>=0), on success +**/ +INT32 +EFIAPI +FdtPathOffsetNameLen ( + IN CONST VOID *Fdt, + IN CONST CHAR8 *Path, + IN INT32 NameLength + ) +{ + return fdt_path_offset_namelen (Fdt, Path, NameLength); +} + +/** + Finds a tree node by its full path. + + @param[in] Fdt The pointer to FDT blob. + @param[in] Path Full path of the node to locate. + + @return structure block offset of the node with the requested path (>=0), on success +**/ +INT32 +EFIAPI +FdtPathOffset ( + IN CONST VOID *Fdt, + IN CONST CHAR8 *Path + ) +{ + return fdt_path_offset (Fdt, Path); +} + /** Returns the name of a given node. @@ -503,3 +773,50 @@ FdtNodeOffsetByCompatible ( { return fdt_node_offset_by_compatible (Fdt, StartOffset, Compatible); } + +/** + Retrieve address size for a bus represented in the tree + + @param[in] Fdt The pointer to FDT blob. + @param[in] NodeOffset Offset of node to check. + + @return Number of cells in the bus address, or negative error. +**/ +INT32 +EFIAPI +FdtAddressCells ( + IN CONST VOID *Fdt, + IN INT32 NodeOffset + ) +{ + return fdt_address_cells (Fdt, NodeOffset); +} + +/** + Retrieve address range size for a bus represented in the tree + + @param[in] Fdt The pointer to FDT blob. + @param[in] NodeOffset Offset of node to check. + + @return Number of cells in the bus size, or negative error. +**/ +INT32 +EFIAPI +FdtSizeCells ( + IN CONST VOID *Fdt, + IN INT32 NodeOffset + ) +{ + return fdt_size_cells (Fdt, NodeOffset); +} + +/* Debug functions. */ +CONST +CHAR8 +* +FdtStrerror ( + IN INT32 ErrVal + ) +{ + return fdt_strerror (ErrVal); +} diff --git a/MdePkg/Library/BaseLib/String.c b/MdePkg/Library/BaseLib/String.c index 637c96e7b31b..f16e1099bee0 100644 --- a/MdePkg/Library/BaseLib/String.c +++ b/MdePkg/Library/BaseLib/String.c @@ -406,10 +406,12 @@ StrDecimalToUintn ( IN CONST CHAR16 *String ) { - UINTN Result; + UINTN Result; + RETURN_STATUS Status; - if (RETURN_ERROR (StrDecimalToUintnS (String, (CHAR16 **)NULL, &Result))) { - return MAX_UINTN; + Status = StrDecimalToUintnS (String, (CHAR16 **)NULL, &Result); + if (Status == RETURN_INVALID_PARAMETER) { + Result = 0; } return Result; @@ -455,10 +457,12 @@ StrDecimalToUint64 ( IN CONST CHAR16 *String ) { - UINT64 Result; + UINT64 Result; + RETURN_STATUS Status; - if (RETURN_ERROR (StrDecimalToUint64S (String, (CHAR16 **)NULL, &Result))) { - return MAX_UINT64; + Status = StrDecimalToUint64S (String, (CHAR16 **)NULL, &Result); + if (Status == RETURN_INVALID_PARAMETER) { + Result = 0; } return Result; @@ -505,10 +509,12 @@ StrHexToUintn ( IN CONST CHAR16 *String ) { - UINTN Result; + UINTN Result; + RETURN_STATUS Status; - if (RETURN_ERROR (StrHexToUintnS (String, (CHAR16 **)NULL, &Result))) { - return MAX_UINTN; + Status = StrHexToUintnS (String, (CHAR16 **)NULL, &Result); + if (Status == RETURN_INVALID_PARAMETER) { + Result = 0; } return Result; @@ -555,10 +561,12 @@ StrHexToUint64 ( IN CONST CHAR16 *String ) { - UINT64 Result; + UINT64 Result; + RETURN_STATUS Status; - if (RETURN_ERROR (StrHexToUint64S (String, (CHAR16 **)NULL, &Result))) { - return MAX_UINT64; + Status = StrHexToUint64S (String, (CHAR16 **)NULL, &Result); + if (Status == RETURN_INVALID_PARAMETER) { + Result = 0; } return Result; @@ -999,10 +1007,12 @@ AsciiStrDecimalToUintn ( IN CONST CHAR8 *String ) { - UINTN Result; + UINTN Result; + RETURN_STATUS Status; - if (RETURN_ERROR (AsciiStrDecimalToUintnS (String, (CHAR8 **)NULL, &Result))) { - return MAX_UINTN; + Status = AsciiStrDecimalToUintnS (String, (CHAR8 **)NULL, &Result); + if (Status == RETURN_INVALID_PARAMETER) { + Result = 0; } return Result; @@ -1044,10 +1054,12 @@ AsciiStrDecimalToUint64 ( IN CONST CHAR8 *String ) { - UINT64 Result; + UINT64 Result; + RETURN_STATUS Status; - if (RETURN_ERROR (AsciiStrDecimalToUint64S (String, (CHAR8 **)NULL, &Result))) { - return MAX_UINT64; + Status = AsciiStrDecimalToUint64S (String, (CHAR8 **)NULL, &Result); + if (Status == RETURN_INVALID_PARAMETER) { + Result = 0; } return Result; @@ -1093,10 +1105,12 @@ AsciiStrHexToUintn ( IN CONST CHAR8 *String ) { - UINTN Result; + UINTN Result; + RETURN_STATUS Status; - if (RETURN_ERROR (AsciiStrHexToUintnS (String, (CHAR8 **)NULL, &Result))) { - return MAX_UINTN; + Status = AsciiStrHexToUintnS (String, (CHAR8 **)NULL, &Result); + if (Status == RETURN_INVALID_PARAMETER) { + Result = 0; } return Result; @@ -1142,10 +1156,12 @@ AsciiStrHexToUint64 ( IN CONST CHAR8 *String ) { - UINT64 Result; + UINT64 Result; + RETURN_STATUS Status; - if (RETURN_ERROR (AsciiStrHexToUint64S (String, (CHAR8 **)NULL, &Result))) { - return MAX_UINT64; + Status = AsciiStrHexToUint64S (String, (CHAR8 **)NULL, &Result); + if (Status == RETURN_INVALID_PARAMETER) { + Result = 0; } return Result; diff --git a/MdePkg/Library/BasePeCoffLib/BasePeCoff.c b/MdePkg/Library/BasePeCoffLib/BasePeCoff.c index 86ff2e769b00..fab7ab3b4c66 100644 --- a/MdePkg/Library/BasePeCoffLib/BasePeCoff.c +++ b/MdePkg/Library/BasePeCoffLib/BasePeCoff.c @@ -68,7 +68,7 @@ PeCoffLoaderGetPeHeader ( UINTN Size; UINTN ReadSize; UINT32 SectionHeaderOffset; - UINT32 Index; + UINTN Index; UINT32 HeaderWithoutDataDir; CHAR8 BufferData; UINTN NumberOfSections; @@ -1054,7 +1054,7 @@ PeCoffLoaderRelocateImage ( RelocDir = &Hdr.Te->DataDirectory[0]; } - if ((RelocDir != NULL) && (RelocDir->Size > 0)) { + if ((RelocDir != NULL) && (RelocDir->Size > 0) && ((RelocDir->Size - 1) < (MAX_UINT32 - RelocDir->VirtualAddress))) { RelocBase = (EFI_IMAGE_BASE_RELOCATION *)PeCoffLoaderImageAddress (ImageContext, RelocDir->VirtualAddress, TeStrippedOffset); RelocBaseEnd = (EFI_IMAGE_BASE_RELOCATION *)PeCoffLoaderImageAddress ( ImageContext, @@ -1407,7 +1407,7 @@ PeCoffLoaderLoadImage ( return RETURN_LOAD_ERROR; } - if (Section->SizeOfRawData > 0) { + if ((Section->SizeOfRawData > 0) && (Base != NULL)) { Status = ImageContext->ImageRead ( ImageContext->Handle, Section->PointerToRawData - TeStrippedOffset, @@ -1424,7 +1424,7 @@ PeCoffLoaderLoadImage ( // If raw size is less then virtual size, zero fill the remaining // - if (Size < Section->Misc.VirtualSize) { + if ((Size < Section->Misc.VirtualSize) && (Base != NULL)) { ZeroMem (Base + Size, Section->Misc.VirtualSize - Size); } diff --git a/MdePkg/Library/PeiServicesLib/PeiServicesLib.c b/MdePkg/Library/PeiServicesLib/PeiServicesLib.c index 98cc69c3a2bd..16d513498151 100644 --- a/MdePkg/Library/PeiServicesLib/PeiServicesLib.c +++ b/MdePkg/Library/PeiServicesLib/PeiServicesLib.c @@ -685,7 +685,11 @@ InternalPeiServicesInstallFvInfoPpi ( } FvInfoPpiDescriptor = AllocatePool (sizeof (EFI_PEI_PPI_DESCRIPTOR)); - ASSERT (FvInfoPpiDescriptor != NULL); + if (FvInfoPpiDescriptor == NULL) { + ASSERT (FvInfoPpiDescriptor != NULL); + // Need to return here, FV may not be published, but we are out of resources anyway... + return; + } FvInfoPpiDescriptor->Guid = PpiGuid; FvInfoPpiDescriptor->Flags = EFI_PEI_PPI_DESCRIPTOR_PPI | EFI_PEI_PPI_DESCRIPTOR_TERMINATE_LIST; diff --git a/MdePkg/Library/StackCheckLib/Readme.md b/MdePkg/Library/StackCheckLib/Readme.md index 636cd047f086..8d15ad4ca4dd 100644 --- a/MdePkg/Library/StackCheckLib/Readme.md +++ b/MdePkg/Library/StackCheckLib/Readme.md @@ -102,25 +102,93 @@ update the tools_def file so the `___CC_FLAGS` includes edk2 updated the tools_def to add `/GS` to VS2022 and VS2019 IA32/X64 builds and `-fstack-protector` to GCC builds. This will cause stack cookie references to be inserted -throughout the code. Every module should have a `StackCheckLib` instances linked to satisfy +throughout the code. Every module should have a `StackCheckLib` instance linked to satisfy these references. So every module doesn't need to add `StackCheckLib` to the LibraryClasses section of the INF file, `StackCheckLib` instances should be linked as NULL in the platform -DSC fies. The only exception to this is host-based unit tests as they will be compiled with -the runtime libraries which already contain the stack cookie definitions and will collide -with `StackCheckLib`. +DSC files. The only exception to this is MSVC built host-based unit tests as they will be +compiled with the runtime libraries which already contain the stack cookie definitions +and will collide with `StackCheckLib`. A `StackCheckLibHostApplication.inf` is linked +by `UnitTestFrameworkPkg/UnitTestFrameworkPkgHost.dsc.inc` that provides the stack +cookie functions for GCC HOST_APPLICATIONS but not for MSVC HOST_APPLICATIONS. + +### Default Stack Check Library Configuration + +`MdePkg/MdeLibs.dsc.inc` links `StackCheckLibNull` for all types except SEC, HOST_APPLICATION, +and USER_DEFINED in order to not break existing DSCs. SEC cannot be generically linked to +because there are some SEC modules which do not link against the standard entry point +libraries and thus do not get stack cookies inserted by the compiler. USER_DEFINED modules +are by nature different from other modules, so we do not make any assumptions about their +state. + +As stated above, all HOST_APPLICATIONS will link against a HOST_APPLICATION specific +implementation provided in `UnitTestFrameworkPkg/UnitTestFrameworkPkgHost.dsc.inc`. + +To link the rest of a platform's modules to `StackCheckLibNull`, a platform would needs +to link it for all SEC and USER_DEFINED modules. If all of the DSC's SEC and USER_DEFINED +modules link against the entry point libs, it would look like the following: + +```inf +[LibraryClasses.common.SEC, LibraryClasses.common.USER_DEFINED] + NULL|MdePkg/Library/StackCheckLibNull/StackCheckLibNull.inf +``` + +If some do not, then the individual SEC/USER_DEFINED modules that do link against +the entry point libs will need to be linked to `StackCheckLibNull`, such as below. +This case is identifiable if a DSC is built and the linker complains the stack +check functions are not found for a module. + +```inf +UefiCpuPkg/SecCore/SecCore.inf { + + NULL|MdePkg/Library/StackCheckLibNull/StackCheckLibNull.inf + } +``` + +### Custom Stack Check Library Configuration + +In order to use a different instance of StackCheckLib than `MdeLibs.dsc.inc` provides, a DSC +should add the following: + +```inf +[Defines] + DEFINE CUSTOM_STACK_CHECK_LIB = TRUE +``` -SEC and PEI_CORE modules should always use `StackCheckLibNull` and pre-memory modules +This will cause `MdeLibs.dsc.inc` to not link `StackCheckLibNull` and rely on a DSC to +link whichever version(s) of `StackCheckLib` it desires. + +It is recommended that SEC and PEI_CORE modules use `StackCheckLibNull` and pre-memory modules should use `StackCheckLibStaticInit`. All other modules should use `StackCheckLibDynamicInit`. + Below is an **example** of how to link the `StackCheckLib` instances in the platform DSC file but it may need customization based on the platform's requirements: -```text +```inf [LibraryClasses.common.SEC, LibraryClasses.common.PEI_CORE] NULL|MdePkg/Library/StackCheckLibNull/StackCheckLibNull.inf [LibraryClasses.common.PEIM] NULL|MdePkg/Library/StackCheckLib/StackCheckLibStaticInit.inf -[LibraryClasses.common.MM_CORE_STANDALONE, LibraryClasses.common.MM_STANDALONE, LibraryClasses.common.DXE_CORE, LibraryClasses.common.SMM_CORE, LibraryClasses.common.DXE_SMM_DRIVER, LibraryClasses.common.DXE_DRIVER, LibraryClasses.common.DXE_RUNTIME_DRIVER, LibraryClasses.common.DXE_SAL_DRIVER, LibraryClasses.common.UEFI_DRIVER, LibraryClasses.common.UEFI_APPLICATION] +[LibraryClasses.common.MM_CORE_STANDALONE, LibraryClasses.common.MM_STANDALONE, LibraryClasses.common.DXE_CORE, +LibraryClasses.common.SMM_CORE, LibraryClasses.common.DXE_SMM_DRIVER, LibraryClasses.common.DXE_DRIVER, +LibraryClasses.common.DXE_RUNTIME_DRIVER, LibraryClasses.common.DXE_SAL_DRIVER, LibraryClasses.common.UEFI_DRIVER, +LibraryClasses.common.UEFI_APPLICATION] NULL|MdePkg/Library/StackCheckLib/StackCheckLibDynamicInit.inf ``` + +### Disable Stack Check Library + +If a platform would like to disable stack cookies (say for debugging purposes), +they can add the following to their DSC: + +```inf +[BuildOptions] + MSVC:*_*_*_CC_FLAGS = /GS- + GCC:*_*_*_CC_FLAGS = -fno-stack-protector +``` + +The same build options can be put in a module's INF to only disable stack cookies +for that module. + +It is not recommended to disable stack cookie checking in production scenarios. diff --git a/MdePkg/Library/UefiDevicePathLib/DevicePathFromText.c b/MdePkg/Library/UefiDevicePathLib/DevicePathFromText.c index 86ecb66ba36b..27668eee30d9 100644 --- a/MdePkg/Library/UefiDevicePathLib/DevicePathFromText.c +++ b/MdePkg/Library/UefiDevicePathLib/DevicePathFromText.c @@ -269,14 +269,14 @@ IsHexStr ( // // skip preceeding white space // - while ((*Str != 0) && *Str == L' ') { + while (*Str == L' ') { Str++; } // // skip preceeding zeros // - while ((*Str != 0) && *Str == L'0') { + while (*Str == L'0') { Str++; } @@ -388,7 +388,10 @@ DevPathFromTextGenericPath ( (UINT16)(sizeof (EFI_DEVICE_PATH_PROTOCOL) + DataLength) ); - StrHexToBytes (DataStr, DataLength * 2, (UINT8 *)(Node + 1), DataLength); + if (Node != NULL) { + StrHexToBytes (DataStr, DataLength * 2, (UINT8 *)(Node + 1), DataLength); + } + return Node; } @@ -453,8 +456,10 @@ DevPathFromTextPci ( (UINT16)sizeof (PCI_DEVICE_PATH) ); - Pci->Function = (UINT8)Strtoi (FunctionStr); - Pci->Device = (UINT8)Strtoi (DeviceStr); + if (Pci != NULL) { + Pci->Function = (UINT8)Strtoi (FunctionStr); + Pci->Device = (UINT8)Strtoi (DeviceStr); + } return (EFI_DEVICE_PATH_PROTOCOL *)Pci; } @@ -482,7 +487,9 @@ DevPathFromTextPcCard ( (UINT16)sizeof (PCCARD_DEVICE_PATH) ); - Pccard->FunctionNumber = (UINT8)Strtoi (FunctionNumberStr); + if (Pccard != NULL) { + Pccard->FunctionNumber = (UINT8)Strtoi (FunctionNumberStr); + } return (EFI_DEVICE_PATH_PROTOCOL *)Pccard; } @@ -514,9 +521,11 @@ DevPathFromTextMemoryMapped ( (UINT16)sizeof (MEMMAP_DEVICE_PATH) ); - MemMap->MemoryType = (UINT32)Strtoi (MemoryTypeStr); - Strtoi64 (StartingAddressStr, &MemMap->StartingAddress); - Strtoi64 (EndingAddressStr, &MemMap->EndingAddress); + if (MemMap != NULL) { + MemMap->MemoryType = (UINT32)Strtoi (MemoryTypeStr); + Strtoi64 (StartingAddressStr, &MemMap->StartingAddress); + Strtoi64 (EndingAddressStr, &MemMap->EndingAddress); + } return (EFI_DEVICE_PATH_PROTOCOL *)MemMap; } @@ -559,8 +568,10 @@ ConvertFromTextVendor ( (UINT16)(sizeof (VENDOR_DEVICE_PATH) + Length) ); - StrToGuid (GuidStr, &Vendor->Guid); - StrHexToBytes (DataStr, Length * 2, (UINT8 *)(Vendor + 1), Length); + if (Vendor != NULL) { + StrToGuid (GuidStr, &Vendor->Guid); + StrHexToBytes (DataStr, Length * 2, (UINT8 *)(Vendor + 1), Length); + } return (EFI_DEVICE_PATH_PROTOCOL *)Vendor; } @@ -607,7 +618,10 @@ DevPathFromTextCtrl ( HW_CONTROLLER_DP, (UINT16)sizeof (CONTROLLER_DEVICE_PATH) ); - Controller->ControllerNumber = (UINT32)Strtoi (ControllerStr); + + if (Controller != NULL) { + Controller->ControllerNumber = (UINT32)Strtoi (ControllerStr); + } return (EFI_DEVICE_PATH_PROTOCOL *)Controller; } @@ -637,11 +651,13 @@ DevPathFromTextBmc ( (UINT16)sizeof (BMC_DEVICE_PATH) ); - BmcDp->InterfaceType = (UINT8)Strtoi (InterfaceTypeStr); - WriteUnaligned64 ( - (UINT64 *)(&BmcDp->BaseAddress), - StrHexToUint64 (BaseAddressStr) - ); + if (BmcDp != NULL) { + BmcDp->InterfaceType = (UINT8)Strtoi (InterfaceTypeStr); + WriteUnaligned64 ( + (UINT64 *)(&BmcDp->BaseAddress), + StrHexToUint64 (BaseAddressStr) + ); + } return (EFI_DEVICE_PATH_PROTOCOL *)BmcDp; } @@ -706,8 +722,10 @@ DevPathFromTextAcpi ( (UINT16)sizeof (ACPI_HID_DEVICE_PATH) ); - Acpi->HID = EisaIdFromText (HIDStr); - Acpi->UID = (UINT32)Strtoi (UIDStr); + if (Acpi != NULL) { + Acpi->HID = EisaIdFromText (HIDStr); + Acpi->UID = (UINT32)Strtoi (UIDStr); + } return (EFI_DEVICE_PATH_PROTOCOL *)Acpi; } @@ -737,8 +755,10 @@ ConvertFromTextAcpi ( (UINT16)sizeof (ACPI_HID_DEVICE_PATH) ); - Acpi->HID = EFI_PNP_ID (PnPId); - Acpi->UID = (UINT32)Strtoi (UIDStr); + if (Acpi != NULL) { + Acpi->HID = EFI_PNP_ID (PnPId); + Acpi->UID = (UINT32)Strtoi (UIDStr); + } return (EFI_DEVICE_PATH_PROTOCOL *)Acpi; } @@ -878,14 +898,16 @@ DevPathFromTextAcpiEx ( Length ); - AcpiEx->HID = EisaIdFromText (HIDStr); - AcpiEx->CID = EisaIdFromText (CIDStr); - AcpiEx->UID = (UINT32)Strtoi (UIDStr); + if (AcpiEx != NULL) { + AcpiEx->HID = EisaIdFromText (HIDStr); + AcpiEx->CID = EisaIdFromText (CIDStr); + AcpiEx->UID = (UINT32)Strtoi (UIDStr); - AsciiStr = (CHAR8 *)((UINT8 *)AcpiEx + sizeof (ACPI_EXTENDED_HID_DEVICE_PATH)); - StrToAscii (HIDSTRStr, &AsciiStr); - StrToAscii (UIDSTRStr, &AsciiStr); - StrToAscii (CIDSTRStr, &AsciiStr); + AsciiStr = (CHAR8 *)((UINT8 *)AcpiEx + sizeof (ACPI_EXTENDED_HID_DEVICE_PATH)); + StrToAscii (HIDSTRStr, &AsciiStr); + StrToAscii (UIDSTRStr, &AsciiStr); + StrToAscii (CIDSTRStr, &AsciiStr); + } return (EFI_DEVICE_PATH_PROTOCOL *)AcpiEx; } @@ -920,6 +942,10 @@ DevPathFromTextAcpiExp ( Length ); + if (AcpiEx == NULL) { + return (EFI_DEVICE_PATH_PROTOCOL *)AcpiEx; + } + AcpiEx->HID = EisaIdFromText (HIDStr); // // According to UEFI spec, the CID parameter is optional and has a default value of 0. @@ -975,7 +1001,10 @@ DevPathFromTextAcpiAdr ( ACPI_ADR_DP, (UINT16)sizeof (ACPI_ADR_DEVICE_PATH) ); - ASSERT (AcpiAdr != NULL); + if (AcpiAdr == NULL) { + ASSERT (AcpiAdr != NULL); + return (EFI_DEVICE_PATH_PROTOCOL *)AcpiAdr; + } for (Index = 0; ; Index++) { DisplayDeviceStr = GetNextParamStr (&TextDeviceNode); @@ -990,7 +1019,12 @@ DevPathFromTextAcpiAdr ( Length + sizeof (UINT32), AcpiAdr ); - ASSERT (AcpiAdr != NULL); + + if (AcpiAdr == NULL) { + ASSERT (AcpiAdr != NULL); + return (EFI_DEVICE_PATH_PROTOCOL *)AcpiAdr; + } + SetDevicePathNodeLength (AcpiAdr, Length + sizeof (UINT32)); } @@ -1040,6 +1074,10 @@ DevPathFromTextAta ( (UINT16)sizeof (ATAPI_DEVICE_PATH) ); + if (Atapi == NULL) { + return (EFI_DEVICE_PATH_PROTOCOL *)Atapi; + } + PrimarySecondaryStr = GetNextParamStr (&TextDeviceNode); SlaveMasterStr = GetNextParamStr (&TextDeviceNode); LunStr = GetNextParamStr (&TextDeviceNode); @@ -1090,8 +1128,10 @@ DevPathFromTextScsi ( (UINT16)sizeof (SCSI_DEVICE_PATH) ); - Scsi->Pun = (UINT16)Strtoi (PunStr); - Scsi->Lun = (UINT16)Strtoi (LunStr); + if (Scsi != NULL) { + Scsi->Pun = (UINT16)Strtoi (PunStr); + Scsi->Lun = (UINT16)Strtoi (LunStr); + } return (EFI_DEVICE_PATH_PROTOCOL *)Scsi; } @@ -1121,9 +1161,11 @@ DevPathFromTextFibre ( (UINT16)sizeof (FIBRECHANNEL_DEVICE_PATH) ); - Fibre->Reserved = 0; - Strtoi64 (WWNStr, &Fibre->WWN); - Strtoi64 (LunStr, &Fibre->Lun); + if (Fibre != NULL) { + Fibre->Reserved = 0; + Strtoi64 (WWNStr, &Fibre->WWN); + Strtoi64 (LunStr, &Fibre->Lun); + } return (EFI_DEVICE_PATH_PROTOCOL *)Fibre; } @@ -1153,12 +1195,14 @@ DevPathFromTextFibreEx ( (UINT16)sizeof (FIBRECHANNELEX_DEVICE_PATH) ); - FibreEx->Reserved = 0; - Strtoi64 (WWNStr, (UINT64 *)(&FibreEx->WWN)); - Strtoi64 (LunStr, (UINT64 *)(&FibreEx->Lun)); + if (FibreEx != NULL) { + FibreEx->Reserved = 0; + Strtoi64 (WWNStr, (UINT64 *)(&FibreEx->WWN)); + Strtoi64 (LunStr, (UINT64 *)(&FibreEx->Lun)); - *(UINT64 *)(&FibreEx->WWN) = SwapBytes64 (*(UINT64 *)(&FibreEx->WWN)); - *(UINT64 *)(&FibreEx->Lun) = SwapBytes64 (*(UINT64 *)(&FibreEx->Lun)); + *(UINT64 *)(&FibreEx->WWN) = SwapBytes64 (*(UINT64 *)(&FibreEx->WWN)); + *(UINT64 *)(&FibreEx->Lun) = SwapBytes64 (*(UINT64 *)(&FibreEx->Lun)); + } return (EFI_DEVICE_PATH_PROTOCOL *)FibreEx; } @@ -1186,8 +1230,10 @@ DevPathFromText1394 ( (UINT16)sizeof (F1394_DEVICE_PATH) ); - F1394DevPath->Reserved = 0; - F1394DevPath->Guid = StrHexToUint64 (GuidStr); + if (F1394DevPath != NULL) { + F1394DevPath->Reserved = 0; + F1394DevPath->Guid = StrHexToUint64 (GuidStr); + } return (EFI_DEVICE_PATH_PROTOCOL *)F1394DevPath; } @@ -1217,8 +1263,10 @@ DevPathFromTextUsb ( (UINT16)sizeof (USB_DEVICE_PATH) ); - Usb->ParentPortNumber = (UINT8)Strtoi (PortStr); - Usb->InterfaceNumber = (UINT8)Strtoi (InterfaceStr); + if (Usb != NULL) { + Usb->ParentPortNumber = (UINT8)Strtoi (PortStr); + Usb->InterfaceNumber = (UINT8)Strtoi (InterfaceStr); + } return (EFI_DEVICE_PATH_PROTOCOL *)Usb; } @@ -1246,7 +1294,9 @@ DevPathFromTextI2O ( (UINT16)sizeof (I2O_DEVICE_PATH) ); - I2ODevPath->Tid = (UINT32)Strtoi (TIDStr); + if (I2ODevPath != NULL) { + I2ODevPath->Tid = (UINT32)Strtoi (TIDStr); + } return (EFI_DEVICE_PATH_PROTOCOL *)I2ODevPath; } @@ -1282,11 +1332,13 @@ DevPathFromTextInfiniband ( (UINT16)sizeof (INFINIBAND_DEVICE_PATH) ); - InfiniBand->ResourceFlags = (UINT32)Strtoi (FlagsStr); - StrToGuid (GuidStr, (EFI_GUID *)InfiniBand->PortGid); - Strtoi64 (SidStr, &InfiniBand->ServiceId); - Strtoi64 (TidStr, &InfiniBand->TargetPortId); - Strtoi64 (DidStr, &InfiniBand->DeviceId); + if (InfiniBand != NULL) { + InfiniBand->ResourceFlags = (UINT32)Strtoi (FlagsStr); + StrToGuid (GuidStr, (EFI_GUID *)InfiniBand->PortGid); + Strtoi64 (SidStr, &InfiniBand->ServiceId); + Strtoi64 (TidStr, &InfiniBand->TargetPortId); + Strtoi64 (DidStr, &InfiniBand->DeviceId); + } return (EFI_DEVICE_PATH_PROTOCOL *)InfiniBand; } @@ -1331,7 +1383,10 @@ DevPathFromTextVenPcAnsi ( MSG_VENDOR_DP, (UINT16)sizeof (VENDOR_DEVICE_PATH) ); - CopyGuid (&Vendor->Guid, &gEfiPcAnsiGuid); + + if (Vendor != NULL) { + CopyGuid (&Vendor->Guid, &gEfiPcAnsiGuid); + } return (EFI_DEVICE_PATH_PROTOCOL *)Vendor; } @@ -1356,7 +1411,10 @@ DevPathFromTextVenVt100 ( MSG_VENDOR_DP, (UINT16)sizeof (VENDOR_DEVICE_PATH) ); - CopyGuid (&Vendor->Guid, &gEfiVT100Guid); + + if (Vendor != NULL) { + CopyGuid (&Vendor->Guid, &gEfiVT100Guid); + } return (EFI_DEVICE_PATH_PROTOCOL *)Vendor; } @@ -1381,7 +1439,10 @@ DevPathFromTextVenVt100Plus ( MSG_VENDOR_DP, (UINT16)sizeof (VENDOR_DEVICE_PATH) ); - CopyGuid (&Vendor->Guid, &gEfiVT100PlusGuid); + + if (Vendor != NULL) { + CopyGuid (&Vendor->Guid, &gEfiVT100PlusGuid); + } return (EFI_DEVICE_PATH_PROTOCOL *)Vendor; } @@ -1406,7 +1467,10 @@ DevPathFromTextVenUtf8 ( MSG_VENDOR_DP, (UINT16)sizeof (VENDOR_DEVICE_PATH) ); - CopyGuid (&Vendor->Guid, &gEfiVTUTF8Guid); + + if (Vendor != NULL) { + CopyGuid (&Vendor->Guid, &gEfiVTUTF8Guid); + } return (EFI_DEVICE_PATH_PROTOCOL *)Vendor; } @@ -1434,13 +1498,15 @@ DevPathFromTextUartFlowCtrl ( (UINT16)sizeof (UART_FLOW_CONTROL_DEVICE_PATH) ); - CopyGuid (&UartFlowControl->Guid, &gEfiUartDevicePathGuid); - if (StrCmp (ValueStr, L"XonXoff") == 0) { - UartFlowControl->FlowControlMap = 2; - } else if (StrCmp (ValueStr, L"Hardware") == 0) { - UartFlowControl->FlowControlMap = 1; - } else { - UartFlowControl->FlowControlMap = 0; + if (UartFlowControl != NULL) { + CopyGuid (&UartFlowControl->Guid, &gEfiUartDevicePathGuid); + if (StrCmp (ValueStr, L"XonXoff") == 0) { + UartFlowControl->FlowControlMap = 2; + } else if (StrCmp (ValueStr, L"Hardware") == 0) { + UartFlowControl->FlowControlMap = 1; + } else { + UartFlowControl->FlowControlMap = 0; + } } return (EFI_DEVICE_PATH_PROTOCOL *)UartFlowControl; @@ -1485,6 +1551,10 @@ DevPathFromTextSAS ( (UINT16)sizeof (SAS_DEVICE_PATH) ); + if (Sas == NULL) { + return (EFI_DEVICE_PATH_PROTOCOL *)Sas; + } + CopyGuid (&Sas->Guid, &gEfiSasDevicePathGuid); Strtoi64 (AddressStr, &Sas->SasAddress); Strtoi64 (LunStr, &Sas->Lun); @@ -1580,6 +1650,10 @@ DevPathFromTextSasEx ( (UINT16)sizeof (SASEX_DEVICE_PATH) ); + if (SasEx == NULL) { + return (EFI_DEVICE_PATH_PROTOCOL *)SasEx; + } + Strtoi64 (AddressStr, &SasAddress); Strtoi64 (LunStr, &Lun); WriteUnaligned64 ((UINT64 *)&SasEx->SasAddress, SwapBytes64 (SasAddress)); @@ -1663,12 +1737,14 @@ DevPathFromTextNVMe ( (UINT16)sizeof (NVME_NAMESPACE_DEVICE_PATH) ); - Nvme->NamespaceId = (UINT32)Strtoi (NamespaceIdStr); - Uuid = (UINT8 *)&Nvme->NamespaceUuid; + if (Nvme != NULL) { + Nvme->NamespaceId = (UINT32)Strtoi (NamespaceIdStr); + Uuid = (UINT8 *)&Nvme->NamespaceUuid; - Index = sizeof (Nvme->NamespaceUuid) / sizeof (UINT8); - while (Index-- != 0) { - Uuid[Index] = (UINT8)StrHexToUintn (SplitStr (&NamespaceUuidStr, L'-')); + Index = sizeof (Nvme->NamespaceUuid) / sizeof (UINT8); + while (Index-- != 0) { + Uuid[Index] = (UINT8)StrHexToUintn (SplitStr (&NamespaceUuidStr, L'-')); + } } return (EFI_DEVICE_PATH_PROTOCOL *)Nvme; @@ -1699,8 +1775,10 @@ DevPathFromTextUfs ( (UINT16)sizeof (UFS_DEVICE_PATH) ); - Ufs->Pun = (UINT8)Strtoi (PunStr); - Ufs->Lun = (UINT8)Strtoi (LunStr); + if (Ufs != NULL) { + Ufs->Pun = (UINT8)Strtoi (PunStr); + Ufs->Lun = (UINT8)Strtoi (LunStr); + } return (EFI_DEVICE_PATH_PROTOCOL *)Ufs; } @@ -1728,7 +1806,9 @@ DevPathFromTextSd ( (UINT16)sizeof (SD_DEVICE_PATH) ); - Sd->SlotNumber = (UINT8)Strtoi (SlotNumberStr); + if (Sd != NULL) { + Sd->SlotNumber = (UINT8)Strtoi (SlotNumberStr); + } return (EFI_DEVICE_PATH_PROTOCOL *)Sd; } @@ -1756,7 +1836,9 @@ DevPathFromTextEmmc ( (UINT16)sizeof (EMMC_DEVICE_PATH) ); - Emmc->SlotNumber = (UINT8)Strtoi (SlotNumberStr); + if (Emmc != NULL) { + Emmc->SlotNumber = (UINT8)Strtoi (SlotNumberStr); + } return (EFI_DEVICE_PATH_PROTOCOL *)Emmc; } @@ -1782,7 +1864,9 @@ DevPathFromTextDebugPort ( (UINT16)sizeof (VENDOR_DEVICE_PATH) ); - CopyGuid (&Vend->Guid, &gEfiDebugPortProtocolGuid); + if (Vend != NULL) { + CopyGuid (&Vend->Guid, &gEfiDebugPortProtocolGuid); + } return (EFI_DEVICE_PATH_PROTOCOL *)Vend; } @@ -1813,14 +1897,16 @@ DevPathFromTextMAC ( (UINT16)sizeof (MAC_ADDR_DEVICE_PATH) ); - MACDevPath->IfType = (UINT8)Strtoi (IfTypeStr); + if (MACDevPath != NULL) { + MACDevPath->IfType = (UINT8)Strtoi (IfTypeStr); - Length = sizeof (EFI_MAC_ADDRESS); - if ((MACDevPath->IfType == 0x01) || (MACDevPath->IfType == 0x00)) { - Length = 6; - } + Length = sizeof (EFI_MAC_ADDRESS); + if ((MACDevPath->IfType == 0x01) || (MACDevPath->IfType == 0x00)) { + Length = 6; + } - StrHexToBytes (AddressStr, Length * 2, MACDevPath->MacAddress.Addr, Length); + StrHexToBytes (AddressStr, Length * 2, MACDevPath->MacAddress.Addr, Length); + } return (EFI_DEVICE_PATH_PROTOCOL *)MACDevPath; } @@ -1882,6 +1968,10 @@ DevPathFromTextIPv4 ( (UINT16)sizeof (IPv4_DEVICE_PATH) ); + if (IPv4 == NULL) { + return (EFI_DEVICE_PATH_PROTOCOL *)IPv4; + } + StrToIpv4Address (RemoteIPStr, NULL, &IPv4->RemoteIpAddress, NULL); IPv4->Protocol = (UINT16)NetworkProtocolFromText (ProtocolStr); if (StrCmp (TypeStr, L"Static") == 0) { @@ -1938,6 +2028,10 @@ DevPathFromTextIPv6 ( (UINT16)sizeof (IPv6_DEVICE_PATH) ); + if (IPv6 == NULL) { + return (EFI_DEVICE_PATH_PROTOCOL *)IPv6; + } + StrToIpv6Address (RemoteIPStr, NULL, &IPv6->RemoteIpAddress, NULL); IPv6->Protocol = (UINT16)NetworkProtocolFromText (ProtocolStr); if (StrCmp (TypeStr, L"Static") == 0) { @@ -1992,6 +2086,10 @@ DevPathFromTextUart ( (UINT16)sizeof (UART_DEVICE_PATH) ); + if (Uart == NULL) { + return (EFI_DEVICE_PATH_PROTOCOL *)Uart; + } + if (StrCmp (BaudStr, L"DEFAULT") == 0) { Uart->BaudRate = 115200; } else { @@ -2072,6 +2170,10 @@ ConvertFromTextUsbClass ( (UINT16)sizeof (USB_CLASS_DEVICE_PATH) ); + if (UsbClass == NULL) { + return (EFI_DEVICE_PATH_PROTOCOL *)UsbClass; + } + VIDStr = GetNextParamStr (&TextDeviceNode); PIDStr = GetNextParamStr (&TextDeviceNode); if (UsbClassText->ClassExist) { @@ -2513,19 +2615,22 @@ DevPathFromTextUsbWwid ( MSG_USB_WWID_DP, (UINT16)(sizeof (USB_WWID_DEVICE_PATH) + SerialNumberStrLen * sizeof (CHAR16)) ); - UsbWwid->VendorId = (UINT16)Strtoi (VIDStr); - UsbWwid->ProductId = (UINT16)Strtoi (PIDStr); - UsbWwid->InterfaceNumber = (UINT16)Strtoi (InterfaceNumStr); - // - // There is no memory allocated in UsbWwid for the '\0' in SerialNumberStr. - // Therefore, the '\0' will not be copied. - // - CopyMem ( - (UINT8 *)UsbWwid + sizeof (USB_WWID_DEVICE_PATH), - SerialNumberStr, - SerialNumberStrLen * sizeof (CHAR16) - ); + if (UsbWwid != NULL) { + UsbWwid->VendorId = (UINT16)Strtoi (VIDStr); + UsbWwid->ProductId = (UINT16)Strtoi (PIDStr); + UsbWwid->InterfaceNumber = (UINT16)Strtoi (InterfaceNumStr); + + // + // There is no memory allocated in UsbWwid for the '\0' in SerialNumberStr. + // Therefore, the '\0' will not be copied. + // + CopyMem ( + (UINT8 *)UsbWwid + sizeof (USB_WWID_DEVICE_PATH), + SerialNumberStr, + SerialNumberStrLen * sizeof (CHAR16) + ); + } return (EFI_DEVICE_PATH_PROTOCOL *)UsbWwid; } @@ -2553,7 +2658,9 @@ DevPathFromTextUnit ( (UINT16)sizeof (DEVICE_LOGICAL_UNIT_DEVICE_PATH) ); - LogicalUnit->Lun = (UINT8)Strtoi (LunStr); + if (LogicalUnit != NULL) { + LogicalUnit->Lun = (UINT8)Strtoi (LunStr); + } return (EFI_DEVICE_PATH_PROTOCOL *)LogicalUnit; } @@ -2596,6 +2703,10 @@ DevPathFromTextiSCSI ( (UINT16)(sizeof (ISCSI_DEVICE_PATH_WITH_NAME) + StrLen (NameStr)) ); + if (ISCSIDevPath == NULL) { + return (EFI_DEVICE_PATH_PROTOCOL *)ISCSIDevPath; + } + AsciiStr = ISCSIDevPath->TargetName; StrToAscii (NameStr, &AsciiStr); @@ -2657,7 +2768,9 @@ DevPathFromTextVlan ( (UINT16)sizeof (VLAN_DEVICE_PATH) ); - Vlan->VlanId = (UINT16)Strtoi (VlanStr); + if (Vlan != NULL) { + Vlan->VlanId = (UINT16)Strtoi (VlanStr); + } return (EFI_DEVICE_PATH_PROTOCOL *)Vlan; } @@ -2684,12 +2797,16 @@ DevPathFromTextBluetooth ( MSG_BLUETOOTH_DP, (UINT16)sizeof (BLUETOOTH_DEVICE_PATH) ); - StrHexToBytes ( - BluetoothStr, - sizeof (BLUETOOTH_ADDRESS) * 2, - BluetoothDp->BD_ADDR.Address, - sizeof (BLUETOOTH_ADDRESS) - ); + + if (BluetoothDp != NULL) { + StrHexToBytes ( + BluetoothStr, + sizeof (BLUETOOTH_ADDRESS) * 2, + BluetoothDp->BD_ADDR.Address, + sizeof (BLUETOOTH_ADDRESS) + ); + } + return (EFI_DEVICE_PATH_PROTOCOL *)BluetoothDp; } @@ -2718,7 +2835,7 @@ DevPathFromTextWiFi ( (UINT16)sizeof (WIFI_DEVICE_PATH) ); - if (NULL != SSIdStr) { + if ((NULL != SSIdStr) && (NULL != WiFiDp)) { DataLen = StrLen (SSIdStr); if (StrLen (SSIdStr) > 32) { SSIdStr[32] = L'\0'; @@ -2757,13 +2874,16 @@ DevPathFromTextBluetoothLE ( (UINT16)sizeof (BLUETOOTH_LE_DEVICE_PATH) ); - BluetoothLeDp->Address.Type = (UINT8)Strtoi (BluetoothLeAddrTypeStr); - StrHexToBytes ( - BluetoothLeAddrStr, - sizeof (BluetoothLeDp->Address.Address) * 2, - BluetoothLeDp->Address.Address, - sizeof (BluetoothLeDp->Address.Address) - ); + if (BluetoothLeDp != NULL) { + BluetoothLeDp->Address.Type = (UINT8)Strtoi (BluetoothLeAddrTypeStr); + StrHexToBytes ( + BluetoothLeAddrStr, + sizeof (BluetoothLeDp->Address.Address) * 2, + BluetoothLeDp->Address.Address, + sizeof (BluetoothLeDp->Address.Address) + ); + } + return (EFI_DEVICE_PATH_PROTOCOL *)BluetoothLeDp; } @@ -2883,7 +3003,7 @@ DevPathFromTextUri ( (UINT16)(sizeof (URI_DEVICE_PATH) + UriLength) ); - while (UriLength-- != 0) { + while (Uri != NULL && UriLength-- != 0) { Uri->Uri[UriLength] = (CHAR8)UriStr[UriLength]; } @@ -2938,6 +3058,10 @@ DevPathFromTextHD ( (UINT16)sizeof (HARDDRIVE_DEVICE_PATH) ); + if (Hd == NULL) { + return (EFI_DEVICE_PATH_PROTOCOL *)Hd; + } + Hd->PartitionNumber = (UINT32)Strtoi (PartitionStr); ZeroMem (Hd->Signature, 16); @@ -2991,9 +3115,11 @@ DevPathFromTextCDROM ( (UINT16)sizeof (CDROM_DEVICE_PATH) ); - CDROMDevPath->BootEntry = (UINT32)Strtoi (EntryStr); - Strtoi64 (StartStr, &CDROMDevPath->PartitionStart); - Strtoi64 (SizeStr, &CDROMDevPath->PartitionSize); + if (CDROMDevPath != NULL) { + CDROMDevPath->BootEntry = (UINT32)Strtoi (EntryStr); + Strtoi64 (StartStr, &CDROMDevPath->PartitionStart); + Strtoi64 (SizeStr, &CDROMDevPath->PartitionSize); + } return (EFI_DEVICE_PATH_PROTOCOL *)CDROMDevPath; } @@ -3039,7 +3165,9 @@ DevPathFromTextFilePath ( (UINT16)(sizeof (FILEPATH_DEVICE_PATH) + StrLen (TextDeviceNode) * 2) ); - StrCpyS (File->PathName, StrLen (TextDeviceNode) + 1, TextDeviceNode); + if (File != NULL) { + StrCpyS (File->PathName, StrLen (TextDeviceNode) + 1, TextDeviceNode); + } return (EFI_DEVICE_PATH_PROTOCOL *)File; } @@ -3067,7 +3195,9 @@ DevPathFromTextMedia ( (UINT16)sizeof (MEDIA_PROTOCOL_DEVICE_PATH) ); - StrToGuid (GuidStr, &Media->Protocol); + if (Media != NULL) { + StrToGuid (GuidStr, &Media->Protocol); + } return (EFI_DEVICE_PATH_PROTOCOL *)Media; } @@ -3095,7 +3225,9 @@ DevPathFromTextFv ( (UINT16)sizeof (MEDIA_FW_VOL_DEVICE_PATH) ); - StrToGuid (GuidStr, &Fv->FvName); + if (Fv != NULL) { + StrToGuid (GuidStr, &Fv->FvName); + } return (EFI_DEVICE_PATH_PROTOCOL *)Fv; } @@ -3123,7 +3255,9 @@ DevPathFromTextFvFile ( (UINT16)sizeof (MEDIA_FW_VOL_FILEPATH_DEVICE_PATH) ); - StrToGuid (GuidStr, &FvFile->FvFileName); + if (FvFile != NULL) { + StrToGuid (GuidStr, &FvFile->FvFileName); + } return (EFI_DEVICE_PATH_PROTOCOL *)FvFile; } @@ -3153,8 +3287,10 @@ DevPathFromTextRelativeOffsetRange ( (UINT16)sizeof (MEDIA_RELATIVE_OFFSET_RANGE_DEVICE_PATH) ); - Strtoi64 (StartingOffsetStr, &Offset->StartingOffset); - Strtoi64 (EndingOffsetStr, &Offset->EndingOffset); + if (Offset != NULL) { + Strtoi64 (StartingOffsetStr, &Offset->StartingOffset); + Strtoi64 (EndingOffsetStr, &Offset->EndingOffset); + } return (EFI_DEVICE_PATH_PROTOCOL *)Offset; } @@ -3190,12 +3326,14 @@ DevPathFromTextRamDisk ( (UINT16)sizeof (MEDIA_RAM_DISK_DEVICE_PATH) ); - Strtoi64 (StartingAddrStr, &StartingAddr); - WriteUnaligned64 ((UINT64 *)&(RamDisk->StartingAddr[0]), StartingAddr); - Strtoi64 (EndingAddrStr, &EndingAddr); - WriteUnaligned64 ((UINT64 *)&(RamDisk->EndingAddr[0]), EndingAddr); - RamDisk->Instance = (UINT16)Strtoi (InstanceStr); - StrToGuid (TypeGuidStr, &RamDisk->TypeGuid); + if (RamDisk != NULL) { + Strtoi64 (StartingAddrStr, &StartingAddr); + WriteUnaligned64 ((UINT64 *)&(RamDisk->StartingAddr[0]), StartingAddr); + Strtoi64 (EndingAddrStr, &EndingAddr); + WriteUnaligned64 ((UINT64 *)&(RamDisk->EndingAddr[0]), EndingAddr); + RamDisk->Instance = (UINT16)Strtoi (InstanceStr); + StrToGuid (TypeGuidStr, &RamDisk->TypeGuid); + } return (EFI_DEVICE_PATH_PROTOCOL *)RamDisk; } @@ -3230,12 +3368,14 @@ DevPathFromTextVirtualDisk ( (UINT16)sizeof (MEDIA_RAM_DISK_DEVICE_PATH) ); - Strtoi64 (StartingAddrStr, &StartingAddr); - WriteUnaligned64 ((UINT64 *)&(RamDisk->StartingAddr[0]), StartingAddr); - Strtoi64 (EndingAddrStr, &EndingAddr); - WriteUnaligned64 ((UINT64 *)&(RamDisk->EndingAddr[0]), EndingAddr); - RamDisk->Instance = (UINT16)Strtoi (InstanceStr); - CopyGuid (&RamDisk->TypeGuid, &gEfiVirtualDiskGuid); + if (RamDisk != NULL) { + Strtoi64 (StartingAddrStr, &StartingAddr); + WriteUnaligned64 ((UINT64 *)&(RamDisk->StartingAddr[0]), StartingAddr); + Strtoi64 (EndingAddrStr, &EndingAddr); + WriteUnaligned64 ((UINT64 *)&(RamDisk->EndingAddr[0]), EndingAddr); + RamDisk->Instance = (UINT16)Strtoi (InstanceStr); + CopyGuid (&RamDisk->TypeGuid, &gEfiVirtualDiskGuid); + } return (EFI_DEVICE_PATH_PROTOCOL *)RamDisk; } @@ -3270,12 +3410,14 @@ DevPathFromTextVirtualCd ( (UINT16)sizeof (MEDIA_RAM_DISK_DEVICE_PATH) ); - Strtoi64 (StartingAddrStr, &StartingAddr); - WriteUnaligned64 ((UINT64 *)&(RamDisk->StartingAddr[0]), StartingAddr); - Strtoi64 (EndingAddrStr, &EndingAddr); - WriteUnaligned64 ((UINT64 *)&(RamDisk->EndingAddr[0]), EndingAddr); - RamDisk->Instance = (UINT16)Strtoi (InstanceStr); - CopyGuid (&RamDisk->TypeGuid, &gEfiVirtualCdGuid); + if (RamDisk != NULL) { + Strtoi64 (StartingAddrStr, &StartingAddr); + WriteUnaligned64 ((UINT64 *)&(RamDisk->StartingAddr[0]), StartingAddr); + Strtoi64 (EndingAddrStr, &EndingAddr); + WriteUnaligned64 ((UINT64 *)&(RamDisk->EndingAddr[0]), EndingAddr); + RamDisk->Instance = (UINT16)Strtoi (InstanceStr); + CopyGuid (&RamDisk->TypeGuid, &gEfiVirtualCdGuid); + } return (EFI_DEVICE_PATH_PROTOCOL *)RamDisk; } @@ -3310,12 +3452,14 @@ DevPathFromTextPersistentVirtualDisk ( (UINT16)sizeof (MEDIA_RAM_DISK_DEVICE_PATH) ); - Strtoi64 (StartingAddrStr, &StartingAddr); - WriteUnaligned64 ((UINT64 *)&(RamDisk->StartingAddr[0]), StartingAddr); - Strtoi64 (EndingAddrStr, &EndingAddr); - WriteUnaligned64 ((UINT64 *)&(RamDisk->EndingAddr[0]), EndingAddr); - RamDisk->Instance = (UINT16)Strtoi (InstanceStr); - CopyGuid (&RamDisk->TypeGuid, &gEfiPersistentVirtualDiskGuid); + if (RamDisk != NULL) { + Strtoi64 (StartingAddrStr, &StartingAddr); + WriteUnaligned64 ((UINT64 *)&(RamDisk->StartingAddr[0]), StartingAddr); + Strtoi64 (EndingAddrStr, &EndingAddr); + WriteUnaligned64 ((UINT64 *)&(RamDisk->EndingAddr[0]), EndingAddr); + RamDisk->Instance = (UINT16)Strtoi (InstanceStr); + CopyGuid (&RamDisk->TypeGuid, &gEfiPersistentVirtualDiskGuid); + } return (EFI_DEVICE_PATH_PROTOCOL *)RamDisk; } @@ -3350,12 +3494,14 @@ DevPathFromTextPersistentVirtualCd ( (UINT16)sizeof (MEDIA_RAM_DISK_DEVICE_PATH) ); - Strtoi64 (StartingAddrStr, &StartingAddr); - WriteUnaligned64 ((UINT64 *)&(RamDisk->StartingAddr[0]), StartingAddr); - Strtoi64 (EndingAddrStr, &EndingAddr); - WriteUnaligned64 ((UINT64 *)&(RamDisk->EndingAddr[0]), EndingAddr); - RamDisk->Instance = (UINT16)Strtoi (InstanceStr); - CopyGuid (&RamDisk->TypeGuid, &gEfiPersistentVirtualCdGuid); + if (RamDisk != NULL) { + Strtoi64 (StartingAddrStr, &StartingAddr); + WriteUnaligned64 ((UINT64 *)&(RamDisk->StartingAddr[0]), StartingAddr); + Strtoi64 (EndingAddrStr, &EndingAddr); + WriteUnaligned64 ((UINT64 *)&(RamDisk->EndingAddr[0]), EndingAddr); + RamDisk->Instance = (UINT16)Strtoi (InstanceStr); + CopyGuid (&RamDisk->TypeGuid, &gEfiPersistentVirtualCdGuid); + } return (EFI_DEVICE_PATH_PROTOCOL *)RamDisk; } @@ -3404,6 +3550,10 @@ DevPathFromTextBBS ( (UINT16)(sizeof (BBS_BBS_DEVICE_PATH) + StrLen (IdStr)) ); + if (Bbs == NULL) { + return (EFI_DEVICE_PATH_PROTOCOL *)Bbs; + } + if (StrCmp (TypeStr, L"Floppy") == 0) { Bbs->DeviceType = BBS_TYPE_FLOPPY; } else if (StrCmp (TypeStr, L"HD") == 0) { @@ -3455,6 +3605,11 @@ DevPathFromTextSata ( MSG_SATA_DP, (UINT16)sizeof (SATA_DEVICE_PATH) ); + + if (Sata == NULL) { + return (EFI_DEVICE_PATH_PROTOCOL *)Sata; + } + Sata->HBAPortNumber = (UINT16)Strtoi (Param1); // @@ -3652,29 +3807,54 @@ UefiDevicePathLibConvertTextToDevicePath ( } DevicePath = (EFI_DEVICE_PATH_PROTOCOL *)AllocatePool (END_DEVICE_PATH_LENGTH); - ASSERT (DevicePath != NULL); + + if (DevicePath == NULL) { + ASSERT (DevicePath != NULL); + return NULL; + } + SetDevicePathEndNode (DevicePath); DevicePathStr = UefiDevicePathLibStrDuplicate (TextDevicePath); + if (DevicePathStr == NULL) { + return NULL; + } + Str = DevicePathStr; while ((DeviceNodeStr = GetNextDeviceNodeStr (&Str, &IsInstanceEnd)) != NULL) { DeviceNode = UefiDevicePathLibConvertTextToDeviceNode (DeviceNodeStr); NewDevicePath = AppendDevicePathNode (DevicePath, DeviceNode); - FreePool (DevicePath); - FreePool (DeviceNode); + if (DevicePath != NULL) { + FreePool (DevicePath); + } + + if (DeviceNode != NULL) { + FreePool (DeviceNode); + } + DevicePath = NewDevicePath; if (IsInstanceEnd) { DeviceNode = (EFI_DEVICE_PATH_PROTOCOL *)AllocatePool (END_DEVICE_PATH_LENGTH); - ASSERT (DeviceNode != NULL); + if (DeviceNode == NULL) { + ASSERT (DeviceNode != NULL); + return NULL; + } + SetDevicePathEndNode (DeviceNode); DeviceNode->SubType = END_INSTANCE_DEVICE_PATH_SUBTYPE; NewDevicePath = AppendDevicePathNode (DevicePath, DeviceNode); - FreePool (DevicePath); - FreePool (DeviceNode); + if (DevicePath != NULL) { + FreePool (DevicePath); + } + + if (DeviceNode != NULL) { + FreePool (DeviceNode); + } + DevicePath = NewDevicePath; } } diff --git a/MdePkg/Library/UefiDevicePathLib/DevicePathToText.c b/MdePkg/Library/UefiDevicePathLib/DevicePathToText.c index afbd590787f4..e827daed5a8d 100644 --- a/MdePkg/Library/UefiDevicePathLib/DevicePathToText.c +++ b/MdePkg/Library/UefiDevicePathLib/DevicePathToText.c @@ -1842,7 +1842,11 @@ DevPathToTextUri ( Uri = DevPath; UriLength = DevicePathNodeLength (Uri) - sizeof (URI_DEVICE_PATH); UriStr = AllocatePool (UriLength + 1); - ASSERT (UriStr != NULL); + + if (UriStr == NULL) { + ASSERT (UriStr != NULL); + return; + } CopyMem (UriStr, Uri->Uri, UriLength); UriStr[UriLength] = '\0'; diff --git a/MdePkg/Library/UefiFileHandleLib/UefiFileHandleLib.c b/MdePkg/Library/UefiFileHandleLib/UefiFileHandleLib.c index 86678e965d99..642b754d64ae 100644 --- a/MdePkg/Library/UefiFileHandleLib/UefiFileHandleLib.c +++ b/MdePkg/Library/UefiFileHandleLib/UefiFileHandleLib.c @@ -930,6 +930,11 @@ FileHandleReturnLine ( Status = FileHandleReadLine (Handle, RetVal, &Size, FALSE, Ascii); if (Status == EFI_BUFFER_TOO_SMALL) { RetVal = AllocateZeroPool (Size); + + if (RetVal == NULL) { + return NULL; + } + Status = FileHandleReadLine (Handle, RetVal, &Size, FALSE, Ascii); } diff --git a/MdePkg/Library/UefiLib/Acpi.c b/MdePkg/Library/UefiLib/Acpi.c index 397fde24ed7b..983d3774c3e9 100644 --- a/MdePkg/Library/UefiLib/Acpi.c +++ b/MdePkg/Library/UefiLib/Acpi.c @@ -220,7 +220,12 @@ LocateAcpiTableInAcpiConfigurationTable ( NULL, NULL ); - Table = LocateAcpiDsdtFromFadt (Fadt); + + if (Fadt != NULL) { + Table = LocateAcpiDsdtFromFadt (Fadt); + } else { + Table = NULL; + } } else if (Signature == EFI_ACPI_2_0_FIRMWARE_ACPI_CONTROL_STRUCTURE_SIGNATURE) { ASSERT (PreviousTable == NULL); // @@ -234,7 +239,12 @@ LocateAcpiTableInAcpiConfigurationTable ( NULL, NULL ); - Table = LocateAcpiFacsFromFadt (Fadt); + + if (Fadt != NULL) { + Table = LocateAcpiFacsFromFadt (Fadt); + } else { + Table = NULL; + } } else { Table = ScanTableInSDT ( Xsdt, @@ -275,7 +285,12 @@ LocateAcpiTableInAcpiConfigurationTable ( NULL, NULL ); - Table = LocateAcpiDsdtFromFadt (Fadt); + + if (Fadt != NULL) { + Table = LocateAcpiDsdtFromFadt (Fadt); + } else { + Table = NULL; + } } else if (Signature == EFI_ACPI_2_0_FIRMWARE_ACPI_CONTROL_STRUCTURE_SIGNATURE) { ASSERT (PreviousTable == NULL); // @@ -289,7 +304,12 @@ LocateAcpiTableInAcpiConfigurationTable ( NULL, NULL ); - Table = LocateAcpiFacsFromFadt (Fadt); + + if (Fadt != NULL) { + Table = LocateAcpiFacsFromFadt (Fadt); + } else { + Table = NULL; + } } else { Table = ScanTableInSDT ( Rsdt, diff --git a/MdePkg/Library/UefiLib/Console.c b/MdePkg/Library/UefiLib/Console.c index c37e3d0f5810..fc181316807c 100644 --- a/MdePkg/Library/UefiLib/Console.c +++ b/MdePkg/Library/UefiLib/Console.c @@ -477,7 +477,11 @@ CreatePopUp ( // Allocate a buffer for a single line of the popup with borders and a Null-terminator // Line = AllocateZeroPool ((MaxLength + 3) * sizeof (CHAR16)); - ASSERT (Line != NULL); + + if (Line == NULL) { + ASSERT (Line != NULL); + return; + } // // Draw top of popup box @@ -513,7 +517,12 @@ CreatePopUp ( // UefiLibGetStringWidth (String, TRUE, MaxLength, &Length); TmpString = AllocateZeroPool ((Length + 1) * sizeof (CHAR16)); - ASSERT (TmpString != NULL); + + if (TmpString == NULL) { + ASSERT (TmpString != NULL); + break; + } + StrnCpyS (TmpString, Length + 1, String, Length - 3); StrCatS (TmpString, Length + 1, L"..."); diff --git a/MdePkg/Library/UefiLib/UefiLibPrint.c b/MdePkg/Library/UefiLib/UefiLibPrint.c index 39edeb7283dd..c2c6cacd55d0 100644 --- a/MdePkg/Library/UefiLib/UefiLibPrint.c +++ b/MdePkg/Library/UefiLib/UefiLibPrint.c @@ -65,7 +65,11 @@ InternalPrint ( BufferSize = (PcdGet32 (PcdUefiLibMaxPrintBufferSize) + 1) * sizeof (CHAR16); Buffer = (CHAR16 *)AllocatePool (BufferSize); - ASSERT (Buffer != NULL); + + if (Buffer == NULL) { + ASSERT (Buffer != NULL); + return 0; + } Return = UnicodeVSPrint (Buffer, BufferSize, Format, Marker); @@ -199,7 +203,11 @@ AsciiInternalPrint ( BufferSize = (PcdGet32 (PcdUefiLibMaxPrintBufferSize) + 1) * sizeof (CHAR16); Buffer = (CHAR16 *)AllocatePool (BufferSize); - ASSERT (Buffer != NULL); + + if (Buffer == NULL) { + ASSERT (Buffer != NULL); + return 0; + } Return = UnicodeVSPrintAsciiFormat (Buffer, BufferSize, Format, Marker); @@ -419,7 +427,11 @@ InternalPrintGraphic ( } Blt = (EFI_IMAGE_OUTPUT *)AllocateZeroPool (sizeof (EFI_IMAGE_OUTPUT)); - ASSERT (Blt != NULL); + + if (Blt == NULL) { + ASSERT (Blt != NULL); + goto Error; + } Blt->Width = (UINT16)(HorizontalResolution); Blt->Height = (UINT16)(VerticalResolution); @@ -625,7 +637,11 @@ PrintXY ( BufferSize = (PcdGet32 (PcdUefiLibMaxPrintBufferSize) + 1) * sizeof (CHAR16); Buffer = (CHAR16 *)AllocatePool (BufferSize); - ASSERT (Buffer != NULL); + + if (Buffer == NULL) { + ASSERT (Buffer != NULL); + return 0; + } PrintNum = UnicodeVSPrint (Buffer, BufferSize, Format, Marker); @@ -703,7 +719,11 @@ AsciiPrintXY ( BufferSize = (PcdGet32 (PcdUefiLibMaxPrintBufferSize) + 1) * sizeof (CHAR16); Buffer = (CHAR16 *)AllocatePool (BufferSize); - ASSERT (Buffer != NULL); + + if (Buffer == NULL) { + ASSERT (Buffer != NULL); + return 0; + } PrintNum = UnicodeSPrintAsciiFormat (Buffer, BufferSize, Format, Marker); diff --git a/MdePkg/Library/UefiPciSegmentLibPciRootBridgeIo/PciSegmentLib.c b/MdePkg/Library/UefiPciSegmentLibPciRootBridgeIo/PciSegmentLib.c index c7988367cfab..6f4677bd27c7 100644 --- a/MdePkg/Library/UefiPciSegmentLibPciRootBridgeIo/PciSegmentLib.c +++ b/MdePkg/Library/UefiPciSegmentLibPciRootBridgeIo/PciSegmentLib.c @@ -184,7 +184,11 @@ DxePciSegmentLibPciRootBridgeIoReadWorker ( EFI_PCI_ROOT_BRIDGE_IO_PROTOCOL *PciRootBridgeIo; PciRootBridgeIo = PciSegmentLibSearchForRootBridge (Address); - ASSERT (PciRootBridgeIo != NULL); + + if (PciRootBridgeIo == NULL) { + ASSERT (PciRootBridgeIo != NULL); + return 0; + } PciRootBridgeIo->Pci.Read ( PciRootBridgeIo, @@ -223,7 +227,11 @@ DxePciSegmentLibPciRootBridgeIoWriteWorker ( EFI_PCI_ROOT_BRIDGE_IO_PROTOCOL *PciRootBridgeIo; PciRootBridgeIo = PciSegmentLibSearchForRootBridge (Address); - ASSERT (PciRootBridgeIo != NULL); + + if (PciRootBridgeIo == NULL) { + ASSERT (PciRootBridgeIo != NULL); + return 0; + } PciRootBridgeIo->Pci.Write ( PciRootBridgeIo, diff --git a/MdePkg/MdeLibs.dsc.inc b/MdePkg/MdeLibs.dsc.inc index 4e3858edb627..542b5f77f4a4 100644 --- a/MdePkg/MdeLibs.dsc.inc +++ b/MdePkg/MdeLibs.dsc.inc @@ -31,8 +31,15 @@ # NULL|MdePkg/Library/CompilerIntrinsicsLib/CompilerIntrinsicsLib.inf +# # Stack Cookies cannot be generically applied to SEC modules because they may not define _ModuleEntryPoint and when we # link a library in, we have to be able to define the entry point. SEC modules that do define _ModuleEntryPoint can -# apply a library class override to get StackCheckLibNull.inf +# apply a library class override to get StackCheckLibNull.inf. +# +# If CUSTOM_STACK_CHECK_LIB is set, MdeLibs.dsc.inc will not link StackCheckLibNull and it is expected that the +# DSC being built is providing it's own implementation of StackCheckLib. +# [LibraryClasses.common.PEI_CORE, LibraryClasses.common.PEIM, LibraryClasses.common.DXE_CORE, LibraryClasses.common.SMM_CORE, LibraryClasses.common.MM_CORE_STANDALONE, LibraryClasses.common.DXE_DRIVER, LibraryClasses.common.DXE_RUNTIME_DRIVER, LibraryClasses.common.DXE_SMM_DRIVER, LibraryClasses.common.MM_STANDALONE, LibraryClasses.common.UEFI_DRIVER, LibraryClasses.common.UEFI_APPLICATION] +!ifndef CUSTOM_STACK_CHECK_LIB NULL|MdePkg/Library/StackCheckLibNull/StackCheckLibNull.inf +!endif diff --git a/MdePkg/Test/MdePkgHostTest.dsc b/MdePkg/Test/MdePkgHostTest.dsc index 1351d191575e..0f9daa4bac37 100644 --- a/MdePkg/Test/MdePkgHostTest.dsc +++ b/MdePkg/Test/MdePkgHostTest.dsc @@ -47,5 +47,10 @@ MdePkg/Test/Mock/Library/GoogleTest/MockPeiServicesLib/MockPeiServicesLib.inf MdePkg/Test/Mock/Library/GoogleTest/MockHobLib/MockHobLib.inf MdePkg/Test/Mock/Library/GoogleTest/MockFdtLib/MockFdtLib.inf + MdePkg/Test/Mock/Library/GoogleTest/MockPostCodeLib/MockPostCodeLib.inf + MdePkg/Test/Mock/Library/GoogleTest/MockSmmServicesTableLib/MockSmmServicesTableLib.inf + MdePkg/Test/Mock/Library/GoogleTest/MockCpuLib/MockCpuLib.inf + MdePkg/Test/Mock/Library/GoogleTest/MockPciSegmentLib/MockPciSegmentLib.inf + MdePkg/Test/Mock/Library/GoogleTest/MockReportStatusCodeLib/MockReportStatusCodeLib.inf MdePkg/Library/StackCheckLibNull/StackCheckLibNullHostApplication.inf diff --git a/MdePkg/Test/Mock/Include/GoogleTest/Library/MockCpuLib.h b/MdePkg/Test/Mock/Include/GoogleTest/Library/MockCpuLib.h new file mode 100644 index 000000000000..658a1eb08cdc --- /dev/null +++ b/MdePkg/Test/Mock/Include/GoogleTest/Library/MockCpuLib.h @@ -0,0 +1,64 @@ +/** @file MockCpuLib.h + Google Test mocks for the CPU Library + + Copyright (c) Microsoft Corporation. + SPDX-License-Identifier: BSD-2-Clause-Patent +**/ + +#ifndef MOCK_CPU_LIB_H_ +#define MOCK_CPU_LIB_H_ + +#include +#include + +extern "C" { + #include +} + +struct MockCpuLib { + MOCK_INTERFACE_DECLARATION (MockCpuLib); + + MOCK_FUNCTION_DECLARATION ( + VOID, + CpuSleep, + ( + ) + ); + + MOCK_FUNCTION_DECLARATION ( + VOID, + CpuFlushTlb, + ( + ) + ); + + MOCK_FUNCTION_DECLARATION ( + VOID, + InitializeFloatingPointUnits, + ( + ) + ); + + MOCK_FUNCTION_DECLARATION ( + BOOLEAN, + StandardSignatureIsAuthenticAMD, + ( + ) + ); + + MOCK_FUNCTION_DECLARATION ( + UINT32, + GetCpuFamilyModel, + ( + ) + ); + + MOCK_FUNCTION_DECLARATION ( + UINT8, + GetCpuSteppingId, + ( + ) + ); +}; + +#endif diff --git a/MdePkg/Test/Mock/Include/GoogleTest/Library/MockFdtLib.h b/MdePkg/Test/Mock/Include/GoogleTest/Library/MockFdtLib.h index 5b21b232b7c7..9e9ddc21ddc2 100644 --- a/MdePkg/Test/Mock/Include/GoogleTest/Library/MockFdtLib.h +++ b/MdePkg/Test/Mock/Include/GoogleTest/Library/MockFdtLib.h @@ -89,7 +89,7 @@ struct MockFdtLib { ); MOCK_FUNCTION_DECLARATION ( INT32, - FdtNodeOffsetByPropValue, + FdtNodeOffsetByPropertyValue, (IN CONST VOID *Fdt, IN INT32 StartOffset, IN CONST CHAR8 *PropertyName, @@ -139,7 +139,7 @@ struct MockFdtLib { ); MOCK_FUNCTION_DECLARATION ( INT32, - FdtSetProp, + FdtSetProperty, (IN VOID *Fdt, IN INT32 NodeOffset, IN CONST CHAR8 *Name, diff --git a/MdePkg/Test/Mock/Include/GoogleTest/Library/MockPciSegmentLib.h b/MdePkg/Test/Mock/Include/GoogleTest/Library/MockPciSegmentLib.h new file mode 100644 index 000000000000..93d142627a3e --- /dev/null +++ b/MdePkg/Test/Mock/Include/GoogleTest/Library/MockPciSegmentLib.h @@ -0,0 +1,350 @@ +/** @file MockPciSegmentLib.h + Google Test mocks for PciSegmentLib + + Copyright (c) Microsoft Corporation. + SPDX-License-Identifier: BSD-2-Clause-Patent +**/ + +#ifndef MOCK_PCISEGMENTLIB_H_ +#define MOCK_PCISEGMENTLIB_H_ + +#include +#include + +extern "C" { + #include +} + +struct MockPciSegmentLib { + MOCK_INTERFACE_DECLARATION (MockPciSegmentLib); + + MOCK_FUNCTION_DECLARATION ( + RETURN_STATUS, + PciSegmentRegisterForRuntimeAccess, + ( + IN UINTN Address + ) + ); + + MOCK_FUNCTION_DECLARATION ( + UINT8, + PciSegmentRead8, + ( + IN UINT64 Address + ) + ); + + MOCK_FUNCTION_DECLARATION ( + UINT8, + PciSegmentWrite8, + ( + IN UINT64 Address, + IN UINT8 Value + ) + ); + + MOCK_FUNCTION_DECLARATION ( + UINT8, + PciSegmentOr8, + ( + IN UINT64 Address, + IN UINT8 OrData + ) + ); + + MOCK_FUNCTION_DECLARATION ( + UINT8, + PciSegmentAnd8, + ( + IN UINT64 Address, + IN UINT8 AndData + ) + ); + + MOCK_FUNCTION_DECLARATION ( + UINT8, + PciSegmentAndThenOr8, + ( + IN UINT64 Address, + IN UINT8 AndData, + IN UINT8 OrData + ) + ); + + MOCK_FUNCTION_DECLARATION ( + UINT8, + PciSegmentBitFieldRead8, + ( + IN UINT64 Address, + IN UINTN StartBit, + IN UINTN EndBit + ) + ); + + MOCK_FUNCTION_DECLARATION ( + UINT8, + PciSegmentBitFieldWrite8, + ( + IN UINT64 Address, + IN UINTN StartBit, + IN UINTN EndBit, + IN UINT8 Value + ) + ); + + MOCK_FUNCTION_DECLARATION ( + UINT8, + PciSegmentBitFieldOr8, + ( + IN UINT64 Address, + IN UINTN StartBit, + IN UINTN EndBit, + IN UINT8 OrData + ) + ); + + MOCK_FUNCTION_DECLARATION ( + UINT8, + PciSegmentBitFieldAnd8, + ( + IN UINT64 Address, + IN UINTN StartBit, + IN UINTN EndBit, + IN UINT8 AndData + ) + ); + + MOCK_FUNCTION_DECLARATION ( + UINT8, + PciSegmentBitFieldAndThenOr8, + ( + IN UINT64 Address, + IN UINTN StartBit, + IN UINTN EndBit, + IN UINT8 AndData, + IN UINT8 OrData + ) + ); + + MOCK_FUNCTION_DECLARATION ( + UINT16, + PciSegmentRead16, + ( + IN UINT64 Address + ) + ); + + MOCK_FUNCTION_DECLARATION ( + UINT16, + PciSegmentWrite16, + ( + IN UINT64 Address, + IN UINT16 Value + ) + ); + + MOCK_FUNCTION_DECLARATION ( + UINT16, + PciSegmentOr16, + ( + IN UINT64 Address, + IN UINT16 OrData + ) + ); + + MOCK_FUNCTION_DECLARATION ( + UINT16, + PciSegmentAnd16, + ( + IN UINT64 Address, + IN UINT16 AndData + ) + ); + + MOCK_FUNCTION_DECLARATION ( + UINT16, + PciSegmentAndThenOr16, + ( + IN UINT64 Address, + IN UINT16 AndData, + IN UINT16 OrData + ) + ); + + MOCK_FUNCTION_DECLARATION ( + UINT16, + PciSegmentBitFieldRead16, + ( + IN UINT64 Address, + IN UINTN StartBit, + IN UINTN EndBit + ) + ); + + MOCK_FUNCTION_DECLARATION ( + UINT16, + PciSegmentBitFieldWrite16, + ( + IN UINT64 Address, + IN UINTN StartBit, + IN UINTN EndBit, + IN UINT16 Value + ) + ); + + MOCK_FUNCTION_DECLARATION ( + UINT16, + PciSegmentBitFieldOr16, + ( + IN UINT64 Address, + IN UINTN StartBit, + IN UINTN EndBit, + IN UINT16 OrData + ) + ); + + MOCK_FUNCTION_DECLARATION ( + UINT16, + PciSegmentBitFieldAnd16, + ( + IN UINT64 Address, + IN UINTN StartBit, + IN UINTN EndBit, + IN UINT16 AndData + ) + ); + + MOCK_FUNCTION_DECLARATION ( + UINT16, + PciSegmentBitFieldAndThenOr16, + ( + IN UINT64 Address, + IN UINTN StartBit, + IN UINTN EndBit, + IN UINT16 AndData, + IN UINT16 OrData + ) + ); + + MOCK_FUNCTION_DECLARATION ( + UINT32, + PciSegmentRead32, + ( + IN UINT64 Address + ) + ); + + MOCK_FUNCTION_DECLARATION ( + UINT32, + PciSegmentWrite32, + ( + IN UINT64 Address, + IN UINT32 Value + ) + ); + + MOCK_FUNCTION_DECLARATION ( + UINT32, + PciSegmentOr32, + ( + IN UINT64 Address, + IN UINT32 OrData + ) + ); + + MOCK_FUNCTION_DECLARATION ( + UINT32, + PciSegmentAnd32, + ( + IN UINT64 Address, + IN UINT32 AndData + ) + ); + + MOCK_FUNCTION_DECLARATION ( + UINT32, + PciSegmentAndThenOr32, + ( + IN UINT64 Address, + IN UINT32 AndData, + IN UINT32 OrData + ) + ); + + MOCK_FUNCTION_DECLARATION ( + UINT32, + PciSegmentBitFieldRead32, + ( + IN UINT64 Address, + IN UINTN StartBit, + IN UINTN EndBit + ) + ); + + MOCK_FUNCTION_DECLARATION ( + UINT32, + PciSegmentBitFieldWrite32, + ( + IN UINT64 Address, + IN UINTN StartBit, + IN UINTN EndBit, + IN UINT32 Value + ) + ); + + MOCK_FUNCTION_DECLARATION ( + UINT32, + PciSegmentBitFieldOr32, + ( + IN UINT64 Address, + IN UINTN StartBit, + IN UINTN EndBit, + IN UINT32 OrData + ) + ); + + MOCK_FUNCTION_DECLARATION ( + UINT32, + PciSegmentBitFieldAnd32, + ( + IN UINT64 Address, + IN UINTN StartBit, + IN UINTN EndBit, + IN UINT32 AndData + ) + ); + + MOCK_FUNCTION_DECLARATION ( + UINT32, + PciSegmentBitFieldAndThenOr32, + ( + IN UINT64 Address, + IN UINTN StartBit, + IN UINTN EndBit, + IN UINT32 AndData, + IN UINT32 OrData + ) + ); + + MOCK_FUNCTION_DECLARATION ( + UINTN, + PciSegmentReadBuffer, + ( + IN UINT64 StartAddress, + IN UINTN Size, + OUT VOID *Buffer + ) + ); + + MOCK_FUNCTION_DECLARATION ( + UINTN, + PciSegmentWriteBuffer, + ( + IN UINT64 StartAddress, + IN UINTN Size, + IN VOID *Buffer + ) + ); +}; + +#endif diff --git a/MdePkg/Test/Mock/Include/GoogleTest/Library/MockPostCodeLib.h b/MdePkg/Test/Mock/Include/GoogleTest/Library/MockPostCodeLib.h new file mode 100644 index 000000000000..6ff36b576af4 --- /dev/null +++ b/MdePkg/Test/Mock/Include/GoogleTest/Library/MockPostCodeLib.h @@ -0,0 +1,56 @@ +/** @file MockPostCodeLib.h + Google Test mocks for PostCodeLib + + Copyright (c) 2006 - 2018, Intel Corporation. All rights reserved. + Copyright (c) Microsoft Corporation. + SPDX-License-Identifier: BSD-2-Clause-Patent +**/ + +#ifndef MOCK_POST_CODE_LIB_H_ +#define MOCK_POST_CODE_LIB_H_ + +#include +#include +extern "C" { + #include + #include +} + +struct MockPostCodeLib { + MOCK_INTERFACE_DECLARATION (MockPostCodeLib); + + MOCK_FUNCTION_DECLARATION ( + UINT32, + PostCode, + ( + IN UINT32 Value + ) + ); + + MOCK_FUNCTION_DECLARATION ( + UINT32, + PostCodeWithDescription, + ( + IN UINT32 Value, + IN CONST CHAR8 *Description OPTIONAL + ) + ); + + MOCK_FUNCTION_DECLARATION ( + BOOLEAN, + PostCodeEnabled, + ( + + ) + ); + + MOCK_FUNCTION_DECLARATION ( + BOOLEAN, + PostCodeDescriptionEnabled, + ( + + ) + ); +}; + +#endif //MOCK_PCI_EXPRESS_LIB_H_ diff --git a/MdePkg/Test/Mock/Include/GoogleTest/Library/MockReportStatusCodeLib.h b/MdePkg/Test/Mock/Include/GoogleTest/Library/MockReportStatusCodeLib.h new file mode 100644 index 000000000000..79dcb6dbe972 --- /dev/null +++ b/MdePkg/Test/Mock/Include/GoogleTest/Library/MockReportStatusCodeLib.h @@ -0,0 +1,29 @@ +/** @file MockReportStatusCodeLib.h + Google Test mocks for ReportStatusCodeLib + + Copyright (c) Microsoft Corporation. + SPDX-License-Identifier: BSD-2-Clause-Patent +**/ + +#ifndef MOCK_REPORT_STATUS_CODE_LIB_H_ +#define MOCK_REPORT_STATUS_CODE_LIB_H_ + +#include +#include + +extern "C" { + #include + #include +} + +struct MockReportStatusCodeLib { + MOCK_INTERFACE_DECLARATION (MockReportStatusCodeLib); + + MOCK_FUNCTION_DECLARATION ( + BOOLEAN, + ReportProgressCodeEnabled, + () + ); +}; + +#endif //MOCK_REPORT_STATUS_CODE_LIB_H_ diff --git a/MdePkg/Test/Mock/Include/GoogleTest/Library/MockSmmServicesTableLib.h b/MdePkg/Test/Mock/Include/GoogleTest/Library/MockSmmServicesTableLib.h new file mode 100644 index 000000000000..0a1cb238abeb --- /dev/null +++ b/MdePkg/Test/Mock/Include/GoogleTest/Library/MockSmmServicesTableLib.h @@ -0,0 +1,166 @@ +/** @file MockSmmServicesTableLib.h + Google Test mocks for SmmServicesTableLib + + Copyright (c) Microsoft Corporation. + SPDX-License-Identifier: BSD-2-Clause-Patent +**/ + +#ifndef MOCK_SMM_SERVICES_TABLE_LIB_H_ +#define MOCK_SMM_SERVICES_TABLE_LIB_H_ + +#include +#include +extern "C" { + #include + #include +} + +// +// Declarations to handle usage of the SmmServicesTableLib by creating mock +// +struct MockSmmServicesTableLib { + MOCK_INTERFACE_DECLARATION (MockSmmServicesTableLib); + + MOCK_FUNCTION_DECLARATION ( + EFI_STATUS, + gSmst_SmmAllocatePool, + ( + IN EFI_MEMORY_TYPE PoolType, + IN UINTN Size, + OUT VOID **Buffer + ) + ); + + MOCK_FUNCTION_DECLARATION ( + EFI_STATUS, + gSmst_SmmFreePool, + ( + IN VOID *Buffer + ) + ); + + MOCK_FUNCTION_DECLARATION ( + EFI_STATUS, + gSmst_SmmAllocatePages, + ( + IN EFI_ALLOCATE_TYPE Type, + IN EFI_MEMORY_TYPE MemoryType, + IN UINTN Pages, + OUT EFI_PHYSICAL_ADDRESS *Memory + ) + ); + + MOCK_FUNCTION_DECLARATION ( + EFI_STATUS, + gSmst_SmmFreePages, + ( + IN EFI_PHYSICAL_ADDRESS Memory, + IN UINTN Pages + ) + ); + + // MP service + MOCK_FUNCTION_DECLARATION ( + EFI_STATUS, + gSmst_SmmStartupThisAp, + ( + IN EFI_AP_PROCEDURE Procedure, + IN UINTN CpuNumber, + IN OUT VOID *ProcArguments OPTIONAL + ) + ); + + MOCK_FUNCTION_DECLARATION ( + EFI_STATUS, + gSmst_SmmInstallProtocolInterface, + ( + IN OUT EFI_HANDLE *Handle, + IN EFI_GUID *Protocol, + IN EFI_INTERFACE_TYPE InterfaceType, + IN VOID *Interface + ) + ); + + MOCK_FUNCTION_DECLARATION ( + EFI_STATUS, + gSmst_SmmUninstallProtocolInterface, + ( + IN EFI_HANDLE Handle, + IN EFI_GUID *Protocol, + IN VOID *Interface + ) + ); + + MOCK_FUNCTION_DECLARATION ( + EFI_STATUS, + gSmst_SmmHandleProtocol, + ( + IN EFI_HANDLE Handle, + IN EFI_GUID *Protocol, + OUT VOID **Interface + ) + ); + + MOCK_FUNCTION_DECLARATION ( + EFI_STATUS, + gSmst_SmmRegisterProtocolNotify, + ( + IN CONST EFI_GUID *Protocol, + IN EFI_MM_NOTIFY_FN Function, + OUT VOID **Registration + ) + ); + + MOCK_FUNCTION_DECLARATION ( + EFI_STATUS, + gSmst_SmmLocateHandle, + ( + IN EFI_LOCATE_SEARCH_TYPE SearchType, + IN EFI_GUID *Protocol, + IN VOID *SearchKey, + IN OUT UINTN *BufferSize, + OUT EFI_HANDLE *Buffer + ) + ); + + MOCK_FUNCTION_DECLARATION ( + EFI_STATUS, + gSmst_SmmLocateProtocol, + ( + IN EFI_GUID *Protocol, + IN VOID *Registration OPTIONAL, + OUT VOID **Interface + ) + ); + + MOCK_FUNCTION_DECLARATION ( + EFI_STATUS, + gSmst_SmiManage, + ( + IN CONST EFI_GUID *HandlerType, + IN CONST VOID *Context, + IN OUT VOID *CommBuffer, + IN OUT UINTN *CommBufferSize + ) + ); + + MOCK_FUNCTION_DECLARATION ( + EFI_STATUS, + gSmst_SmmInterruptRegister, + ( + IN EFI_SMM_HANDLER_ENTRY_POINT2 Handler, + IN CONST EFI_GUID *HandlerType, + OUT EFI_HANDLE *DispatchHandle + ) + ); + + MOCK_FUNCTION_DECLARATION ( + EFI_STATUS, + gSmst_SmmInterruptUnRegister, + ( + IN EFI_HANDLE DispatchHandle + ) + ); +}; + +#endif diff --git a/MdePkg/Test/Mock/Include/GoogleTest/Library/MockUefiLib.h b/MdePkg/Test/Mock/Include/GoogleTest/Library/MockUefiLib.h index 93697da9cf86..7dc5d602e6aa 100644 --- a/MdePkg/Test/Mock/Include/GoogleTest/Library/MockUefiLib.h +++ b/MdePkg/Test/Mock/Include/GoogleTest/Library/MockUefiLib.h @@ -2,6 +2,7 @@ Google Test mocks for UefiLib Copyright (c) 2022, Intel Corporation. All rights reserved. + Copyright (c) Microsoft Corporation. SPDX-License-Identifier: BSD-2-Clause-Patent **/ @@ -18,21 +19,354 @@ extern "C" { struct MockUefiLib { MOCK_INTERFACE_DECLARATION (MockUefiLib); + MOCK_FUNCTION_DECLARATION ( + EFI_STATUS, + EfiGetSystemConfigurationTable, + (IN EFI_GUID *TableGuid, + OUT VOID **Table) + ); + + MOCK_FUNCTION_DECLARATION ( + EFI_EVENT, + EfiCreateProtocolNotifyEvent, + (IN EFI_GUID *ProtocolGuid, + IN EFI_TPL NotifyTpl, + IN EFI_EVENT_NOTIFY NotifyFunction, + IN VOID *NotifyContext OPTIONAL, + OUT VOID **Registration) + ); + + MOCK_FUNCTION_DECLARATION ( + EFI_STATUS, + EfiNamedEventListen, + (IN CONST EFI_GUID *Name, + IN EFI_TPL NotifyTpl, + IN EFI_EVENT_NOTIFY NotifyFunction, + IN CONST VOID *NotifyContext OPTIONAL, + OUT VOID *Registration OPTIONAL) + ); + + MOCK_FUNCTION_DECLARATION ( + EFI_STATUS, + EfiNamedEventSignal, + (IN CONST EFI_GUID *Name) + ); + + MOCK_FUNCTION_DECLARATION ( + EFI_STATUS, + EfiEventGroupSignal, + (IN CONST EFI_GUID *EventGroup) + ); + + MOCK_FUNCTION_DECLARATION ( + VOID, + EfiEventEmptyFunction, + (IN EFI_EVENT Event, + IN VOID *Context) + ); + + MOCK_FUNCTION_DECLARATION ( + EFI_TPL, + EfiGetCurrentTpl, + () + ); + + MOCK_FUNCTION_DECLARATION ( + EFI_LOCK *, + EfiInitializeLock, + (IN OUT EFI_LOCK *Lock, + IN EFI_TPL Priority) + ); + + MOCK_FUNCTION_DECLARATION ( + VOID, + EfiAcquireLock, + (IN EFI_LOCK *Lock) + ); + + MOCK_FUNCTION_DECLARATION ( + EFI_STATUS, + EfiAcquireLockOrFail, + (IN EFI_LOCK *Lock) + ); + + MOCK_FUNCTION_DECLARATION ( + VOID, + EfiReleaseLock, + (IN EFI_LOCK *Lock) + ); + + MOCK_FUNCTION_DECLARATION ( + EFI_STATUS, + EfiTestManagedDevice, + (IN CONST EFI_HANDLE ControllerHandle, + IN CONST EFI_HANDLE DriverBindingHandle, + IN CONST EFI_GUID *ProtocolGuid) + ); + + MOCK_FUNCTION_DECLARATION ( + EFI_STATUS, + EfiTestChildHandle, + (IN CONST EFI_HANDLE ControllerHandle, + IN CONST EFI_HANDLE ChildHandle, + IN CONST EFI_GUID *ProtocolGuid) + ); + + MOCK_FUNCTION_DECLARATION ( + EFI_STATUS, + IsLanguageSupported, + (IN CONST CHAR8 *SupportedLanguages, + IN CONST CHAR8 *TargetLanguage) + ); + + MOCK_FUNCTION_DECLARATION ( + EFI_STATUS, + LookupUnicodeString, + (IN CONST CHAR8 *Language, + IN CONST CHAR8 *SupportedLanguages, + IN CONST EFI_UNICODE_STRING_TABLE *UnicodeStringTable, + OUT CHAR16 **UnicodeString) + ); + + MOCK_FUNCTION_DECLARATION ( + EFI_STATUS, + LookupUnicodeString2, + (IN CONST CHAR8 *Language, + IN CONST CHAR8 *SupportedLanguages, + IN CONST EFI_UNICODE_STRING_TABLE *UnicodeStringTable, + OUT CHAR16 **UnicodeString, + IN BOOLEAN Iso639Language) + ); + + MOCK_FUNCTION_DECLARATION ( + EFI_STATUS, + AddUnicodeString, + (IN CONST CHAR8 *Language, + IN CONST CHAR8 *SupportedLanguages, + IN OUT EFI_UNICODE_STRING_TABLE **UnicodeStringTable, + IN CONST CHAR16 *UnicodeString) + ); + + MOCK_FUNCTION_DECLARATION ( + EFI_STATUS, + AddUnicodeString2, + (IN CONST CHAR8 *Language, + IN CONST CHAR8 *SupportedLanguages, + IN OUT EFI_UNICODE_STRING_TABLE **UnicodeStringTable, + IN CONST CHAR16 *UnicodeString, + IN BOOLEAN Iso639Language) + ); + + MOCK_FUNCTION_DECLARATION ( + EFI_STATUS, + FreeUnicodeStringTable, + (IN EFI_UNICODE_STRING_TABLE *UnicodeStringTable) + ); + MOCK_FUNCTION_DECLARATION ( EFI_STATUS, GetVariable2, (IN CONST CHAR16 *Name, IN CONST EFI_GUID *Guid, - OUT VOID **Value, - OUT UINTN *Size OPTIONAL) + OUT VOID **Value, + OUT UINTN *Size OPTIONAL) ); MOCK_FUNCTION_DECLARATION ( EFI_STATUS, GetEfiGlobalVariable2, (IN CONST CHAR16 *Name, - OUT VOID **Value, - OUT UINTN *Size OPTIONAL) + OUT VOID **Value, + OUT UINTN *Size OPTIONAL) + ); + + MOCK_FUNCTION_DECLARATION ( + EFI_STATUS, + GetVariable3, + (IN CONST CHAR16 *Name, + IN CONST EFI_GUID *Guid, + OUT VOID **Value, + OUT UINTN *Size OPTIONAL, + OUT UINT32 *Attr OPTIONAL) + ); + + MOCK_FUNCTION_DECLARATION ( + UINTN, + GetGlyphWidth, + (IN CHAR16 UnicodeChar) + ); + + MOCK_FUNCTION_DECLARATION ( + UINTN, + UnicodeStringDisplayLength, + (IN CONST CHAR16 *String) + ); + + MOCK_FUNCTION_DECLARATION ( + VOID, + EfiSignalEventReadyToBoot, + () + ); + + MOCK_FUNCTION_DECLARATION ( + VOID, + EfiSignalEventLegacyBoot, + () + ); + + MOCK_FUNCTION_DECLARATION ( + EFI_STATUS, + EfiCreateEventLegacyBoot, + (OUT EFI_EVENT *LegacyBootEvent) + ); + + MOCK_FUNCTION_DECLARATION ( + EFI_STATUS, + EfiCreateEventLegacyBootEx, + (IN EFI_TPL NotifyTpl, + IN EFI_EVENT_NOTIFY NotifyFunction OPTIONAL, + IN VOID *NotifyContext OPTIONAL, + OUT EFI_EVENT *LegacyBootEvent) + ); + + MOCK_FUNCTION_DECLARATION ( + EFI_STATUS, + EfiCreateEventReadyToBoot, + (OUT EFI_EVENT *ReadyToBootEvent) + ); + + MOCK_FUNCTION_DECLARATION ( + EFI_STATUS, + EfiCreateEventReadyToBootEx, + (IN EFI_TPL NotifyTpl, + IN EFI_EVENT_NOTIFY NotifyFunction OPTIONAL, + IN VOID *NotifyContext OPTIONAL, + OUT EFI_EVENT *ReadyToBootEvent) + ); + + MOCK_FUNCTION_DECLARATION ( + VOID, + EfiInitializeFwVolDevicepathNode, + (IN OUT MEDIA_FW_VOL_FILEPATH_DEVICE_PATH *FvDevicePathNode, + IN CONST EFI_GUID *NameGuid) + ); + + MOCK_FUNCTION_DECLARATION ( + EFI_GUID *, + EfiGetNameGuidFromFwVolDevicePathNode, + (IN CONST MEDIA_FW_VOL_FILEPATH_DEVICE_PATH *FvDevicePathNode) + ); + + MOCK_FUNCTION_DECLARATION ( + EFI_STATUS, + EfiLibInstallDriverBinding, + (IN CONST EFI_HANDLE ImageHandle, + IN CONST EFI_SYSTEM_TABLE *SystemTable, + IN EFI_DRIVER_BINDING_PROTOCOL *DriverBinding, + IN EFI_HANDLE DriverBindingHandle) + ); + + MOCK_FUNCTION_DECLARATION ( + EFI_STATUS, + EfiLibUninstallDriverBinding, + (IN EFI_DRIVER_BINDING_PROTOCOL *DriverBinding) + ); + + MOCK_FUNCTION_DECLARATION ( + EFI_STATUS, + EfiLibInstallAllDriverProtocols, + (IN CONST EFI_HANDLE ImageHandle, + IN CONST EFI_SYSTEM_TABLE *SystemTable, + IN EFI_DRIVER_BINDING_PROTOCOL *DriverBinding, + IN EFI_HANDLE DriverBindingHandle, + IN CONST EFI_COMPONENT_NAME_PROTOCOL *ComponentName OPTIONAL, + IN CONST EFI_DRIVER_CONFIGURATION_PROTOCOL *DriverConfiguration OPTIONAL, + IN CONST EFI_DRIVER_DIAGNOSTICS_PROTOCOL *DriverDiagnostics OPTIONAL) + ); + + MOCK_FUNCTION_DECLARATION ( + EFI_STATUS, + EfiLibUninstallAllDriverProtocols, + (IN EFI_DRIVER_BINDING_PROTOCOL *DriverBinding, + IN CONST EFI_COMPONENT_NAME_PROTOCOL *ComponentName OPTIONAL, + IN CONST EFI_DRIVER_CONFIGURATION_PROTOCOL *DriverConfiguration OPTIONAL, + IN CONST EFI_DRIVER_DIAGNOSTICS_PROTOCOL *DriverDiagnostics OPTIONAL) + ); + + MOCK_FUNCTION_DECLARATION ( + EFI_STATUS, + EfiLibInstallDriverBindingComponentName2, + (IN CONST EFI_HANDLE ImageHandle, + IN CONST EFI_SYSTEM_TABLE *SystemTable, + IN EFI_DRIVER_BINDING_PROTOCOL *DriverBinding, + IN EFI_HANDLE DriverBindingHandle, + IN CONST EFI_COMPONENT_NAME_PROTOCOL *ComponentName OPTIONAL, + IN CONST EFI_COMPONENT_NAME2_PROTOCOL *ComponentName2 OPTIONAL) + ); + + MOCK_FUNCTION_DECLARATION ( + EFI_STATUS, + EfiLibUninstallDriverBindingComponentName2, + (IN EFI_DRIVER_BINDING_PROTOCOL *DriverBinding, + IN CONST EFI_COMPONENT_NAME_PROTOCOL *ComponentName OPTIONAL, + IN CONST EFI_COMPONENT_NAME2_PROTOCOL *ComponentName2 OPTIONAL) + ); + + MOCK_FUNCTION_DECLARATION ( + EFI_STATUS, + EfiLibInstallAllDriverProtocols2, + (IN CONST EFI_HANDLE ImageHandle, + IN CONST EFI_SYSTEM_TABLE *SystemTable, + IN EFI_DRIVER_BINDING_PROTOCOL *DriverBinding, + IN EFI_HANDLE DriverBindingHandle, + IN CONST EFI_COMPONENT_NAME_PROTOCOL *ComponentName OPTIONAL, + IN CONST EFI_COMPONENT_NAME2_PROTOCOL *ComponentName2 OPTIONAL, + IN CONST EFI_DRIVER_CONFIGURATION_PROTOCOL *DriverConfiguration OPTIONAL, + IN CONST EFI_DRIVER_CONFIGURATION2_PROTOCOL *DriverConfiguration2 OPTIONAL, + IN CONST EFI_DRIVER_DIAGNOSTICS_PROTOCOL *DriverDiagnostics OPTIONAL, + IN CONST EFI_DRIVER_DIAGNOSTICS2_PROTOCOL *DriverDiagnostics2 OPTIONAL) + ); + + MOCK_FUNCTION_DECLARATION ( + EFI_STATUS, + EfiLibUninstallAllDriverProtocols2, + (IN EFI_DRIVER_BINDING_PROTOCOL *DriverBinding, + IN CONST EFI_COMPONENT_NAME_PROTOCOL *ComponentName OPTIONAL, + IN CONST EFI_COMPONENT_NAME2_PROTOCOL *ComponentName2 OPTIONAL, + IN CONST EFI_DRIVER_CONFIGURATION_PROTOCOL *DriverConfiguration OPTIONAL, + IN CONST EFI_DRIVER_CONFIGURATION2_PROTOCOL *DriverConfiguration2 OPTIONAL, + IN CONST EFI_DRIVER_DIAGNOSTICS_PROTOCOL *DriverDiagnostics OPTIONAL, + IN CONST EFI_DRIVER_DIAGNOSTICS2_PROTOCOL *DriverDiagnostics2 OPTIONAL) + ); + + MOCK_FUNCTION_DECLARATION ( + EFI_STATUS, + EfiLocateProtocolBuffer, + (IN EFI_GUID *Protocol, + OUT UINTN *NoProtocols, + OUT VOID ***Buffer) + ); + + MOCK_FUNCTION_DECLARATION ( + EFI_STATUS, + EfiOpenFileByDevicePath, + (IN OUT EFI_DEVICE_PATH_PROTOCOL **FilePath, + OUT EFI_FILE_PROTOCOL **File, + IN UINT64 OpenMode, + IN UINT64 Attributes) + ); + + MOCK_FUNCTION_DECLARATION ( + EFI_ACPI_COMMON_HEADER *, + EfiLocateNextAcpiTable, + (IN UINT32 Signature, + IN EFI_ACPI_COMMON_HEADER *PreviousTable OPTIONAL) + ); + + MOCK_FUNCTION_DECLARATION ( + EFI_ACPI_COMMON_HEADER *, + EfiLocateFirstAcpiTable, + (IN UINT32 Signature) ); }; diff --git a/MdePkg/Test/Mock/Include/GoogleTest/Protocol/MockMpService.h b/MdePkg/Test/Mock/Include/GoogleTest/Protocol/MockMpService.h new file mode 100644 index 000000000000..94262e246d84 --- /dev/null +++ b/MdePkg/Test/Mock/Include/GoogleTest/Protocol/MockMpService.h @@ -0,0 +1,124 @@ +/** @file MockMpService.h + This file declares a mock of MP service Protocol. + + Copyright (c) Microsoft Corporation. + SPDX-License-Identifier: BSD-2-Clause-Patent +**/ + +#ifndef MOCK_MP_SERVICE_H_ +#define MOCK_MP_SERVICE_H_ + +#include +#include + +extern "C" { + #include + #include +} + +struct MockMpService { + MOCK_INTERFACE_DECLARATION (MockMpService); + + MOCK_FUNCTION_DECLARATION ( + EFI_STATUS, + GetNumberOfProcessors, + ( + IN EFI_MP_SERVICES_PROTOCOL *This, + OUT UINTN *NumberOfProcessors, + OUT UINTN *NumberOfEnabledProcessors + ) + ); + + MOCK_FUNCTION_DECLARATION ( + EFI_STATUS, + GetProcessorInfo, + ( + IN EFI_MP_SERVICES_PROTOCOL *This, + IN UINTN ProcessorNumber, + OUT EFI_PROCESSOR_INFORMATION *ProcessorInfoBuffer + ) + ); + + MOCK_FUNCTION_DECLARATION ( + EFI_STATUS, + StartupAllAPs, + ( + IN EFI_MP_SERVICES_PROTOCOL *This, + IN EFI_AP_PROCEDURE Procedure, + IN BOOLEAN SingleThread, + IN EFI_EVENT WaitEvent OPTIONAL, + IN UINTN TimeoutInMicroSeconds, + IN VOID *ProcedureArgument OPTIONAL, + OUT UINTN **FailedCpuList OPTIONAL + ) + ); + + MOCK_FUNCTION_DECLARATION ( + EFI_STATUS, + StartupThisAP, + ( + IN EFI_MP_SERVICES_PROTOCOL *This, + IN EFI_AP_PROCEDURE Procedure, + IN UINTN ProcessorNumber, + IN EFI_EVENT WaitEvent OPTIONAL, + IN UINTN TimeoutInMicroseconds, + IN VOID *ProcedureArgument OPTIONAL, + OUT BOOLEAN *Finished OPTIONAL + ) + ); + + MOCK_FUNCTION_DECLARATION ( + EFI_STATUS, + SwitchBSP, + ( + IN EFI_MP_SERVICES_PROTOCOL *This, + IN UINTN ProcessorNumber, + IN BOOLEAN EnableOldBSP + ) + ); + + MOCK_FUNCTION_DECLARATION ( + EFI_STATUS, + EnableDisableAP, + ( + IN EFI_MP_SERVICES_PROTOCOL *This, + IN UINTN ProcessorNumber, + IN BOOLEAN EnableAP, + IN UINT32 *HealthFlag OPTIONAL + ) + ); + + MOCK_FUNCTION_DECLARATION ( + EFI_STATUS, + WhoAmI, + ( + IN EFI_MP_SERVICES_PROTOCOL *This, + OUT UINTN *ProcessorNumber + ) + ); +}; + +MOCK_INTERFACE_DEFINITION (MockMpService); +MOCK_FUNCTION_DEFINITION (MockMpService, GetNumberOfProcessors, 3, EFIAPI); +MOCK_FUNCTION_DEFINITION (MockMpService, GetProcessorInfo, 3, EFIAPI); +MOCK_FUNCTION_DEFINITION (MockMpService, StartupAllAPs, 7, EFIAPI); +MOCK_FUNCTION_DEFINITION (MockMpService, StartupThisAP, 7, EFIAPI); +MOCK_FUNCTION_DEFINITION (MockMpService, SwitchBSP, 3, EFIAPI); +MOCK_FUNCTION_DEFINITION (MockMpService, EnableDisableAP, 4, EFIAPI); +MOCK_FUNCTION_DEFINITION (MockMpService, WhoAmI, 2, EFIAPI); + +static EFI_MP_SERVICES_PROTOCOL MP_SERVICE_PROTOCOL_INSTANCE = { + GetNumberOfProcessors, + GetProcessorInfo, + StartupAllAPs, + StartupThisAP, + SwitchBSP, + EnableDisableAP, + WhoAmI +}; + +extern "C" { + EFI_MP_SERVICES_PROTOCOL *gMpServiceProtocol = &MP_SERVICE_PROTOCOL_INSTANCE; +} + +#endif // MOCK_MP_SERVICE_H_ diff --git a/MdePkg/Test/Mock/Library/GoogleTest/MockCpuLib/MockCpuLib.cpp b/MdePkg/Test/Mock/Library/GoogleTest/MockCpuLib/MockCpuLib.cpp new file mode 100644 index 000000000000..cf379f1214d4 --- /dev/null +++ b/MdePkg/Test/Mock/Library/GoogleTest/MockCpuLib/MockCpuLib.cpp @@ -0,0 +1,17 @@ +/** @file MockCpuLib.cpp + Google Test mocks for BaseLib + + Copyright (c) Microsoft Corporation. + SPDX-License-Identifier: BSD-2-Clause-Patent +**/ + +#include + +MOCK_INTERFACE_DEFINITION (MockCpuLib); + +MOCK_FUNCTION_DEFINITION (MockCpuLib, CpuSleep, 0, EFIAPI); +MOCK_FUNCTION_DEFINITION (MockCpuLib, CpuFlushTlb, 0, EFIAPI); +MOCK_FUNCTION_DEFINITION (MockCpuLib, InitializeFloatingPointUnits, 0, EFIAPI); +MOCK_FUNCTION_DEFINITION (MockCpuLib, StandardSignatureIsAuthenticAMD, 0, EFIAPI); +MOCK_FUNCTION_DEFINITION (MockCpuLib, GetCpuFamilyModel, 0, EFIAPI); +MOCK_FUNCTION_DEFINITION (MockCpuLib, GetCpuSteppingId, 0, EFIAPI); diff --git a/MdePkg/Test/Mock/Library/GoogleTest/MockCpuLib/MockCpuLib.inf b/MdePkg/Test/Mock/Library/GoogleTest/MockCpuLib/MockCpuLib.inf new file mode 100644 index 000000000000..cdebd2ea8e21 --- /dev/null +++ b/MdePkg/Test/Mock/Library/GoogleTest/MockCpuLib/MockCpuLib.inf @@ -0,0 +1,33 @@ +## @file MockCpuLib.inf +# Mock implementation of the CPU library +# +# Copyright (c) Microsoft Corporation. +# SPDX-License-Identifier: BSD-2-Clause-Patent +# +## + +[Defines] + INF_VERSION = 0x00010005 + BASE_NAME = MockCpuLib + FILE_GUID = 8544B3FE-D1A8-4037-A8A9-43DC8D07077C + MODULE_TYPE = HOST_APPLICATION + VERSION_STRING = 1.0 + LIBRARY_CLASS = CpuLib + PI_SPECIFICATION_VERSION = 0x0001000A + +# +# VALID_ARCHITECTURES = IA32 X64 +# + +[Sources] + MockCpuLib.cpp + +[Packages] + MdePkg/MdePkg.dec + UnitTestFrameworkPkg/UnitTestFrameworkPkg.dec + +[LibraryClasses] + GoogleTestLib + +[BuildOptions] + MSFT:*_*_*_CC_FLAGS = /EHsc diff --git a/MdePkg/Test/Mock/Library/GoogleTest/MockFdtLib/MockFdtLib.cpp b/MdePkg/Test/Mock/Library/GoogleTest/MockFdtLib/MockFdtLib.cpp index a955780d23fe..8be96704b59a 100644 --- a/MdePkg/Test/Mock/Library/GoogleTest/MockFdtLib/MockFdtLib.cpp +++ b/MdePkg/Test/Mock/Library/GoogleTest/MockFdtLib/MockFdtLib.cpp @@ -22,13 +22,13 @@ MOCK_FUNCTION_DEFINITION (MockFdtLib, FdtNextNode, 3, EFIAPI); MOCK_FUNCTION_DEFINITION (MockFdtLib, FdtFirstSubnode, 2, EFIAPI); MOCK_FUNCTION_DEFINITION (MockFdtLib, FdtNextSubnode, 2, EFIAPI); MOCK_FUNCTION_DEFINITION (MockFdtLib, FdtSubnodeOffsetNameLen, 4, EFIAPI); -MOCK_FUNCTION_DEFINITION (MockFdtLib, FdtNodeOffsetByPropValue, 5, EFIAPI); +MOCK_FUNCTION_DEFINITION (MockFdtLib, FdtNodeOffsetByPropertyValue, 5, EFIAPI); MOCK_FUNCTION_DEFINITION (MockFdtLib, FdtGetProperty, 4, EFIAPI); MOCK_FUNCTION_DEFINITION (MockFdtLib, FdtFirstPropertyOffset, 2, EFIAPI); MOCK_FUNCTION_DEFINITION (MockFdtLib, FdtNextPropertyOffset, 2, EFIAPI); MOCK_FUNCTION_DEFINITION (MockFdtLib, FdtGetPropertyByOffset, 3, EFIAPI); MOCK_FUNCTION_DEFINITION (MockFdtLib, FdtGetString, 3, EFIAPI); MOCK_FUNCTION_DEFINITION (MockFdtLib, FdtAddSubnode, 3, EFIAPI); -MOCK_FUNCTION_DEFINITION (MockFdtLib, FdtSetProp, 5, EFIAPI); +MOCK_FUNCTION_DEFINITION (MockFdtLib, FdtSetProperty, 5, EFIAPI); MOCK_FUNCTION_DEFINITION (MockFdtLib, FdtGetName, 3, EFIAPI); MOCK_FUNCTION_DEFINITION (MockFdtLib, FdtNodeDepth, 2, EFIAPI); diff --git a/MdePkg/Test/Mock/Library/GoogleTest/MockPciSegmentLib/MockPciSegmentLib.cpp b/MdePkg/Test/Mock/Library/GoogleTest/MockPciSegmentLib/MockPciSegmentLib.cpp new file mode 100644 index 000000000000..2f6426679d20 --- /dev/null +++ b/MdePkg/Test/Mock/Library/GoogleTest/MockPciSegmentLib/MockPciSegmentLib.cpp @@ -0,0 +1,43 @@ +/** @file MockPciSegmentLib.cpp + Google Test mocks for PciSegmentLib + + Copyright (c) Microsoft Corporation. + SPDX-License-Identifier: BSD-2-Clause-Patent +**/ + +#include + +MOCK_INTERFACE_DEFINITION (MockPciSegmentLib); +MOCK_FUNCTION_DEFINITION (MockPciSegmentLib, PciSegmentRegisterForRuntimeAccess, 1, EFIAPI); +MOCK_FUNCTION_DEFINITION (MockPciSegmentLib, PciSegmentRead8, 1, EFIAPI); +MOCK_FUNCTION_DEFINITION (MockPciSegmentLib, PciSegmentWrite8, 2, EFIAPI); +MOCK_FUNCTION_DEFINITION (MockPciSegmentLib, PciSegmentOr8, 2, EFIAPI); +MOCK_FUNCTION_DEFINITION (MockPciSegmentLib, PciSegmentAnd8, 2, EFIAPI); +MOCK_FUNCTION_DEFINITION (MockPciSegmentLib, PciSegmentAndThenOr8, 3, EFIAPI); +MOCK_FUNCTION_DEFINITION (MockPciSegmentLib, PciSegmentBitFieldRead8, 3, EFIAPI); +MOCK_FUNCTION_DEFINITION (MockPciSegmentLib, PciSegmentBitFieldWrite8, 4, EFIAPI); +MOCK_FUNCTION_DEFINITION (MockPciSegmentLib, PciSegmentBitFieldOr8, 4, EFIAPI); +MOCK_FUNCTION_DEFINITION (MockPciSegmentLib, PciSegmentBitFieldAnd8, 4, EFIAPI); +MOCK_FUNCTION_DEFINITION (MockPciSegmentLib, PciSegmentBitFieldAndThenOr8, 5, EFIAPI); +MOCK_FUNCTION_DEFINITION (MockPciSegmentLib, PciSegmentRead16, 1, EFIAPI); +MOCK_FUNCTION_DEFINITION (MockPciSegmentLib, PciSegmentWrite16, 2, EFIAPI); +MOCK_FUNCTION_DEFINITION (MockPciSegmentLib, PciSegmentOr16, 2, EFIAPI); +MOCK_FUNCTION_DEFINITION (MockPciSegmentLib, PciSegmentAnd16, 2, EFIAPI); +MOCK_FUNCTION_DEFINITION (MockPciSegmentLib, PciSegmentAndThenOr16, 3, EFIAPI); +MOCK_FUNCTION_DEFINITION (MockPciSegmentLib, PciSegmentBitFieldRead16, 3, EFIAPI); +MOCK_FUNCTION_DEFINITION (MockPciSegmentLib, PciSegmentBitFieldWrite16, 4, EFIAPI); +MOCK_FUNCTION_DEFINITION (MockPciSegmentLib, PciSegmentBitFieldOr16, 4, EFIAPI); +MOCK_FUNCTION_DEFINITION (MockPciSegmentLib, PciSegmentBitFieldAnd16, 4, EFIAPI); +MOCK_FUNCTION_DEFINITION (MockPciSegmentLib, PciSegmentBitFieldAndThenOr16, 5, EFIAPI); +MOCK_FUNCTION_DEFINITION (MockPciSegmentLib, PciSegmentRead32, 1, EFIAPI); +MOCK_FUNCTION_DEFINITION (MockPciSegmentLib, PciSegmentWrite32, 2, EFIAPI); +MOCK_FUNCTION_DEFINITION (MockPciSegmentLib, PciSegmentOr32, 2, EFIAPI); +MOCK_FUNCTION_DEFINITION (MockPciSegmentLib, PciSegmentAnd32, 2, EFIAPI); +MOCK_FUNCTION_DEFINITION (MockPciSegmentLib, PciSegmentAndThenOr32, 3, EFIAPI); +MOCK_FUNCTION_DEFINITION (MockPciSegmentLib, PciSegmentBitFieldRead32, 3, EFIAPI); +MOCK_FUNCTION_DEFINITION (MockPciSegmentLib, PciSegmentBitFieldWrite32, 4, EFIAPI); +MOCK_FUNCTION_DEFINITION (MockPciSegmentLib, PciSegmentBitFieldOr32, 4, EFIAPI); +MOCK_FUNCTION_DEFINITION (MockPciSegmentLib, PciSegmentBitFieldAnd32, 4, EFIAPI); +MOCK_FUNCTION_DEFINITION (MockPciSegmentLib, PciSegmentBitFieldAndThenOr32, 5, EFIAPI); +MOCK_FUNCTION_DEFINITION (MockPciSegmentLib, PciSegmentReadBuffer, 3, EFIAPI); +MOCK_FUNCTION_DEFINITION (MockPciSegmentLib, PciSegmentWriteBuffer, 3, EFIAPI); diff --git a/MdePkg/Test/Mock/Library/GoogleTest/MockPciSegmentLib/MockPciSegmentLib.inf b/MdePkg/Test/Mock/Library/GoogleTest/MockPciSegmentLib/MockPciSegmentLib.inf new file mode 100644 index 000000000000..6e708c689ab2 --- /dev/null +++ b/MdePkg/Test/Mock/Library/GoogleTest/MockPciSegmentLib/MockPciSegmentLib.inf @@ -0,0 +1,33 @@ +## @file MockPciSegmentLib.inf +# Mock implementation of the PCI Segment Library +# +# Copyright (c) Microsoft Corporation. +# SPDX-License-Identifier: BSD-2-Clause-Patent +# +## + +[Defines] + INF_VERSION = 0x00010005 + BASE_NAME = MockPciSegmentLib + FILE_GUID = 0C5E46F6-82DF-45DF-9750-E231110681D1 + MODULE_TYPE = HOST_APPLICATION + VERSION_STRING = 1.0 + LIBRARY_CLASS = PciSegmentLib + PI_SPECIFICATION_VERSION = 0x0001000A + +# +# VALID_ARCHITECTURES = IA32 X64 +# + +[Sources] + MockPciSegmentLib.cpp + +[Packages] + MdePkg/MdePkg.dec + UnitTestFrameworkPkg/UnitTestFrameworkPkg.dec + +[LibraryClasses] + GoogleTestLib + +[BuildOptions] + MSFT:*_*_*_CC_FLAGS = /EHsc diff --git a/MdePkg/Test/Mock/Library/GoogleTest/MockPostCodeLib/MockPostCodeLib.cpp b/MdePkg/Test/Mock/Library/GoogleTest/MockPostCodeLib/MockPostCodeLib.cpp new file mode 100644 index 000000000000..b10009a3deef --- /dev/null +++ b/MdePkg/Test/Mock/Library/GoogleTest/MockPostCodeLib/MockPostCodeLib.cpp @@ -0,0 +1,14 @@ +/** @file MockPostCodeLib.cpp + Google Test mocks for PostCodeLib + + Copyright (c) Microsoft Corporation. + SPDX-License-Identifier: BSD-2-Clause-Patent +**/ + +#include + +MOCK_INTERFACE_DEFINITION (MockPostCodeLib); +MOCK_FUNCTION_DEFINITION (MockPostCodeLib, PostCode, 1, EFIAPI); +MOCK_FUNCTION_DEFINITION (MockPostCodeLib, PostCodeWithDescription, 2, EFIAPI); +MOCK_FUNCTION_DEFINITION (MockPostCodeLib, PostCodeEnabled, 0, EFIAPI); +MOCK_FUNCTION_DEFINITION (MockPostCodeLib, PostCodeDescriptionEnabled, 0, EFIAPI); diff --git a/MdePkg/Test/Mock/Library/GoogleTest/MockPostCodeLib/MockPostCodeLib.inf b/MdePkg/Test/Mock/Library/GoogleTest/MockPostCodeLib/MockPostCodeLib.inf new file mode 100644 index 000000000000..236dfe302289 --- /dev/null +++ b/MdePkg/Test/Mock/Library/GoogleTest/MockPostCodeLib/MockPostCodeLib.inf @@ -0,0 +1,33 @@ +## @file MockPostCodeLib.inf +# Google Test mocks for PostCodeLib +# +# Copyright (c) Microsoft Corporation. +# SPDX-License-Identifier: BSD-2-Clause-Patent +## + +[Defines] + INF_VERSION = 0x00010005 + BASE_NAME = MockPostCodeLib + FILE_GUID = 25BF192B-A519-4997-823A-AFEC2C953627 + MODULE_TYPE = HOST_APPLICATION + VERSION_STRING = 1.0 + LIBRARY_CLASS = PostCodeLib + +# +# The following information is for reference only and not required by the build tools. +# +# VALID_ARCHITECTURES = IA32 X64 +# + +[Sources] + MockPostCodeLib.cpp + +[Packages] + MdePkg/MdePkg.dec + UnitTestFrameworkPkg/UnitTestFrameworkPkg.dec + +[LibraryClasses] + GoogleTestLib + +[BuildOptions] + MSFT:*_*_*_CC_FLAGS = /EHsc diff --git a/MdePkg/Test/Mock/Library/GoogleTest/MockReportStatusCodeLib/MockReportStatusCodeLib.cpp b/MdePkg/Test/Mock/Library/GoogleTest/MockReportStatusCodeLib/MockReportStatusCodeLib.cpp new file mode 100644 index 000000000000..0900cbc180dc --- /dev/null +++ b/MdePkg/Test/Mock/Library/GoogleTest/MockReportStatusCodeLib/MockReportStatusCodeLib.cpp @@ -0,0 +1,11 @@ +/** @file MockReportStatusCodeLib.cpp + Google Test mocks for ReportStatusCodeLib + + Copyright (c) Microsoft Corporation. + SPDX-License-Identifier: BSD-2-Clause-Patent +**/ + +#include + +MOCK_INTERFACE_DEFINITION (MockReportStatusCodeLib); +MOCK_FUNCTION_DEFINITION (MockReportStatusCodeLib, ReportProgressCodeEnabled, 0, EFIAPI); diff --git a/MdePkg/Test/Mock/Library/GoogleTest/MockReportStatusCodeLib/MockReportStatusCodeLib.inf b/MdePkg/Test/Mock/Library/GoogleTest/MockReportStatusCodeLib/MockReportStatusCodeLib.inf new file mode 100644 index 000000000000..683938b488a6 --- /dev/null +++ b/MdePkg/Test/Mock/Library/GoogleTest/MockReportStatusCodeLib/MockReportStatusCodeLib.inf @@ -0,0 +1,33 @@ +## @file MockReportStatusCodeLib.inf +# Google Test mocks for ReportStatusCodeLib +# +# Copyright (c) Microsoft Corporation. +# SPDX-License-Identifier: BSD-2-Clause-Patent +## + +[Defines] + INF_VERSION = 0x00010005 + BASE_NAME = MockReportStatusCodeLib + FILE_GUID = 3DFF7308-AC32-4BE9-9D01-B6F25E9161C3 + MODULE_TYPE = HOST_APPLICATION + VERSION_STRING = 1.0 + LIBRARY_CLASS = ReportStatusCodeLib + +# +# The following information is for reference only and not required by the build tools. +# +# VALID_ARCHITECTURES = IA32 X64 +# + +[Sources] + MockReportStatusCodeLib.cpp + +[Packages] + MdePkg/MdePkg.dec + UnitTestFrameworkPkg/UnitTestFrameworkPkg.dec + +[LibraryClasses] + GoogleTestLib + +[BuildOptions] + MSFT:*_*_*_CC_FLAGS = /EHsc diff --git a/MdePkg/Test/Mock/Library/GoogleTest/MockSmmServicesTableLib/MockSmmServicesTableLib.cpp b/MdePkg/Test/Mock/Library/GoogleTest/MockSmmServicesTableLib/MockSmmServicesTableLib.cpp new file mode 100644 index 000000000000..91bf42f8db3c --- /dev/null +++ b/MdePkg/Test/Mock/Library/GoogleTest/MockSmmServicesTableLib/MockSmmServicesTableLib.cpp @@ -0,0 +1,56 @@ +/** @file MockSmmServicesTableLib.cpp + Google Test mocks for SmmServicesTableLib + + Copyright (c) Microsoft Corporation. + SPDX-License-Identifier: BSD-2-Clause-Patent +**/ +#include + +MOCK_INTERFACE_DEFINITION (MockSmmServicesTableLib); + +MOCK_FUNCTION_DEFINITION (MockSmmServicesTableLib, gSmst_SmmAllocatePool, 3, EFIAPI); +MOCK_FUNCTION_DEFINITION (MockSmmServicesTableLib, gSmst_SmmFreePool, 1, EFIAPI); +MOCK_FUNCTION_DEFINITION (MockSmmServicesTableLib, gSmst_SmmAllocatePages, 4, EFIAPI); +MOCK_FUNCTION_DEFINITION (MockSmmServicesTableLib, gSmst_SmmFreePages, 2, EFIAPI); +MOCK_FUNCTION_DEFINITION (MockSmmServicesTableLib, gSmst_SmmStartupThisAp, 3, EFIAPI); +MOCK_FUNCTION_DEFINITION (MockSmmServicesTableLib, gSmst_SmmInstallProtocolInterface, 4, EFIAPI); +MOCK_FUNCTION_DEFINITION (MockSmmServicesTableLib, gSmst_SmmUninstallProtocolInterface, 3, EFIAPI); +MOCK_FUNCTION_DEFINITION (MockSmmServicesTableLib, gSmst_SmmHandleProtocol, 3, EFIAPI); +MOCK_FUNCTION_DEFINITION (MockSmmServicesTableLib, gSmst_SmmRegisterProtocolNotify, 3, EFIAPI); +MOCK_FUNCTION_DEFINITION (MockSmmServicesTableLib, gSmst_SmmLocateHandle, 5, EFIAPI); +MOCK_FUNCTION_DEFINITION (MockSmmServicesTableLib, gSmst_SmmLocateProtocol, 3, EFIAPI); +MOCK_FUNCTION_DEFINITION (MockSmmServicesTableLib, gSmst_SmiManage, 4, EFIAPI); +MOCK_FUNCTION_DEFINITION (MockSmmServicesTableLib, gSmst_SmmInterruptRegister, 3, EFIAPI); +MOCK_FUNCTION_DEFINITION (MockSmmServicesTableLib, gSmst_SmmInterruptUnRegister, 1, EFIAPI); + +static EFI_SMM_SYSTEM_TABLE2 LocalSmst = { + { 0, 0, 0, 0, 0 }, // EFI_TABLE_HEADER + NULL, // SmmFirmwareVendor + 0, // SmmFirmwareRevision + NULL, // EFI_SMM_INSTALL_CONFIGURATION_TABLE2 + { NULL }, // EFI_SMM_CPU_IO2_PROTOCOL + gSmst_SmmAllocatePool, // EFI_ALLOCATE_POOL + gSmst_SmmFreePool, // EFI_FREE_POOL + gSmst_SmmAllocatePages, // EFI_ALLOCATE_PAGES + gSmst_SmmFreePages, // EFI_FREE_PAGES + gSmst_SmmStartupThisAp, // EFI_SMM_STARTUP_THIS_AP + 0, // CurrentlyExecutingCpu + 0, // NumberOfCpus + NULL, // CpuSaveStateSize + NULL, // CpuSaveState + 0, // NumberOfTableEntries + NULL, // EFI_CONFIGURATION_TABLE + gSmst_SmmInstallProtocolInterface, // EFI_INSTALL_PROTOCOL_INTERFACE + gSmst_SmmUninstallProtocolInterface, // EFI_UNINSTALL_PROTOCOL_INTERFACE + gSmst_SmmHandleProtocol, // EFI_HANDLE_PROTOCOL + gSmst_SmmRegisterProtocolNotify, // EFI_SMM_REGISTER_PROTOCOL_NOTIFY + gSmst_SmmLocateHandle, // EFI_LOCATE_HANDLE + gSmst_SmmLocateProtocol, // EFI_LOCATE_PROTOCOL + gSmst_SmiManage, // EFI_SMM_INTERRUPT_MANAGE + gSmst_SmmInterruptRegister, // EFI_SMM_INTERRUPT_REGISTER + gSmst_SmmInterruptUnRegister // EFI_SMM_INTERRUPT_UNREGISTER +}; + +extern "C" { + EFI_SMM_SYSTEM_TABLE2 *gSmst = &LocalSmst; +} diff --git a/MdePkg/Test/Mock/Library/GoogleTest/MockSmmServicesTableLib/MockSmmServicesTableLib.inf b/MdePkg/Test/Mock/Library/GoogleTest/MockSmmServicesTableLib/MockSmmServicesTableLib.inf new file mode 100644 index 000000000000..d3bb48740982 --- /dev/null +++ b/MdePkg/Test/Mock/Library/GoogleTest/MockSmmServicesTableLib/MockSmmServicesTableLib.inf @@ -0,0 +1,33 @@ +## @file MockSmmServicesTableLib.inf +# Google Test mocks for SmmServicesTableLib +# +# Copyright (c) Microsoft Corporation. +# SPDX-License-Identifier: BSD-2-Clause-Patent +## + +[Defines] + INF_VERSION = 0x00010005 + BASE_NAME = MockSmmServicesTableLib + FILE_GUID = CF640A65-619D-43A1-A22D-7FF21FA2B2AF + MODULE_TYPE = HOST_APPLICATION + VERSION_STRING = 1.0 + LIBRARY_CLASS = SmmServicesTableLib + +# +# The following information is for reference only and not required by the build tools. +# +# VALID_ARCHITECTURES = IA32 X64 +# + +[Sources] + MockSmmServicesTableLib.cpp + +[Packages] + MdePkg/MdePkg.dec + UnitTestFrameworkPkg/UnitTestFrameworkPkg.dec + +[LibraryClasses] + GoogleTestLib + +[BuildOptions] + MSFT:*_*_*_CC_FLAGS = /EHsc diff --git a/MdePkg/Test/Mock/Library/GoogleTest/MockUefiLib/MockUefiLib.cpp b/MdePkg/Test/Mock/Library/GoogleTest/MockUefiLib/MockUefiLib.cpp index 2a0c9613eaa2..7e76a90a41e3 100644 --- a/MdePkg/Test/Mock/Library/GoogleTest/MockUefiLib/MockUefiLib.cpp +++ b/MdePkg/Test/Mock/Library/GoogleTest/MockUefiLib/MockUefiLib.cpp @@ -2,11 +2,55 @@ Google Test mocks for UefiLib Copyright (c) 2022, Intel Corporation. All rights reserved. + Copyright (c) Microsoft Corporation. SPDX-License-Identifier: BSD-2-Clause-Patent **/ + #include MOCK_INTERFACE_DEFINITION (MockUefiLib); +MOCK_FUNCTION_DEFINITION (MockUefiLib, EfiGetSystemConfigurationTable, 2, EFIAPI); +MOCK_FUNCTION_DEFINITION (MockUefiLib, EfiCreateProtocolNotifyEvent, 5, EFIAPI); +MOCK_FUNCTION_DEFINITION (MockUefiLib, EfiNamedEventListen, 5, EFIAPI); +MOCK_FUNCTION_DEFINITION (MockUefiLib, EfiNamedEventSignal, 1, EFIAPI); +MOCK_FUNCTION_DEFINITION (MockUefiLib, EfiEventGroupSignal, 1, EFIAPI); +MOCK_FUNCTION_DEFINITION (MockUefiLib, EfiEventEmptyFunction, 2, EFIAPI); +MOCK_FUNCTION_DEFINITION (MockUefiLib, EfiGetCurrentTpl, 0, EFIAPI); +MOCK_FUNCTION_DEFINITION (MockUefiLib, EfiInitializeLock, 2, EFIAPI); +MOCK_FUNCTION_DEFINITION (MockUefiLib, EfiAcquireLock, 1, EFIAPI); +MOCK_FUNCTION_DEFINITION (MockUefiLib, EfiAcquireLockOrFail, 1, EFIAPI); +MOCK_FUNCTION_DEFINITION (MockUefiLib, EfiReleaseLock, 1, EFIAPI); +MOCK_FUNCTION_DEFINITION (MockUefiLib, EfiTestManagedDevice, 3, EFIAPI); +MOCK_FUNCTION_DEFINITION (MockUefiLib, EfiTestChildHandle, 3, EFIAPI); +MOCK_FUNCTION_DEFINITION (MockUefiLib, IsLanguageSupported, 2, EFIAPI); +MOCK_FUNCTION_DEFINITION (MockUefiLib, LookupUnicodeString, 4, EFIAPI); +MOCK_FUNCTION_DEFINITION (MockUefiLib, LookupUnicodeString2, 5, EFIAPI); +MOCK_FUNCTION_DEFINITION (MockUefiLib, AddUnicodeString, 4, EFIAPI); +MOCK_FUNCTION_DEFINITION (MockUefiLib, AddUnicodeString2, 5, EFIAPI); +MOCK_FUNCTION_DEFINITION (MockUefiLib, FreeUnicodeStringTable, 1, EFIAPI); MOCK_FUNCTION_DEFINITION (MockUefiLib, GetVariable2, 4, EFIAPI); MOCK_FUNCTION_DEFINITION (MockUefiLib, GetEfiGlobalVariable2, 3, EFIAPI); +MOCK_FUNCTION_DEFINITION (MockUefiLib, GetVariable3, 5, EFIAPI); +MOCK_FUNCTION_DEFINITION (MockUefiLib, GetGlyphWidth, 1, EFIAPI); +MOCK_FUNCTION_DEFINITION (MockUefiLib, UnicodeStringDisplayLength, 1, EFIAPI); +MOCK_FUNCTION_DEFINITION (MockUefiLib, EfiSignalEventReadyToBoot, 0, EFIAPI); +MOCK_FUNCTION_DEFINITION (MockUefiLib, EfiSignalEventLegacyBoot, 0, EFIAPI); +MOCK_FUNCTION_DEFINITION (MockUefiLib, EfiCreateEventLegacyBoot, 1, EFIAPI); +MOCK_FUNCTION_DEFINITION (MockUefiLib, EfiCreateEventLegacyBootEx, 4, EFIAPI); +MOCK_FUNCTION_DEFINITION (MockUefiLib, EfiCreateEventReadyToBoot, 1, EFIAPI); +MOCK_FUNCTION_DEFINITION (MockUefiLib, EfiCreateEventReadyToBootEx, 4, EFIAPI); +MOCK_FUNCTION_DEFINITION (MockUefiLib, EfiInitializeFwVolDevicepathNode, 2, EFIAPI); +MOCK_FUNCTION_DEFINITION (MockUefiLib, EfiGetNameGuidFromFwVolDevicePathNode, 1, EFIAPI); +MOCK_FUNCTION_DEFINITION (MockUefiLib, EfiLibInstallDriverBinding, 4, EFIAPI); +MOCK_FUNCTION_DEFINITION (MockUefiLib, EfiLibUninstallDriverBinding, 1, EFIAPI); +MOCK_FUNCTION_DEFINITION (MockUefiLib, EfiLibInstallAllDriverProtocols, 7, EFIAPI); +MOCK_FUNCTION_DEFINITION (MockUefiLib, EfiLibUninstallAllDriverProtocols, 4, EFIAPI); +MOCK_FUNCTION_DEFINITION (MockUefiLib, EfiLibInstallDriverBindingComponentName2, 6, EFIAPI); +MOCK_FUNCTION_DEFINITION (MockUefiLib, EfiLibUninstallDriverBindingComponentName2, 3, EFIAPI); +MOCK_FUNCTION_DEFINITION (MockUefiLib, EfiLibInstallAllDriverProtocols2, 10, EFIAPI); +MOCK_FUNCTION_DEFINITION (MockUefiLib, EfiLibUninstallAllDriverProtocols2, 7, EFIAPI); +MOCK_FUNCTION_DEFINITION (MockUefiLib, EfiLocateProtocolBuffer, 3, EFIAPI); +MOCK_FUNCTION_DEFINITION (MockUefiLib, EfiOpenFileByDevicePath, 4, EFIAPI); +MOCK_FUNCTION_DEFINITION (MockUefiLib, EfiLocateNextAcpiTable, 2, EFIAPI); +MOCK_FUNCTION_DEFINITION (MockUefiLib, EfiLocateFirstAcpiTable, 1, EFIAPI); diff --git a/MdePkg/Test/UnitTest/Library/DevicePathLib/TestDevicePathLib.c b/MdePkg/Test/UnitTest/Library/DevicePathLib/TestDevicePathLib.c index 687497278c95..52e2322c1a26 100644 --- a/MdePkg/Test/UnitTest/Library/DevicePathLib/TestDevicePathLib.c +++ b/MdePkg/Test/UnitTest/Library/DevicePathLib/TestDevicePathLib.c @@ -473,11 +473,9 @@ TestAppendDevicePathInstance ( Appended = AppendDevicePathInstance (NULL, NULL); UT_ASSERT_EQUAL ((uintptr_t)Appended, (uintptr_t)NULL); - FreePool (Appended); Appended = AppendDevicePathInstance ((EFI_DEVICE_PATH_PROTOCOL *)&mSimpleDevicePath, (EFI_DEVICE_PATH_PROTOCOL *)&mInvalidSimpleDevicePath); UT_ASSERT_EQUAL ((uintptr_t)Appended, (uintptr_t)NULL); - FreePool (Appended); return UNIT_TEST_PASSED; } diff --git a/NetworkPkg/Dhcp6Dxe/Dhcp6Utility.c b/NetworkPkg/Dhcp6Dxe/Dhcp6Utility.c index f38e3ee3fe1a..f72bc93a689f 100644 --- a/NetworkPkg/Dhcp6Dxe/Dhcp6Utility.c +++ b/NetworkPkg/Dhcp6Dxe/Dhcp6Utility.c @@ -1001,7 +1001,7 @@ Dhcp6AppendETOption ( return EFI_INVALID_PARAMETER; } - if ((Elapsed == NULL)) { + if (Elapsed == NULL) { return EFI_INVALID_PARAMETER; } diff --git a/NetworkPkg/Dhcp6Dxe/GoogleTest/Dhcp6IoGoogleTest.cpp b/NetworkPkg/Dhcp6Dxe/GoogleTest/Dhcp6IoGoogleTest.cpp index 7db253a7b87f..5998d481f65c 100644 --- a/NetworkPkg/Dhcp6Dxe/GoogleTest/Dhcp6IoGoogleTest.cpp +++ b/NetworkPkg/Dhcp6Dxe/GoogleTest/Dhcp6IoGoogleTest.cpp @@ -161,7 +161,7 @@ TEST_F (Dhcp6AppendOptionTest, ValidDataExpectSuccess) { Packet->Length = sizeof (EFI_DHCP6_HEADER); OriginalLength = Packet->Length; - UntrustedDuid = (EFI_DHCP6_DUID *)AllocateZeroPool (sizeof (EFI_DHCP6_DUID)); + UntrustedDuid = (EFI_DHCP6_DUID *)AllocateZeroPool (OFFSET_OF (EFI_DHCP6_DUID, Duid) + sizeof (Duid)); ASSERT_NE (UntrustedDuid, (EFI_DHCP6_DUID *)NULL); UntrustedDuid->Length = NTOHS (sizeof (Duid)); @@ -763,7 +763,7 @@ TEST_F (Dhcp6SeekStsOptionTest, SeekIATAOptionExpectFail) { Dhcp6SeekStsOptionTest::Packet, &Option, Dhcp6OptStatusCode, - SearchPatternLength, + HTONS (SearchPatternLength), (UINT8 *)&SearchPattern ); ASSERT_EQ (Status, EFI_SUCCESS); @@ -815,7 +815,7 @@ TEST_F (Dhcp6SeekStsOptionTest, SeekIANAOptionExpectSuccess) { Dhcp6SeekStsOptionTest::Packet, &Option, Dhcp6OptStatusCode, - SearchPatternLength, + HTONS (SearchPatternLength), (UINT8 *)&SearchPattern ); ASSERT_EQ (Status, EFI_SUCCESS); diff --git a/NetworkPkg/HttpBootDxe/HttpBootImpl.c b/NetworkPkg/HttpBootDxe/HttpBootImpl.c index 6f10bcff39df..91e934ce06c1 100644 --- a/NetworkPkg/HttpBootDxe/HttpBootImpl.c +++ b/NetworkPkg/HttpBootDxe/HttpBootImpl.c @@ -388,7 +388,8 @@ HttpBootGetBootFileCaller ( ImageType ); if (!EFI_ERROR (Status) || - ((Status != EFI_TIMEOUT) && (Status != EFI_DEVICE_ERROR))) + ((Status != EFI_TIMEOUT) && (Status != EFI_DEVICE_ERROR)) || + (Retries >= PcdGet32 (PcdMaxHttpResumeRetries))) { break; } diff --git a/OvmfPkg/Library/SmmCpuPlatformHookLibQemu/SmmCpuPlatformHookLibQemu.c b/OvmfPkg/Library/SmmCpuPlatformHookLibQemu/SmmCpuPlatformHookLibQemu.c index 4df057101e8b..cab7d90bcc81 100644 --- a/OvmfPkg/Library/SmmCpuPlatformHookLibQemu/SmmCpuPlatformHookLibQemu.c +++ b/OvmfPkg/Library/SmmCpuPlatformHookLibQemu/SmmCpuPlatformHookLibQemu.c @@ -2,7 +2,7 @@ SMM CPU Platform Hook library instance for QEMU. Copyright (c) 2020, Red Hat, Inc. -Copyright (c) 2006 - 2015, Intel Corporation. All rights reserved.
+Copyright (c) 2006 - 2024, Intel Corporation. All rights reserved.
SPDX-License-Identifier: BSD-2-Clause-Patent **/ @@ -113,3 +113,21 @@ GetPlatformPageTableAttribute ( { return EFI_UNSUPPORTED; } + +/** + SMM CPU Platform Hook before executing MMI Handler. + + This function can be used to perform the platform specific items before executing MMI Handler. + + @retval EFI_SUCCESS The smm cpu platform hook before executing MMI Handler is executed successfully. + @retval EFI_UNSUPPORTED The smm cpu platform hook before executing MMI Handler is unsupported. + +**/ +EFI_STATUS +EFIAPI +SmmCpuPlatformHookBeforeMmiHandler ( + VOID + ) +{ + return EFI_UNSUPPORTED; +} diff --git a/OvmfPkg/RiscVVirt/RiscVVirt.dsc.inc b/OvmfPkg/RiscVVirt/RiscVVirt.dsc.inc index b5215705545d..b7ab32f79d51 100644 --- a/OvmfPkg/RiscVVirt/RiscVVirt.dsc.inc +++ b/OvmfPkg/RiscVVirt/RiscVVirt.dsc.inc @@ -78,6 +78,7 @@ # RISC-V Architectural Libraries CpuExceptionHandlerLib|UefiCpuPkg/Library/BaseRiscV64CpuExceptionHandlerLib/BaseRiscV64CpuExceptionHandlerLib.inf RiscVSbiLib|MdePkg/Library/BaseRiscVSbiLib/BaseRiscVSbiLib.inf + RiscVFpuLib|UefiCpuPkg/Library/BaseRiscVFpuLib/BaseRiscVFpuLib.inf RiscVMmuLib|UefiCpuPkg/Library/BaseRiscVMmuLib/BaseRiscVMmuLib.inf PlatformBootManagerLib|OvmfPkg/RiscVVirt/Library/PlatformBootManagerLib/PlatformBootManagerLib.inf ResetSystemLib|OvmfPkg/RiscVVirt/Library/ResetSystemLib/BaseResetSystemLib.inf diff --git a/ReadMe.rst b/ReadMe.rst index 3fbabe1a1b92..dc74f6d4a9ba 100644 --- a/ReadMe.rst +++ b/ReadMe.rst @@ -96,7 +96,7 @@ that are covered by additional licenses. - `MdeModulePkg/Universal/RegularExpressionDxe/oniguruma `__ - `UnitTestFrameworkPkg/Library/CmockaLib/cmocka `__ - `UnitTestFrameworkPkg/Library/GoogleTestLib/googletest `__ -- `UnitTestFrameworkPkg/Library/SubhookLib/subhook `__ +- `UnitTestFrameworkPkg/Library/SubhookLib/subhook `__ - `RedfishPkg/Library/JsonLib/jansson `__ - `MdePkg/Library/BaseFdtLib/libfdt `__ - `MdePkg/Library/MipiSysTLib/mipisyst `__ diff --git a/RedfishPkg/Include/RedfishCommon.h b/RedfishPkg/Include/RedfishCommon.h new file mode 100644 index 000000000000..18244e985544 --- /dev/null +++ b/RedfishPkg/Include/RedfishCommon.h @@ -0,0 +1,17 @@ +/** @file + This header file defines common macros for the use in RedfishPkg. + + Copyright (c) 2024, NVIDIA CORPORATION & AFFILIATES. All rights reserved. + + SPDX-License-Identifier: BSD-2-Clause-Patent + +**/ + +#ifndef REDFISH_COMMON_H_ +#define REDFISH_COMMON_H_ + +#ifndef IS_EMPTY_STRING +#define IS_EMPTY_STRING(a) ((a) == NULL || (a)[0] == '\0') +#endif + +#endif diff --git a/RedfishPkg/Library/RedfishDebugLib/RedfishDebugLib.c b/RedfishPkg/Library/RedfishDebugLib/RedfishDebugLib.c index f8bb51ff5322..694a0878156d 100644 --- a/RedfishPkg/Library/RedfishDebugLib/RedfishDebugLib.c +++ b/RedfishPkg/Library/RedfishDebugLib/RedfishDebugLib.c @@ -9,7 +9,7 @@ **/ #include - +#include #include #include #include @@ -17,10 +17,6 @@ #include #include -#ifndef IS_EMPTY_STRING -#define IS_EMPTY_STRING(a) ((a) == NULL || (a)[0] == '\0') -#endif - #define REDFISH_JSON_STRING_LENGTH 200 #define REDFISH_JSON_OUTPUT_FORMAT (EDKII_JSON_COMPACT | EDKII_JSON_INDENT(2)) #define REDFISH_PRINT_BUFFER_BYTES_PER_ROW 16 diff --git a/RedfishPkg/RedfishCredentialDxe/RedfishCredentialDxe.c b/RedfishPkg/RedfishCredentialDxe/RedfishCredentialDxe.c index 23201e1dc827..9f2b264fed28 100644 --- a/RedfishPkg/RedfishCredentialDxe/RedfishCredentialDxe.c +++ b/RedfishPkg/RedfishCredentialDxe/RedfishCredentialDxe.c @@ -567,6 +567,7 @@ RedfishGetAuthConfig ( **/ EFI_STATUS ClearRedfishServiceList ( + VOID ) { REDFISH_SERVICE_LIST *Instance; @@ -917,7 +918,7 @@ ReleaseCredentialPrivate ( mCredentialPrivate->AccountName = NULL; } - ClearRedfishServiceList (mCredentialPrivate); + ClearRedfishServiceList (); } return EFI_SUCCESS; diff --git a/RedfishPkg/RedfishCredentialDxe/RedfishCredentialDxe.h b/RedfishPkg/RedfishCredentialDxe/RedfishCredentialDxe.h index 4988afab441d..271f884ec9e5 100644 --- a/RedfishPkg/RedfishCredentialDxe/RedfishCredentialDxe.h +++ b/RedfishPkg/RedfishCredentialDxe/RedfishCredentialDxe.h @@ -3,6 +3,7 @@ (C) Copyright 2020 Hewlett Packard Enterprise Development LP
(C) Copyright 2024 American Megatrends International LLC
+ Copyright (c) 2024, NVIDIA CORPORATION & AFFILIATES. All rights reserved. SPDX-License-Identifier: BSD-2-Clause-Patent @@ -11,6 +12,7 @@ #ifndef EDKII_REDFISH_CREDENTIAL_DXE_H_ #define EDKII_REDFISH_CREDENTIAL_DXE_H_ +#include #include #include @@ -29,10 +31,6 @@ #define REDFISH_MANAGER_ACCOUNT_COLLECTION_URI L"AccountService/Accounts" #define REDFISH_URI_LENGTH 128 -#ifndef IS_EMPTY_STRING -#define IS_EMPTY_STRING(a) ((a) == NULL || (a)[0] == '\0') -#endif - /// /// Definition of REDFISH_SERVICE_LIST /// diff --git a/RedfishPkg/RedfishHttpDxe/RedfishHttpDxe.h b/RedfishPkg/RedfishHttpDxe/RedfishHttpDxe.h index 0c4042365506..38c3cd24a405 100644 --- a/RedfishPkg/RedfishHttpDxe/RedfishHttpDxe.h +++ b/RedfishPkg/RedfishHttpDxe/RedfishHttpDxe.h @@ -11,6 +11,7 @@ #define EDKII_REDFISH_HTTP_DXE_H_ #include +#include #include #include @@ -31,7 +32,6 @@ #include #include -#define IS_EMPTY_STRING(a) ((a) == NULL || (a)[0] == '\0') #define REDFISH_HTTP_CACHE_LIST_SIZE 0x80 #define REDFISH_ERROR_MSG_MAX 128 #define REDFISH_DEBUG_STRING_LENGTH 200 diff --git a/RedfishPkg/RedfishPlatformConfigDxe/RedfishPlatformConfigImpl.h b/RedfishPkg/RedfishPlatformConfigDxe/RedfishPlatformConfigImpl.h index 525ca43fa9ae..9ac7f268576c 100644 --- a/RedfishPkg/RedfishPlatformConfigDxe/RedfishPlatformConfigImpl.h +++ b/RedfishPkg/RedfishPlatformConfigDxe/RedfishPlatformConfigImpl.h @@ -13,6 +13,7 @@ #define EDKII_REDFISH_PLATFORM_CONFIG_IMPL_H_ #include +#include // // Libraries @@ -27,7 +28,6 @@ #include #include -#define IS_EMPTY_STRING(a) (a == NULL || a[0] == L'\0') #define ENGLISH_LANGUAGE_CODE "en-US" #define X_UEFI_SCHEMA_PREFIX "x-UEFI-redfish-" diff --git a/ShellPkg/Application/Shell/FileHandleWrappers.c b/ShellPkg/Application/Shell/FileHandleWrappers.c index 2ba9b3401a0c..f98d86a16f3d 100644 --- a/ShellPkg/Application/Shell/FileHandleWrappers.c +++ b/ShellPkg/Application/Shell/FileHandleWrappers.c @@ -2144,6 +2144,10 @@ FileInterfaceFileWrite ( // Ascii // AsciiBuffer = AllocateZeroPool (*BufferSize); + if (AsciiBuffer == NULL) { + return EFI_OUT_OF_RESOURCES; + } + AsciiSPrint (AsciiBuffer, *BufferSize, "%S", Buffer); Size = AsciiStrSize (AsciiBuffer) - 1; // (we dont need the null terminator) Status = (((EFI_FILE_PROTOCOL_FILE *)This)->Orig->Write (((EFI_FILE_PROTOCOL_FILE *)This)->Orig, &Size, AsciiBuffer)); diff --git a/ShellPkg/Application/Shell/Shell.c b/ShellPkg/Application/Shell/Shell.c index 01b4e37871f2..9bacf9d8c761 100644 --- a/ShellPkg/Application/Shell/Shell.c +++ b/ShellPkg/Application/Shell/Shell.c @@ -576,6 +576,11 @@ UefiMain ( Size = 100; TempString = AllocateZeroPool (Size); + if (TempString == NULL) { + ASSERT (TempString != NULL); + Status = EFI_OUT_OF_RESOURCES; + goto FreeResources; + } UnicodeSPrint (TempString, Size, L"%d", PcdGet8 (PcdShellSupportLevel)); Status = InternalEfiShellSetEnv (L"uefishellsupport", TempString, TRUE); @@ -2609,10 +2614,15 @@ RunCommandOrFile ( CommandWithPath = ShellFindFilePathEx (FirstParameter, mExecutableExtensions); } - // - // This should be impossible now. - // - ASSERT (CommandWithPath != NULL); + if (CommandWithPath == NULL) { + // + // This should be impossible now. + // + ASSERT (CommandWithPath != NULL); + ShellPrintHiiEx (-1, -1, NULL, STRING_TOKEN (STR_SHELL_NOT_FOUND), ShellInfoObject.HiiHandle, FirstParameter); + SetLastError (SHELL_NOT_FOUND); + return EFI_NOT_FOUND; + } // // Make sure that path is not just a directory (or not found) @@ -3330,8 +3340,8 @@ FindFirstCharacter ( IN CONST CHAR16 EscapeCharacter ) { - UINT32 WalkChar; - UINT32 WalkStr; + UINTN WalkChar; + UINTN WalkStr; for (WalkStr = 0; WalkStr < StrLen (String); WalkStr++) { if (String[WalkStr] == EscapeCharacter) { diff --git a/ShellPkg/Application/Shell/ShellManParser.c b/ShellPkg/Application/Shell/ShellManParser.c index 5c823cd7f584..f7082467c751 100644 --- a/ShellPkg/Application/Shell/ShellManParser.c +++ b/ShellPkg/Application/Shell/ShellManParser.c @@ -549,6 +549,7 @@ ManFileFindTitleSection ( returned help text. @retval EFI_INVALID_PARAMETER HelpText is NULL. @retval EFI_INVALID_PARAMETER ManFileName is invalid. + @retval EFI_INVALID_PARAMETER Command is invalid. @retval EFI_NOT_FOUND There is no help text available for Command. **/ EFI_STATUS @@ -600,7 +601,12 @@ ProcessManFile ( TempString = ShellCommandGetCommandHelp (Command); if (TempString != NULL) { FileHandle = ConvertEfiFileProtocolToShellHandle (CreateFileInterfaceMem (TRUE), NULL); - HelpSize = StrLen (TempString) * sizeof (CHAR16); + if (FileHandle == NULL) { + Status = EFI_OUT_OF_RESOURCES; + goto Done; + } + + HelpSize = StrLen (TempString) * sizeof (CHAR16); ShellWriteFile (FileHandle, &HelpSize, TempString); ShellSetFilePosition (FileHandle, 0); HelpSize = 0; @@ -624,8 +630,18 @@ ProcessManFile ( Status = SearchPathForFile (TempString, &FileHandle); if (EFI_ERROR (Status)) { FileDevPath = FileDevicePath (NULL, TempString); - DevPath = AppendDevicePath (ShellInfoObject.ImageDevPath, FileDevPath); - Status = InternalOpenFileDevicePath (DevPath, &FileHandle, EFI_FILE_MODE_READ, 0); + if (FileDevPath == NULL) { + Status = EFI_OUT_OF_RESOURCES; + goto Done; + } + + DevPath = AppendDevicePath (ShellInfoObject.ImageDevPath, FileDevPath); + if (DevPath == NULL) { + Status = EFI_OUT_OF_RESOURCES; + goto Done; + } + + Status = InternalOpenFileDevicePath (DevPath, &FileHandle, EFI_FILE_MODE_READ, 0); SHELL_FREE_NON_NULL (FileDevPath); SHELL_FREE_NON_NULL (DevPath); } @@ -733,7 +749,12 @@ ProcessManFile ( } FileHandle = ConvertEfiFileProtocolToShellHandle (CreateFileInterfaceMem (TRUE), NULL); - HelpSize = StrLen (TempString) * sizeof (CHAR16); + if (FileHandle == NULL) { + Status = EFI_OUT_OF_RESOURCES; + goto Done; + } + + HelpSize = StrLen (TempString) * sizeof (CHAR16); ShellWriteFile (FileHandle, &HelpSize, TempString); ShellSetFilePosition (FileHandle, 0); HelpSize = 0; diff --git a/ShellPkg/Application/Shell/ShellParametersProtocol.c b/ShellPkg/Application/Shell/ShellParametersProtocol.c index 64d67d9f1360..8464cbf61612 100644 --- a/ShellPkg/Application/Shell/ShellParametersProtocol.c +++ b/ShellPkg/Application/Shell/ShellParametersProtocol.c @@ -354,7 +354,11 @@ CreatePopulateInstallShellParametersProtocol ( Status = SHELL_GET_ENVIRONMENT_VARIABLE (L"ShellOpt", &Size, FullCommandLine); if (Status == EFI_BUFFER_TOO_SMALL) { FullCommandLine = AllocateZeroPool (Size + LoadedImage->LoadOptionsSize); - Status = SHELL_GET_ENVIRONMENT_VARIABLE (L"ShellOpt", &Size, FullCommandLine); + if (FullCommandLine == NULL) { + return EFI_OUT_OF_RESOURCES; + } + + Status = SHELL_GET_ENVIRONMENT_VARIABLE (L"ShellOpt", &Size, FullCommandLine); } if (Status == EFI_NOT_FOUND) { @@ -738,6 +742,7 @@ UpdateStdInStdOutStdErr ( OutAppend = FALSE; CommandLineCopy = NULL; FirstLocation = NULL; + TempHandle = NULL; if ((ShellParameters == NULL) || (SystemTableInfo == NULL) || (OldStdIn == NULL) || (OldStdOut == NULL) || (OldStdErr == NULL)) { return (EFI_INVALID_PARAMETER); @@ -1176,7 +1181,10 @@ UpdateStdInStdOutStdErr ( if (!ErrUnicode && !EFI_ERROR (Status)) { TempHandle = CreateFileInterfaceFile (TempHandle, FALSE); - ASSERT (TempHandle != NULL); + if (TempHandle == NULL) { + ASSERT (TempHandle != NULL); + Status = EFI_OUT_OF_RESOURCES; + } } if (!EFI_ERROR (Status)) { @@ -1223,7 +1231,10 @@ UpdateStdInStdOutStdErr ( if (!OutUnicode && !EFI_ERROR (Status)) { TempHandle = CreateFileInterfaceFile (TempHandle, FALSE); - ASSERT (TempHandle != NULL); + if (TempHandle == NULL) { + ASSERT (TempHandle != NULL); + Status = EFI_OUT_OF_RESOURCES; + } } if (!EFI_ERROR (Status)) { @@ -1245,9 +1256,13 @@ UpdateStdInStdOutStdErr ( } TempHandle = CreateFileInterfaceEnv (StdOutVarName); - ASSERT (TempHandle != NULL); - ShellParameters->StdOut = TempHandle; - gST->ConOut = CreateSimpleTextOutOnFile (TempHandle, &gST->ConsoleOutHandle, gST->ConOut); + if (TempHandle == NULL) { + ASSERT (TempHandle != NULL); + Status = EFI_OUT_OF_RESOURCES; + } else { + ShellParameters->StdOut = TempHandle; + gST->ConOut = CreateSimpleTextOutOnFile (TempHandle, &gST->ConsoleOutHandle, gST->ConOut); + } } // @@ -1262,9 +1277,13 @@ UpdateStdInStdOutStdErr ( } TempHandle = CreateFileInterfaceEnv (StdErrVarName); - ASSERT (TempHandle != NULL); - ShellParameters->StdErr = TempHandle; - gST->StdErr = CreateSimpleTextOutOnFile (TempHandle, &gST->StandardErrorHandle, gST->StdErr); + if (TempHandle == NULL) { + ASSERT (TempHandle != NULL); + Status = EFI_OUT_OF_RESOURCES; + } else { + ShellParameters->StdErr = TempHandle; + gST->StdErr = CreateSimpleTextOutOnFile (TempHandle, &gST->StandardErrorHandle, gST->StdErr); + } } // @@ -1307,8 +1326,12 @@ UpdateStdInStdOutStdErr ( TempHandle = CreateFileInterfaceFile (TempHandle, FALSE); } - ShellParameters->StdIn = TempHandle; - gST->ConIn = CreateSimpleTextInOnFile (TempHandle, &gST->ConsoleInHandle); + if (TempHandle == NULL) { + Status = EFI_OUT_OF_RESOURCES; + } else { + ShellParameters->StdIn = TempHandle; + gST->ConIn = CreateSimpleTextInOnFile (TempHandle, &gST->ConsoleInHandle); + } } } } diff --git a/ShellPkg/Application/Shell/ShellProtocol.c b/ShellPkg/Application/Shell/ShellProtocol.c index da8c31cb038a..ff53f6ba4ff9 100644 --- a/ShellPkg/Application/Shell/ShellProtocol.c +++ b/ShellPkg/Application/Shell/ShellProtocol.c @@ -436,7 +436,10 @@ EfiShellGetFilePathFromDevicePath ( if ((DevicePathType (&FilePath->Header) != MEDIA_DEVICE_PATH) || (DevicePathSubType (&FilePath->Header) != MEDIA_FILEPATH_DP)) { - FreePool (PathForReturn); + if (PathForReturn != NULL) { + FreePool (PathForReturn); + } + return NULL; } @@ -447,7 +450,10 @@ EfiShellGetFilePathFromDevicePath ( AlignedNode = AllocateCopyPool (DevicePathNodeLength (FilePath), FilePath); if (AlignedNode == NULL) { - FreePool (PathForReturn); + if (PathForReturn != NULL) { + FreePool (PathForReturn); + } + return NULL; } @@ -719,7 +725,11 @@ EfiShellGetDeviceName ( continue; } - Lang = GetBestLanguageForDriver (CompName2->SupportedLanguages, Language, FALSE); + Lang = GetBestLanguageForDriver (CompName2->SupportedLanguages, Language, FALSE); + if (Lang == NULL) { + continue; + } + Status = CompName2->GetControllerName (CompName2, DeviceHandle, NULL, Lang, &DeviceNameToReturn); FreePool (Lang); Lang = NULL; @@ -767,7 +777,11 @@ EfiShellGetDeviceName ( continue; } - Lang = GetBestLanguageForDriver (CompName2->SupportedLanguages, Language, FALSE); + Lang = GetBestLanguageForDriver (CompName2->SupportedLanguages, Language, FALSE); + if (Lang == NULL) { + continue; + } + Status = CompName2->GetControllerName (CompName2, ParentControllerBuffer[LoopVar], DeviceHandle, Lang, &DeviceNameToReturn); FreePool (Lang); Lang = NULL; @@ -1817,16 +1831,32 @@ EfiShellExecute ( return (EFI_UNSUPPORTED); } + Temp = NULL; if (NestingEnabled ()) { DevPath = AppendDevicePath (ShellInfoObject.ImageDevPath, ShellInfoObject.FileDevPath); + if (DevPath == NULL) { + return EFI_OUT_OF_RESOURCES; + } DEBUG_CODE_BEGIN (); Temp = ConvertDevicePathToText (ShellInfoObject.FileDevPath, TRUE, TRUE); - FreePool (Temp); + if (Temp != NULL) { + FreePool (Temp); + } + Temp = ConvertDevicePathToText (ShellInfoObject.ImageDevPath, TRUE, TRUE); - FreePool (Temp); - Temp = ConvertDevicePathToText (DevPath, TRUE, TRUE); - FreePool (Temp); + if (Temp != NULL) { + FreePool (Temp); + } + + if (DevPath != NULL) { + Temp = ConvertDevicePathToText (DevPath, TRUE, TRUE); + } + + if (Temp != NULL) { + FreePool (Temp); + } + DEBUG_CODE_END (); Temp = NULL; @@ -2395,6 +2425,8 @@ ShellSearchHandle ( CHAR16 *NewFullName; UINTN Size; + NewShellNode = NULL; + FileInfo = NULL; if ( (FilePattern == NULL) || (UnicodeCollation == NULL) || (FileList == NULL) @@ -2434,14 +2466,17 @@ ShellSearchHandle ( // // We want the root node. create the node. // - FileInfo = FileHandleGetInfo (FileHandle); - NewShellNode = CreateAndPopulateShellFileInfo ( - MapName, - EFI_SUCCESS, - L"\\", - FileHandle, - FileInfo - ); + FileInfo = FileHandleGetInfo (FileHandle); + if (FileInfo != NULL) { + NewShellNode = CreateAndPopulateShellFileInfo ( + MapName, + EFI_SUCCESS, + L"\\", + FileHandle, + FileInfo + ); + } + SHELL_FREE_NON_NULL (FileInfo); } else { // @@ -2631,6 +2666,9 @@ EfiShellFindFiles ( } PatternCopy = PathCleanUpDirectories (PatternCopy); + if (PatternCopy == NULL) { + return (EFI_OUT_OF_RESOURCES); + } Count = StrStr (PatternCopy, L":") - PatternCopy + 1; ASSERT (Count <= StrLen (PatternCopy)); @@ -2715,6 +2753,10 @@ EfiShellOpenFileList ( // if (StrStr (Path, L":") == NULL) { CurDir = EfiShellGetCurDir (NULL); + if (CurDir == NULL) { + return EFI_NOT_FOUND; + } + ASSERT ((Path2 == NULL && Path2Size == 0) || (Path2 != NULL)); StrnCatGrow (&Path2, &Path2Size, CurDir, 0); StrnCatGrow (&Path2, &Path2Size, L"\\", 0); @@ -2855,6 +2897,10 @@ EfiShellGetEnvEx ( // Allocate the space and recall the get function // Buffer = AllocateZeroPool (Size); + if (Buffer == NULL) { + return NULL; + } + Status = SHELL_GET_ENVIRONMENT_VARIABLE_AND_ATTRIBUTES (Name, Attributes, &Size, Buffer); } @@ -3122,7 +3168,10 @@ EfiShellSetCurDir ( } DirectoryName = StrnCatGrow (&DirectoryName, NULL, Dir, 0); - ASSERT (DirectoryName != NULL); + if (DirectoryName == NULL) { + ASSERT (DirectoryName != NULL); + return (EFI_OUT_OF_RESOURCES); + } PathCleanUpDirectories (DirectoryName); @@ -3500,6 +3549,11 @@ EfiShellGetAlias ( Status = gRT->GetVariable (AliasLower, &gShellAliasGuid, &Attribs, &RetSize, RetVal); if (Status == EFI_BUFFER_TOO_SMALL) { RetVal = AllocateZeroPool (RetSize); + if (RetVal == NULL) { + FreePool (AliasLower); + return NULL; + } + Status = gRT->GetVariable (AliasLower, &gShellAliasGuid, &Attribs, &RetSize, RetVal); } diff --git a/ShellPkg/DynamicCommand/HttpDynamicCommand/Http.c b/ShellPkg/DynamicCommand/HttpDynamicCommand/Http.c index b4e88e7635bc..37afefd80bf3 100644 --- a/ShellPkg/DynamicCommand/HttpDynamicCommand/Http.c +++ b/ShellPkg/DynamicCommand/HttpDynamicCommand/Http.c @@ -1815,6 +1815,10 @@ DownloadFile ( Context->Uri, StrLen (Context->Uri) ); + if (DownloadUrl == NULL) { + Status = EFI_OUT_OF_RESOURCES; + goto ON_EXIT; + } PRINT_HII (STRING_TOKEN (STR_HTTP_DOWNLOADING), DownloadUrl); diff --git a/ShellPkg/DynamicCommand/TftpDynamicCommand/Tftp.c b/ShellPkg/DynamicCommand/TftpDynamicCommand/Tftp.c index 7e5c73b3daaa..a60d6be2d6e0 100644 --- a/ShellPkg/DynamicCommand/TftpDynamicCommand/Tftp.c +++ b/ShellPkg/DynamicCommand/TftpDynamicCommand/Tftp.c @@ -395,7 +395,11 @@ RunTftp ( } RemoteFilePath = ShellCommandLineGetRawValue (CheckPackage, 2); - ASSERT (RemoteFilePath != NULL); + if (RemoteFilePath == NULL) { + ASSERT (RemoteFilePath != NULL); + goto Error; + } + FilePathSize = StrLen (RemoteFilePath) + 1; AsciiRemoteFilePath = AllocatePool (FilePathSize); if (AsciiRemoteFilePath == NULL) { diff --git a/ShellPkg/Library/UefiHandleParsingLib/UefiHandleParsingLib.c b/ShellPkg/Library/UefiHandleParsingLib/UefiHandleParsingLib.c index 781da4d55d96..1e3ba1b0a91f 100644 --- a/ShellPkg/Library/UefiHandleParsingLib/UefiHandleParsingLib.c +++ b/ShellPkg/Library/UefiHandleParsingLib/UefiHandleParsingLib.c @@ -299,6 +299,9 @@ LoadedImageProtocolDumpInformation ( SHELL_FREE_NON_NULL (Temp); SHELL_FREE_NON_NULL (FileName); + if (RetVal == NULL) { + return NULL; + } } Temp = HiiGetString (mHandleParsingHiiHandle, STRING_TOKEN (STR_LI_DUMP_MAIN), NULL); @@ -309,24 +312,25 @@ LoadedImageProtocolDumpInformation ( PdbFileName = PeCoffLoaderGetPdbPointer (LoadedImage->ImageBase); DataType = ConvertMemoryType (LoadedImage->ImageDataType); CodeType = ConvertMemoryType (LoadedImage->ImageCodeType); - - RetVal = CatSPrint ( - RetVal, - Temp, - LoadedImage->Revision, - LoadedImage->ParentHandle, - LoadedImage->SystemTable, - LoadedImage->DeviceHandle, - FilePath, - PdbFileName, - LoadedImage->LoadOptionsSize, - LoadedImage->LoadOptions, - LoadedImage->ImageBase, - LoadedImage->ImageSize, - CodeType, - DataType, - LoadedImage->Unload - ); + if ((PdbFileName != NULL) && (DataType != NULL) && (CodeType != NULL) && (FilePath != NULL)) { + RetVal = CatSPrint ( + RetVal, + Temp, + LoadedImage->Revision, + LoadedImage->ParentHandle, + LoadedImage->SystemTable, + LoadedImage->DeviceHandle, + FilePath, + PdbFileName, + LoadedImage->LoadOptionsSize, + LoadedImage->LoadOptions, + LoadedImage->ImageBase, + LoadedImage->ImageSize, + CodeType, + DataType, + LoadedImage->Unload + ); + } SHELL_FREE_NON_NULL (Temp); SHELL_FREE_NON_NULL (FilePath); @@ -389,6 +393,10 @@ GraphicsOutputProtocolDumpInformation ( } Fmt = ConvertPixelFormat (GraphicsOutput->Mode->Info->PixelFormat); + if (Fmt == NULL) { + SHELL_FREE_NON_NULL (Temp); + return NULL; + } RetVal = CatSPrint ( NULL, @@ -409,6 +417,9 @@ GraphicsOutputProtocolDumpInformation ( ); SHELL_FREE_NON_NULL (Temp); + if (RetVal == NULL) { + goto EXIT; + } Temp = HiiGetString (mHandleParsingHiiHandle, STRING_TOKEN (STR_GOP_RES_LIST_MAIN), NULL); if (Temp == NULL) { @@ -509,6 +520,9 @@ EdidDiscoveredProtocolDumpInformation ( RetVal = CatSPrint (NULL, Temp, EdidDiscovered->SizeOfEdid); SHELL_FREE_NON_NULL (Temp); + if (RetVal == NULL) { + return NULL; + } if (EdidDiscovered->SizeOfEdid != 0) { Temp = HiiGetString (mHandleParsingHiiHandle, STRING_TOKEN (STR_EDID_DISCOVERED_DATA), NULL); @@ -575,6 +589,9 @@ EdidActiveProtocolDumpInformation ( RetVal = CatSPrint (NULL, Temp, EdidActive->SizeOfEdid); SHELL_FREE_NON_NULL (Temp); + if (RetVal == NULL) { + return NULL; + } if (EdidActive->SizeOfEdid != 0) { Temp = HiiGetString (mHandleParsingHiiHandle, STRING_TOKEN (STR_EDID_ACTIVE_DATA), NULL); @@ -790,6 +807,9 @@ TxtOutProtocolDumpInformation ( Size = (Dev->Mode->MaxMode + 1) * 80; RetVal = AllocateZeroPool (Size); + if (RetVal == NULL) { + return NULL; + } Temp = HiiGetString (mHandleParsingHiiHandle, STRING_TOKEN (STR_TXT_OUT_DUMP_HEADER), NULL); if (Temp != NULL) { @@ -801,6 +821,11 @@ TxtOutProtocolDumpInformation ( // Dump TextOut Info // Temp = HiiGetString (mHandleParsingHiiHandle, STRING_TOKEN (STR_TXT_OUT_DUMP_LINE), NULL); + if (Temp == NULL) { + FreePool (RetVal); + return NULL; + } + for (Index = 0; Index < Dev->Mode->MaxMode; Index++) { Status = Dev->QueryMode (Dev, Index, &Col, &Row); NewSize = Size - StrSize (RetVal); @@ -1056,6 +1081,10 @@ BusSpecificDriverOverrideProtocolDumpInformation ( ConvertHandleToHandleIndex (ImageHandle), ConvertDevicePathToText (LoadedImage->FilePath, TRUE, TRUE) ); + if (TempRetVal == NULL) { + break; + } + StrnCatGrow (&RetVal, &Size, TempRetVal, 0); SHELL_FREE_NON_NULL (TempRetVal); } @@ -1287,6 +1316,11 @@ PciIoProtocolDumpInformation ( Pci.Hdr.ClassCode[1], Pci.Hdr.ClassCode[2] ); + if (RetVal == NULL) { + FreePool (GetString); + return NULL; + } + for (Index = 0; Index < sizeof (Pci); Index++) { if ((Index % 0x10) == 0) { TempRetVal = CatSPrint (RetVal, L"\r\n %02x", *((UINT8 *)(&Pci) + Index)); @@ -1435,6 +1469,10 @@ AdapterInformationDumpInformation ( } RetVal = CatSPrint (NULL, TempStr); + if (RetVal == NULL) { + goto ERROR_EXIT; + } + SHELL_FREE_NON_NULL (TempStr); for (GuidIndex = 0; GuidIndex < InfoTypesBufferCount; GuidIndex++) { @@ -1726,6 +1764,10 @@ FirmwareManagementDumpInformation ( } RetVal = CatSPrint (NULL, TempStr, ImageInfoSize); + if (RetVal == NULL) { + goto ERROR_EXIT; + } + SHELL_FREE_NON_NULL (TempStr); // @@ -1823,37 +1865,65 @@ FirmwareManagementDumpInformation ( } else { AttributeSettingStr = CatSPrint (NULL, L"("); + if (AttributeSettingStr == NULL) { + goto ERROR_EXIT; + } + if ((AttributeSetting & IMAGE_ATTRIBUTE_IMAGE_UPDATABLE) != 0x0) { TempRetVal = CatSPrint (AttributeSettingStr, L" IMAGE_ATTRIBUTE_IMAGE_UPDATABLE"); + if (TempRetVal == NULL) { + goto ERROR_EXIT; + } + SHELL_FREE_NON_NULL (AttributeSettingStr); AttributeSettingStr = TempRetVal; } if ((AttributeSetting & IMAGE_ATTRIBUTE_RESET_REQUIRED) != 0x0) { TempRetVal = CatSPrint (AttributeSettingStr, L" IMAGE_ATTRIBUTE_RESET_REQUIRED"); + if (TempRetVal == NULL) { + goto ERROR_EXIT; + } + SHELL_FREE_NON_NULL (AttributeSettingStr); AttributeSettingStr = TempRetVal; } if ((AttributeSetting & IMAGE_ATTRIBUTE_AUTHENTICATION_REQUIRED) != 0x0) { TempRetVal = CatSPrint (AttributeSettingStr, L" IMAGE_ATTRIBUTE_AUTHENTICATION_REQUIRED"); + if (TempRetVal == NULL) { + goto ERROR_EXIT; + } + SHELL_FREE_NON_NULL (AttributeSettingStr); AttributeSettingStr = TempRetVal; } if ((AttributeSetting & IMAGE_ATTRIBUTE_IN_USE) != 0x0) { TempRetVal = CatSPrint (AttributeSettingStr, L" IMAGE_ATTRIBUTE_IN_USE"); + if (TempRetVal == NULL) { + goto ERROR_EXIT; + } + SHELL_FREE_NON_NULL (AttributeSettingStr); AttributeSettingStr = TempRetVal; } if ((AttributeSetting & IMAGE_ATTRIBUTE_UEFI_IMAGE) != 0x0) { TempRetVal = CatSPrint (AttributeSettingStr, L" IMAGE_ATTRIBUTE_UEFI_IMAGE"); + if (TempRetVal == NULL) { + goto ERROR_EXIT; + } + SHELL_FREE_NON_NULL (AttributeSettingStr); AttributeSettingStr = TempRetVal; } TempRetVal = CatSPrint (AttributeSettingStr, L" )"); + if (TempRetVal == NULL) { + goto ERROR_EXIT; + } + SHELL_FREE_NON_NULL (AttributeSettingStr); AttributeSettingStr = TempRetVal; } @@ -2848,7 +2918,11 @@ GetStringNameFromHandle ( ); if (!EFI_ERROR (Status)) { BestLang = GetBestLanguageForDriver (CompNameStruct->SupportedLanguages, Language, FALSE); - Status = CompNameStruct->GetDriverName (CompNameStruct, BestLang, &RetVal); + if (BestLang == NULL) { + return (NULL); + } + + Status = CompNameStruct->GetDriverName (CompNameStruct, BestLang, &RetVal); if (BestLang != NULL) { FreePool (BestLang); BestLang = NULL; @@ -2869,7 +2943,11 @@ GetStringNameFromHandle ( ); if (!EFI_ERROR (Status)) { BestLang = GetBestLanguageForDriver (CompNameStruct->SupportedLanguages, Language, FALSE); - Status = CompNameStruct->GetDriverName (CompNameStruct, BestLang, &RetVal); + if (BestLang == NULL) { + return (NULL); + } + + Status = CompNameStruct->GetDriverName (CompNameStruct, BestLang, &RetVal); if (BestLang != NULL) { FreePool (BestLang); } diff --git a/ShellPkg/Library/UefiShellAcpiViewCommandLib/AcpiParser.h b/ShellPkg/Library/UefiShellAcpiViewCommandLib/AcpiParser.h index 32816242fc23..ded5657f007c 100644 --- a/ShellPkg/Library/UefiShellAcpiViewCommandLib/AcpiParser.h +++ b/ShellPkg/Library/UefiShellAcpiViewCommandLib/AcpiParser.h @@ -1029,6 +1029,29 @@ ParseAcpiRas2 ( IN UINT8 AcpiTableRevision ); +/** + This function parses the ACPI RASF table. + When trace is enabled this function parses the RASF table and + traces the ACPI table fields. + + This function parses the RASF ACPI table + + This function also performs validation of the ACPI table fields. + + @param [in] Trace If TRUE, trace the ACPI fields. + @param [in] Ptr Pointer to the start of the buffer. + @param [in] AcpiTableLength Length of the ACPI table. + @param [in] AcpiTableRevision Revision of the ACPI table. +**/ +VOID +EFIAPI +ParseAcpiRasf ( + IN BOOLEAN Trace, + IN UINT8 *Ptr, + IN UINT32 AcpiTableLength, + IN UINT8 AcpiTableRevision + ); + /** This function parses the ACPI RSDP table. diff --git a/ShellPkg/Library/UefiShellAcpiViewCommandLib/Parsers/Ras2/Ras2Parser.c b/ShellPkg/Library/UefiShellAcpiViewCommandLib/Parsers/Ras2/Ras2Parser.c index 9c61b96817ab..38bd15d95f11 100644 --- a/ShellPkg/Library/UefiShellAcpiViewCommandLib/Parsers/Ras2/Ras2Parser.c +++ b/ShellPkg/Library/UefiShellAcpiViewCommandLib/Parsers/Ras2/Ras2Parser.c @@ -14,9 +14,6 @@ #include "AcpiParser.h" #include "AcpiView.h" -// Maximum Memory Domain matrix print size. -#define MAX_MEMORY_DOMAIN_TARGET_PRINT_MATRIX 10 - // Local variables STATIC CONST UINT16 *Ras2PccDescriptors; diff --git a/ShellPkg/Library/UefiShellAcpiViewCommandLib/Parsers/Rasf/RasfParser.c b/ShellPkg/Library/UefiShellAcpiViewCommandLib/Parsers/Rasf/RasfParser.c new file mode 100644 index 000000000000..d78531cbe1a8 --- /dev/null +++ b/ShellPkg/Library/UefiShellAcpiViewCommandLib/Parsers/Rasf/RasfParser.c @@ -0,0 +1,61 @@ +/** @file + RASF table parser + + Copyright (c) 2024, Arm Limited. All rights reserved. + SPDX-License-Identifier: BSD-2-Clause-Patent + + @par Reference(s): + - ACPI 6.5 Specification - August 2022 +**/ + +#include +#include +#include +#include "AcpiParser.h" +#include "AcpiView.h" + +STATIC ACPI_DESCRIPTION_HEADER_INFO AcpiHdrInfo; + +/** + An ACPI_PARSER array describing the ACPI RASF Table. +**/ +STATIC CONST ACPI_PARSER RasfParser[] = { + PARSE_ACPI_HEADER (&AcpiHdrInfo), + { L"RASF PCC Identifier", 12,36, L"%02X %02X %02X %02X - %02X %02X %02X %02X - %02X %02X %02X %02X", Dump12Chars, NULL, NULL, NULL } +}; + +/** + This function parses the ACPI RASF table. + When trace is enabled this function parses the RASF table and + traces the ACPI table fields. + + This function also performs validation of the ACPI table fields. + + @param [in] Trace If TRUE, trace the ACPI fields. + @param [in] Ptr Pointer to the start of the buffer. + @param [in] AcpiTableLength Length of the ACPI table. + @param [in] AcpiTableRevision Revision of the ACPI table. +**/ +VOID +EFIAPI +ParseAcpiRasf ( + IN BOOLEAN Trace, + IN UINT8 *Ptr, + IN UINT32 AcpiTableLength, + IN UINT8 AcpiTableRevision + ) +{ + if (!Trace) { + return; + } + + // Parse ACPI Header + RASF "fixed" fields + ParseAcpi ( + Trace, + 0, + "RASF", + Ptr, + AcpiTableLength, + PARSER_PARAMS (RasfParser) + ); +} diff --git a/ShellPkg/Library/UefiShellAcpiViewCommandLib/UefiShellAcpiViewCommandLib.c b/ShellPkg/Library/UefiShellAcpiViewCommandLib/UefiShellAcpiViewCommandLib.c index 5e73a3909543..7b140a062b6a 100644 --- a/ShellPkg/Library/UefiShellAcpiViewCommandLib/UefiShellAcpiViewCommandLib.c +++ b/ShellPkg/Library/UefiShellAcpiViewCommandLib/UefiShellAcpiViewCommandLib.c @@ -72,6 +72,7 @@ ACPI_TABLE_PARSER ParserList[] = { { EFI_ACPI_6_4_PROCESSOR_PROPERTIES_TOPOLOGY_TABLE_STRUCTURE_SIGNATURE, ParseAcpiPptt }, { EFI_ACPI_6_5_ACPI_RAS2_FEATURE_TABLE_SIGNATURE, ParseAcpiRas2 }, + { EFI_ACPI_6_5_ACPI_RAS_FEATURE_TABLE_SIGNATURE, ParseAcpiRasf }, { RSDP_TABLE_INFO, ParseAcpiRsdp }, { EFI_ACPI_6_2_SYSTEM_LOCALITY_INFORMATION_TABLE_SIGNATURE, ParseAcpiSlit }, { EFI_ACPI_6_2_SERIAL_PORT_CONSOLE_REDIRECTION_TABLE_SIGNATURE, ParseAcpiSpcr }, diff --git a/ShellPkg/Library/UefiShellAcpiViewCommandLib/UefiShellAcpiViewCommandLib.inf b/ShellPkg/Library/UefiShellAcpiViewCommandLib/UefiShellAcpiViewCommandLib.inf index 7ef8b0afb7b2..af77856a8531 100644 --- a/ShellPkg/Library/UefiShellAcpiViewCommandLib/UefiShellAcpiViewCommandLib.inf +++ b/ShellPkg/Library/UefiShellAcpiViewCommandLib/UefiShellAcpiViewCommandLib.inf @@ -51,6 +51,7 @@ Parsers/Pptt/PpttParser.c Parsers/Pptt/PpttParser.h Parsers/Ras2/Ras2Parser.c + Parsers/Rasf/RasfParser.c Parsers/Rsdp/RsdpParser.c Parsers/Slit/SlitParser.c Parsers/Spcr/SpcrParser.c diff --git a/ShellPkg/Library/UefiShellBcfgCommandLib/UefiShellBcfgCommandLib.c b/ShellPkg/Library/UefiShellBcfgCommandLib/UefiShellBcfgCommandLib.c index 0b94d9f5a183..b5617703c795 100644 --- a/ShellPkg/Library/UefiShellBcfgCommandLib/UefiShellBcfgCommandLib.c +++ b/ShellPkg/Library/UefiShellBcfgCommandLib/UefiShellBcfgCommandLib.c @@ -99,6 +99,7 @@ UpdateOptionalData ( UINT8 *OriginalData; UINTN NewSize; UINT8 *NewData; + UINTN TmpSize; UINTN OriginalOptionDataSize; UnicodeSPrint (VariableName, sizeof (VariableName), L"%s%04x", Target == BcfgTargetBootOrder ? L"Boot" : L"Driver", Index); @@ -135,11 +136,14 @@ UpdateOptionalData ( // Allocate new struct and discard old optional data. // ASSERT (OriginalData != NULL); - OriginalOptionDataSize = sizeof (UINT32) + sizeof (UINT16) + StrSize (((CHAR16 *)(OriginalData + sizeof (UINT32) + sizeof (UINT16)))); - OriginalOptionDataSize += (*(UINT16 *)(OriginalData + sizeof (UINT32))); - OriginalOptionDataSize -= OriginalSize; - NewSize = OriginalSize - OriginalOptionDataSize + DataSize; - NewData = AllocatePool (NewSize); + // Length of Attributes, FilePathListLength, Description fields + TmpSize = sizeof (UINT32) + sizeof (UINT16) + StrSize (((CHAR16 *)(OriginalData + sizeof (UINT32) + sizeof (UINT16)))); + // Length of FilePathList field + TmpSize += (*(UINT16 *)(OriginalData + sizeof (UINT32))); + // What remains is the original OptionalData field + OriginalOptionDataSize = OriginalSize - TmpSize; + NewSize = OriginalSize - OriginalOptionDataSize + DataSize; + NewData = AllocatePool (NewSize); if (NewData == NULL) { Status = EFI_OUT_OF_RESOURCES; } else { @@ -202,6 +206,10 @@ GetBootOptionCrc ( ); if (Status == EFI_BUFFER_TOO_SMALL) { Buffer = AllocateZeroPool (BufferSize); + if (Buffer == NULL) { + return EFI_OUT_OF_RESOURCES; + } + Status = gRT->GetVariable ( VariableName, (EFI_GUID *)&gEfiGlobalVariableGuid, @@ -423,7 +431,12 @@ BcfgMod ( } if (BcfgOperation->Type == BcfgTypeModh) { - CurHandle = ConvertHandleIndexToHandle (BcfgOperation->HandleIndex); + CurHandle = ConvertHandleIndexToHandle (BcfgOperation->HandleIndex); + if (CurHandle == NULL) { + ShellPrintHiiEx (-1, -1, NULL, STRING_TOKEN (STR_GEN_PARAM_INV), gShellBcfgHiiHandle, L"bcfg", L"Handle Number"); + return (SHELL_INVALID_PARAMETER); + } + ShellStatus = GetDevicePathByHandle (CurHandle, BcfgOperation->Target, &DevicePathBuffer); if (ShellStatus == SHELL_SUCCESS) { DevicePath = DuplicateDevicePath (DevicePathBuffer); @@ -506,7 +519,12 @@ BcfgMod ( LoadOption.Description = AllocateCopyPool (StrSize (BcfgOperation->Description), BcfgOperation->Description); } else { SHELL_FREE_NON_NULL (LoadOption.FilePath); - LoadOption.FilePath = DuplicateDevicePath (DevicePath); + if (DevicePath != NULL) { + LoadOption.FilePath = DuplicateDevicePath (DevicePath); + } else { + ShellPrintHiiEx (-1, -1, NULL, STRING_TOKEN (SHELL_OUT_OF_RESOURCES), gShellBcfgHiiHandle, L"bcfg", OptionStr); + goto Done; + } } Status = EfiBootManagerLoadOptionToVariable (&LoadOption); @@ -518,6 +536,8 @@ BcfgMod ( EfiBootManagerFreeLoadOption (&LoadOption); +Done: + if (DevicePath != NULL) { FreePool (DevicePath); } @@ -781,10 +801,17 @@ BcfgAdd ( // // Add the option // - DescSize = StrSize (Desc); - FilePathSize = GetDevicePathSize (FilePath); + DescSize = StrSize (Desc); + if (FilePath == NULL) { + ASSERT (FilePath != NULL); + ShellStatus = SHELL_UNSUPPORTED; + TempByteBuffer = NULL; + } else { + FilePathSize = GetDevicePathSize (FilePath); + + TempByteBuffer = AllocateZeroPool (sizeof (UINT32) + sizeof (UINT16) + DescSize + FilePathSize); + } - TempByteBuffer = AllocateZeroPool (sizeof (UINT32) + sizeof (UINT16) + DescSize + FilePathSize); if (TempByteBuffer != NULL) { TempByteStart = TempByteBuffer; *((UINT32 *)TempByteBuffer) = LOAD_OPTION_ACTIVE; // Attributes @@ -1020,7 +1047,7 @@ BcfgAddOpt ( SHELL_STATUS ShellStatus; EFI_STATUS Status; UINT16 OptionIndex; - UINT16 LoopCounter; + UINT32 LoopCounter; UINT64 Intermediate; CONST CHAR16 *Temp; CONST CHAR16 *Walker; @@ -1089,7 +1116,13 @@ BcfgAddOpt ( } Temp2 = StrStr (FileName, L"\""); - ASSERT (Temp2 != NULL); + if (Temp2 == NULL) { + ASSERT (Temp2 != NULL); + ShellPrintHiiEx (-1, -1, NULL, STRING_TOKEN (STR_GEN_PARAM_INV), gShellBcfgHiiHandle, L"bcfg", Walker); + ShellStatus = SHELL_INVALID_PARAMETER; + return (ShellStatus); + } + Temp2[0] = CHAR_NULL; Temp2++; if (StrLen (Temp2) > 0) { @@ -1359,6 +1392,12 @@ BcfgDisplayDump ( ); if (Status == EFI_BUFFER_TOO_SMALL) { Buffer = AllocateZeroPool (BufferSize); + if (Buffer == NULL) { + ShellPrintHiiEx (-1, -1, NULL, STRING_TOKEN (STR_GEN_NO_MEM), gShellBcfgHiiHandle, L"bcfg"); + ++Errors; + goto Cleanup; + } + Status = gRT->GetVariable ( VariableName, (EFI_GUID *)&gEfiGlobalVariableGuid, @@ -1399,6 +1438,11 @@ BcfgDisplayDump ( if (LoadOption->FilePathListLength != 0) { FilePathList = (UINT8 *)Description + DescriptionSize; DevPathString = ConvertDevicePathToText (FilePathList, TRUE, FALSE); + if (DevPathString == NULL) { + ShellPrintHiiEx (-1, -1, NULL, STRING_TOKEN (STR_GEN_NO_MEM), gShellBcfgHiiHandle, L"bcfg"); + ++Errors; + goto Cleanup; + } } OptionalDataOffset = sizeof *LoadOption + DescriptionSize + @@ -1586,6 +1630,12 @@ ShellCommandRunBcfg ( if ((ShellStatus == SHELL_SUCCESS) && (CurrentOperation.Target < BcfgTargetMax)) { for (ParamNumber = 2; ParamNumber < ShellCommandLineGetCount (Package) && ShellStatus == SHELL_SUCCESS; ParamNumber++) { CurrentParam = ShellCommandLineGetRawValue (Package, ParamNumber); + if (CurrentParam == NULL) { + ShellPrintHiiEx (-1, -1, NULL, STRING_TOKEN (STR_GEN_PARAM_INV), gShellBcfgHiiHandle, L"bcfg", L"NULL"); + ShellStatus = SHELL_INVALID_PARAMETER; + goto Done; + } + if (gUnicodeCollation->StriColl (gUnicodeCollation, (CHAR16 *)CurrentParam, L"dump") == 0) { CurrentOperation.Type = BcfgTypeDump; if (ShellCommandLineGetCount (Package) > 3) { @@ -1879,6 +1929,8 @@ ShellCommandRunBcfg ( } } +Done: + if (Package != NULL) { ShellCommandLineFreeVarList (Package); } diff --git a/ShellPkg/Library/UefiShellCommandLib/ConsistMapping.c b/ShellPkg/Library/UefiShellCommandLib/ConsistMapping.c index 1767a7dc4af6..9ef6a0192f3b 100755 --- a/ShellPkg/Library/UefiShellCommandLib/ConsistMapping.c +++ b/ShellPkg/Library/UefiShellCommandLib/ConsistMapping.c @@ -1404,6 +1404,10 @@ GetHIDevicePath ( NonHIDevicePathNodeCount = 0; HIDevicePath = AllocateZeroPool (sizeof (EFI_DEVICE_PATH_PROTOCOL)); + if (HIDevicePath == NULL) { + return NULL; + } + SetDevicePathEndNode (HIDevicePath); Node.DevPath.Type = END_DEVICE_PATH_TYPE; diff --git a/ShellPkg/Library/UefiShellCommandLib/UefiShellCommandLib.c b/ShellPkg/Library/UefiShellCommandLib/UefiShellCommandLib.c index 75fbd50cbe51..b0c77e4e802f 100644 --- a/ShellPkg/Library/UefiShellCommandLib/UefiShellCommandLib.c +++ b/ShellPkg/Library/UefiShellCommandLib/UefiShellCommandLib.c @@ -1142,7 +1142,7 @@ DeleteScriptFileStruct ( IN SCRIPT_FILE *Script ) { - UINT8 LoopVar; + UINTN LoopVar; if (Script == NULL) { return; @@ -1263,6 +1263,10 @@ ShellCommandCreateNewMappingName ( String = NULL; String = AllocateZeroPool (PcdGet8 (PcdShellMapNameLength) * sizeof (String[0])); + if (String == NULL) { + return (NULL); + } + UnicodeSPrint ( String, PcdGet8 (PcdShellMapNameLength) * sizeof (String[0]), @@ -1459,29 +1463,39 @@ ShellCommandCreateInitialMappingsAndPaths ( // PerformQuickSort (DevicePathList, Count, sizeof (EFI_DEVICE_PATH_PROTOCOL *), DevicePathCompare); - if (!EFI_ERROR (ShellCommandConsistMappingInitialize (&ConsistMappingTable))) { + Status = ShellCommandConsistMappingInitialize (&ConsistMappingTable); + if (EFI_ERROR (Status)) { + SHELL_FREE_NON_NULL (HandleList); + SHELL_FREE_NON_NULL (DevicePathList); + return Status; + } + + // + // Assign new Mappings to all... + // + for (Count = 0; HandleList[Count] != NULL; Count++) { // - // Assign new Mappings to all... + // Get default name first // - for (Count = 0; HandleList[Count] != NULL; Count++) { - // - // Get default name first - // - NewDefaultName = ShellCommandCreateNewMappingName (MappingTypeFileSystem); + NewDefaultName = ShellCommandCreateNewMappingName (MappingTypeFileSystem); + if (NewDefaultName == NULL) { ASSERT (NewDefaultName != NULL); - Status = ShellCommandAddMapItemAndUpdatePath (NewDefaultName, DevicePathList[Count], 0, TRUE); - ASSERT_EFI_ERROR (Status); - FreePool (NewDefaultName); + Status = EFI_OUT_OF_RESOURCES; + break; + } - // - // Now do consistent name - // - NewConsistName = ShellCommandConsistMappingGenMappingName (DevicePathList[Count], ConsistMappingTable); - if (NewConsistName != NULL) { - Status = ShellCommandAddMapItemAndUpdatePath (NewConsistName, DevicePathList[Count], 0, FALSE); - ASSERT_EFI_ERROR (Status); - FreePool (NewConsistName); - } + Status = ShellCommandAddMapItemAndUpdatePath (NewDefaultName, DevicePathList[Count], 0, TRUE); + ASSERT_EFI_ERROR (Status); + FreePool (NewDefaultName); + + // + // Now do consistent name + // + NewConsistName = ShellCommandConsistMappingGenMappingName (DevicePathList[Count], ConsistMappingTable); + if (NewConsistName != NULL) { + Status = ShellCommandAddMapItemAndUpdatePath (NewConsistName, DevicePathList[Count], 0, FALSE); + ASSERT_EFI_ERROR (Status); + FreePool (NewConsistName); } } @@ -1561,7 +1575,13 @@ ShellCommandCreateInitialMappingsAndPaths ( // Get default name first // NewDefaultName = ShellCommandCreateNewMappingName (MappingTypeBlockIo); - ASSERT (NewDefaultName != NULL); + if (NewDefaultName == NULL) { + ASSERT (NewDefaultName != NULL); + SHELL_FREE_NON_NULL (HandleList); + SHELL_FREE_NON_NULL (DevicePathList); + return EFI_OUT_OF_RESOURCES; + } + Status = ShellCommandAddMapItemAndUpdatePath (NewDefaultName, DevicePathList[Count], 0, FALSE); ASSERT_EFI_ERROR (Status); FreePool (NewDefaultName); @@ -1631,6 +1651,11 @@ ShellCommandUpdateMapping ( PerformQuickSort (DevicePathList, Count, sizeof (EFI_DEVICE_PATH_PROTOCOL *), DevicePathCompare); Status = ShellCommandConsistMappingInitialize (&ConsistMappingTable); + if (EFI_ERROR (Status)) { + SHELL_FREE_NON_NULL (HandleList); + SHELL_FREE_NON_NULL (DevicePathList); + return Status; + } // // Assign new Mappings to remainders diff --git a/ShellPkg/Library/UefiShellDebug1CommandsLib/Comp.c b/ShellPkg/Library/UefiShellDebug1CommandsLib/Comp.c index e94236d0b9ef..26d6653d996b 100644 --- a/ShellPkg/Library/UefiShellDebug1CommandsLib/Comp.c +++ b/ShellPkg/Library/UefiShellDebug1CommandsLib/Comp.c @@ -280,7 +280,13 @@ ShellCommandRunComp ( ShellStatus = SHELL_INVALID_PARAMETER; } else { TempParam = ShellCommandLineGetRawValue (Package, 1); - ASSERT (TempParam != NULL); + if (TempParam == NULL) { + ASSERT (TempParam != NULL); + ShellPrintHiiEx (-1, -1, NULL, STRING_TOKEN (STR_GEN_PARAM_INV), gShellDebug1HiiHandle, L"comp", TempParam); + ShellStatus = SHELL_INVALID_PARAMETER; + goto Exit; + } + FileName1 = ShellFindFilePath (TempParam); if (FileName1 == NULL) { ShellPrintHiiEx (-1, -1, NULL, STRING_TOKEN (STR_FILE_FIND_FAIL), gShellDebug1HiiHandle, L"comp", TempParam); @@ -294,7 +300,13 @@ ShellCommandRunComp ( } TempParam = ShellCommandLineGetRawValue (Package, 2); - ASSERT (TempParam != NULL); + if (TempParam == NULL) { + ASSERT (TempParam != NULL); + ShellPrintHiiEx (-1, -1, NULL, STRING_TOKEN (STR_GEN_PARAM_INV), gShellDebug1HiiHandle, L"comp", TempParam); + ShellStatus = SHELL_INVALID_PARAMETER; + goto Exit; + } + FileName2 = ShellFindFilePath (TempParam); if (FileName2 == NULL) { ShellPrintHiiEx (-1, -1, NULL, STRING_TOKEN (STR_FILE_FIND_FAIL), gShellDebug1HiiHandle, L"comp", TempParam); @@ -367,7 +379,7 @@ ShellCommandRunComp ( } if (ShellStatus == SHELL_SUCCESS) { - while (DiffPointNumber < DifferentCount) { + while ((UINT64)DiffPointNumber < DifferentCount) { DataSizeFromFile1 = 1; DataSizeFromFile2 = 1; OneByteFromFile1 = 0; @@ -499,6 +511,7 @@ ShellCommandRunComp ( ShellCommandLineFreeVarList (Package); } +Exit: SHELL_FREE_NON_NULL (FileName1); SHELL_FREE_NON_NULL (FileName2); diff --git a/ShellPkg/Library/UefiShellDebug1CommandsLib/Dblk.c b/ShellPkg/Library/UefiShellDebug1CommandsLib/Dblk.c index 5329b559ba46..a9aa483e4ce0 100644 --- a/ShellPkg/Library/UefiShellDebug1CommandsLib/Dblk.c +++ b/ShellPkg/Library/UefiShellDebug1CommandsLib/Dblk.c @@ -111,6 +111,8 @@ ShellCommandRunDblk ( UINT64 BlockCount; EFI_DEVICE_PATH_PROTOCOL *DevPath; + Lba = 0; + BlockCount = 0; ShellStatus = SHELL_SUCCESS; Status = EFI_SUCCESS; @@ -186,7 +188,7 @@ ShellCommandRunDblk ( // // do the work if we have a valid block identifier // - if (gEfiShellProtocol->GetDevicePathFromMap (BlockName) == NULL) { + if ((BlockName == NULL) || (gEfiShellProtocol->GetDevicePathFromMap (BlockName) == NULL)) { ShellPrintHiiEx (-1, -1, NULL, STRING_TOKEN (STR_GEN_PARAM_INV), gShellDebug1HiiHandle, L"dblk", BlockName); ShellStatus = SHELL_INVALID_PARAMETER; } else { diff --git a/ShellPkg/Library/UefiShellDebug1CommandsLib/DmpStore.c b/ShellPkg/Library/UefiShellDebug1CommandsLib/DmpStore.c index 975db0a62049..b81099c7345a 100644 --- a/ShellPkg/Library/UefiShellDebug1CommandsLib/DmpStore.c +++ b/ShellPkg/Library/UefiShellDebug1CommandsLib/DmpStore.c @@ -448,7 +448,11 @@ CascadeProcessVariables ( StrnCatGrow (&FoundVarName, &NameSize, PrevName, 0); } else { FoundVarName = AllocateZeroPool (sizeof (CHAR16)); - NameSize = sizeof (CHAR16); + if (FoundVarName == NULL) { + return (SHELL_OUT_OF_RESOURCES); + } + + NameSize = sizeof (CHAR16); } Status = gRT->GetNextVariableName (&NameSize, FoundVarName, &FoundVarGuid); diff --git a/ShellPkg/Library/UefiShellDebug1CommandsLib/Edit/Edit.c b/ShellPkg/Library/UefiShellDebug1CommandsLib/Edit/Edit.c index f5edc1bdbb49..144007a3d349 100644 --- a/ShellPkg/Library/UefiShellDebug1CommandsLib/Edit/Edit.c +++ b/ShellPkg/Library/UefiShellDebug1CommandsLib/Edit/Edit.c @@ -101,8 +101,14 @@ ShellCommandRunEdit ( // if (ShellCommandLineGetCount (Package) == 2) { TempParam = ShellCommandLineGetRawValue (Package, 1); - ASSERT (TempParam != NULL); - FileBufferSetFileName (TempParam); + if (TempParam == NULL) { + ASSERT (TempParam != NULL); + ShellPrintHiiEx (-1, -1, NULL, STRING_TOKEN (STR_GEN_PARAM_INV), gShellDebug1HiiHandle, L"edit"); + ShellStatus = SHELL_INVALID_PARAMETER; + } else { + FileBufferSetFileName (TempParam); + } + // if (EFI_ERROR(ShellFileExists(MainEditor.FileBuffer->FileName))) { // Status = ShellOpenFileByName(MainEditor.FileBuffer->FileName, &TempHandle, EFI_FILE_MODE_CREATE|EFI_FILE_MODE_READ|EFI_FILE_MODE_WRITE, 0); // if (!EFI_ERROR(Status)) { diff --git a/ShellPkg/Library/UefiShellDebug1CommandsLib/Edit/MainTextEditor.c b/ShellPkg/Library/UefiShellDebug1CommandsLib/Edit/MainTextEditor.c index 58beaaf9c57a..f3ea38438d84 100644 --- a/ShellPkg/Library/UefiShellDebug1CommandsLib/Edit/MainTextEditor.c +++ b/ShellPkg/Library/UefiShellDebug1CommandsLib/Edit/MainTextEditor.c @@ -1378,7 +1378,9 @@ MainCommandDisplayHelp ( // for (CurrentLine = 0; 0 != MainMenuHelpInfo[CurrentLine]; CurrentLine++) { InfoString = HiiGetString (gShellDebug1HiiHandle, MainMenuHelpInfo[CurrentLine], NULL); - ShellPrintEx (0, CurrentLine+1, L"%E%s%N", InfoString); + if (InfoString != NULL) { + ShellPrintEx (0, CurrentLine+1, L"%E%s%N", InfoString); + } } // diff --git a/ShellPkg/Library/UefiShellDebug1CommandsLib/EditMenuBar.c b/ShellPkg/Library/UefiShellDebug1CommandsLib/EditMenuBar.c index 3284f0c1e214..c9eace1ac96e 100644 --- a/ShellPkg/Library/UefiShellDebug1CommandsLib/EditMenuBar.c +++ b/ShellPkg/Library/UefiShellDebug1CommandsLib/EditMenuBar.c @@ -107,6 +107,9 @@ MenuBarRefresh ( // for (Item = MenuItems; Item != NULL && Item->Function != NULL; Item++) { NameString = HiiGetString (gShellDebug1HiiHandle, Item->NameToken, NULL); + if (NameString == NULL) { + return EFI_INVALID_PARAMETER; + } Width = MAX ((StrLen (NameString) + 6), 20); if (((Col + Width) > LastCol)) { @@ -115,6 +118,10 @@ MenuBarRefresh ( } FunctionKeyString = HiiGetString (gShellDebug1HiiHandle, Item->FunctionKeyToken, NULL); + if (FunctionKeyString == NULL) { + FreePool (NameString); + return EFI_INVALID_PARAMETER; + } ShellPrintEx ((INT32)(Col) - 1, (INT32)(Row) - 1, L"%E%s%N %H%s%N ", FunctionKeyString, NameString); diff --git a/ShellPkg/Library/UefiShellDebug1CommandsLib/EfiCompress.c b/ShellPkg/Library/UefiShellDebug1CommandsLib/EfiCompress.c index d581a334f469..ea190d0770f7 100644 --- a/ShellPkg/Library/UefiShellDebug1CommandsLib/EfiCompress.c +++ b/ShellPkg/Library/UefiShellDebug1CommandsLib/EfiCompress.c @@ -48,6 +48,7 @@ ShellCommandRunEfiCompress ( InShellFileHandle = NULL; OutShellFileHandle = NULL; InBuffer = NULL; + Package = NULL; // // initialize the shell lib (we must be in non-auto-init...) @@ -79,10 +80,16 @@ ShellCommandRunEfiCompress ( ShellStatus = SHELL_INVALID_PARAMETER; } else { TempParam = ShellCommandLineGetRawValue (Package, 1); - ASSERT (TempParam != NULL); + if (TempParam == NULL) { + ASSERT (TempParam != NULL); + ShellPrintHiiEx (-1, -1, NULL, STRING_TOKEN (STR_GEN_PARAM_INV), gShellDebug1HiiHandle, L"eficompress"); + ShellStatus = SHELL_INVALID_PARAMETER; + goto Exit; + } + InFileName = ShellFindFilePath (TempParam); OutFileName = ShellCommandLineGetRawValue (Package, 2); - if (InFileName == NULL) { + if ((InFileName == NULL) || (OutFileName == NULL)) { ShellPrintHiiEx (-1, -1, NULL, STRING_TOKEN (STR_FILE_FIND_FAIL), gShellDebug1HiiHandle, L"eficompress", TempParam); ShellStatus = SHELL_NOT_FOUND; } else { @@ -150,6 +157,11 @@ ShellCommandRunEfiCompress ( ShellCommandLineFreeVarList (Package); } +Exit: + if ((ShellStatus != SHELL_SUCCESS) && (Package != NULL)) { + ShellCommandLineFreeVarList (Package); + } + if (InShellFileHandle != NULL) { gEfiShellProtocol->CloseFile (InShellFileHandle); } diff --git a/ShellPkg/Library/UefiShellDebug1CommandsLib/EfiDecompress.c b/ShellPkg/Library/UefiShellDebug1CommandsLib/EfiDecompress.c index 72f8c087cb69..37f19a156aba 100644 --- a/ShellPkg/Library/UefiShellDebug1CommandsLib/EfiDecompress.c +++ b/ShellPkg/Library/UefiShellDebug1CommandsLib/EfiDecompress.c @@ -85,10 +85,16 @@ ShellCommandRunEfiDecompress ( ShellStatus = SHELL_INVALID_PARAMETER; } else { TempParam = ShellCommandLineGetRawValue (Package, 1); - ASSERT (TempParam != NULL); + if (TempParam == NULL) { + ASSERT (TempParam != NULL); + ShellPrintHiiEx (-1, -1, NULL, STRING_TOKEN (STR_GEN_PARAM_INV), gShellDebug1HiiHandle, L"efidecompress"); + ShellStatus = SHELL_INVALID_PARAMETER; + goto Done; + } + InFileName = ShellFindFilePath (TempParam); OutFileName = ShellCommandLineGetRawValue (Package, 2); - if (InFileName == NULL) { + if ((InFileName == NULL) || (OutFileName == NULL)) { ShellPrintHiiEx (-1, -1, NULL, STRING_TOKEN (STR_FILE_FIND_FAIL), gShellDebug1HiiHandle, L"efidecompress", TempParam); ShellStatus = SHELL_NOT_FOUND; } else { @@ -112,13 +118,25 @@ ShellCommandRunEfiDecompress ( if (ShellStatus == SHELL_SUCCESS) { Status = FileHandleGetSize (InFileHandle, &Temp64Bit); - ASSERT_EFI_ERROR (Status); - if (!EFI_ERROR (Status)) { - ASSERT (Temp64Bit <= (UINT32)(-1)); - InSize = (UINTN)Temp64Bit; - InBuffer = AllocateZeroPool (InSize); + if (EFI_ERROR (Status)) { + ShellPrintHiiEx (-1, -1, NULL, STRING_TOKEN (STR_GEN_FILE_OPEN_FAIL), gShellDebug1HiiHandle, L"efidecompress", ShellCommandLineGetRawValue (Package, 1)); + ShellStatus = SHELL_NOT_FOUND; + } + } + + if (ShellStatus == SHELL_SUCCESS) { + // + // Limit the File Size to UINT32, even though calls accept UINTN. + // 32 bits = 4gb. + // + Status = SafeUint64ToUint32 (Temp64Bit, (UINT32 *)&InSize); + if (EFI_ERROR (Status)) { + ASSERT_EFI_ERROR (Status); + ShellStatus = SHELL_BAD_BUFFER_SIZE; + goto Done; } + InBuffer = AllocateZeroPool (InSize); if (InBuffer == NULL) { Status = EFI_OUT_OF_RESOURCES; } else { @@ -166,6 +184,8 @@ ShellCommandRunEfiDecompress ( } } +Done: + ShellCommandLineFreeVarList (Package); } diff --git a/ShellPkg/Library/UefiShellDebug1CommandsLib/HexEdit/FileImage.c b/ShellPkg/Library/UefiShellDebug1CommandsLib/HexEdit/FileImage.c index d8818dd958c2..3b1824114959 100644 --- a/ShellPkg/Library/UefiShellDebug1CommandsLib/HexEdit/FileImage.c +++ b/ShellPkg/Library/UefiShellDebug1CommandsLib/HexEdit/FileImage.c @@ -371,6 +371,10 @@ HFileImageSave ( // set status string // Str = CatSPrint (NULL, L"%d Lines Written", NumLines); + if (Str == NULL) { + return EFI_OUT_OF_RESOURCES; + } + StatusBarSetStatusString (Str); FreePool (Str); diff --git a/ShellPkg/Library/UefiShellDebug1CommandsLib/HexEdit/MainHexEditor.c b/ShellPkg/Library/UefiShellDebug1CommandsLib/HexEdit/MainHexEditor.c index 0eb917acf73e..51e4ae2f8193 100644 --- a/ShellPkg/Library/UefiShellDebug1CommandsLib/HexEdit/MainHexEditor.c +++ b/ShellPkg/Library/UefiShellDebug1CommandsLib/HexEdit/MainHexEditor.c @@ -115,7 +115,11 @@ HMainCommandDisplayHelp ( , NULL ); - ShellPrintEx (0, CurrentLine+1, L"%E%s%N", InfoString); + if (InfoString != NULL) { + ShellPrintEx (0, CurrentLine+1, L"%E%s%N", InfoString); + } else { + ASSERT (FALSE); + } } // diff --git a/ShellPkg/Library/UefiShellDebug1CommandsLib/LoadPciRom.c b/ShellPkg/Library/UefiShellDebug1CommandsLib/LoadPciRom.c index 852d6dcf8087..40260ea3dc93 100644 --- a/ShellPkg/Library/UefiShellDebug1CommandsLib/LoadPciRom.c +++ b/ShellPkg/Library/UefiShellDebug1CommandsLib/LoadPciRom.c @@ -302,6 +302,11 @@ LoadEfiDriversFromRomImage ( ); if (!EFI_ERROR (Status)) { DecompressedImageBuffer = AllocateZeroPool (DestinationSize); + if (DecompressedImageBuffer == NULL) { + ShellPrintHiiEx (-1, -1, NULL, STRING_TOKEN (STR_GEN_OUT_MEM), gShellDebug1HiiHandle, L"loadpcirom"); + return EFI_OUT_OF_RESOURCES; + } + if (ImageBuffer != NULL) { Scratch = AllocateZeroPool (ScratchSize); if (Scratch != NULL) { @@ -333,6 +338,11 @@ LoadEfiDriversFromRomImage ( // UnicodeSPrint (RomFileName, sizeof (RomFileName), L"%s[%d]", FileName, ImageIndex); FilePath = FileDevicePath (NULL, RomFileName); + if (FilePath == NULL) { + ShellPrintHiiEx (-1, -1, NULL, STRING_TOKEN (STR_LOADPCIROM_LOAD_FAIL), gShellDebug1HiiHandle, L"loadpcirom", FileName, ImageIndex); + SHELL_FREE_NON_NULL (DecompressedImageBuffer); + return EFI_OUT_OF_RESOURCES; + } Status = gBS->LoadImage ( TRUE, diff --git a/ShellPkg/Library/UefiShellDebug1CommandsLib/MemMap.c b/ShellPkg/Library/UefiShellDebug1CommandsLib/MemMap.c index a089953b286f..3f4cada2b7d6 100644 --- a/ShellPkg/Library/UefiShellDebug1CommandsLib/MemMap.c +++ b/ShellPkg/Library/UefiShellDebug1CommandsLib/MemMap.c @@ -214,7 +214,13 @@ ShellCommandRunMemMap ( if (Status == EFI_BUFFER_TOO_SMALL) { Size += SIZE_1KB; Descriptors = AllocateZeroPool (Size); - Status = gBS->GetMemoryMap (&Size, Descriptors, &MapKey, &ItemSize, &Version); + if (Descriptors == NULL) { + ShellPrintHiiEx (-1, -1, NULL, STRING_TOKEN (STR_GEN_OUT_MEM), gShellDebug1HiiHandle, L"memmap"); + ShellCommandLineFreeVarList (Package); + return SHELL_OUT_OF_RESOURCES; + } + + Status = gBS->GetMemoryMap (&Size, Descriptors, &MapKey, &ItemSize, &Version); } if (EFI_ERROR (Status)) { diff --git a/ShellPkg/Library/UefiShellDebug1CommandsLib/Mm.c b/ShellPkg/Library/UefiShellDebug1CommandsLib/Mm.c index b75e2f477080..cff2c9daee38 100644 --- a/ShellPkg/Library/UefiShellDebug1CommandsLib/Mm.c +++ b/ShellPkg/Library/UefiShellDebug1CommandsLib/Mm.c @@ -537,7 +537,13 @@ ShellCommandRunMm ( goto Done; } - Temp = ShellCommandLineGetRawValue (Package, 1); + Temp = ShellCommandLineGetRawValue (Package, 1); + if (Temp == NULL) { + ShellPrintHiiEx (-1, -1, NULL, STRING_TOKEN (STR_GEN_PROBLEM), gShellDebug1HiiHandle, L"mm", L"NULL"); + ShellStatus = SHELL_INVALID_PARAMETER; + goto Done; + } + Status = ShellConvertStringToUint64 (Temp, &Address, TRUE, FALSE); if (EFI_ERROR (Status)) { ShellPrintHiiEx (-1, -1, NULL, STRING_TOKEN (STR_GEN_PARAM_INV), gShellDebug1HiiHandle, L"mm", Temp); diff --git a/ShellPkg/Library/UefiShellDebug1CommandsLib/Mode.c b/ShellPkg/Library/UefiShellDebug1CommandsLib/Mode.c index d907ddd4152f..c0e288632d91 100644 --- a/ShellPkg/Library/UefiShellDebug1CommandsLib/Mode.c +++ b/ShellPkg/Library/UefiShellDebug1CommandsLib/Mode.c @@ -67,14 +67,20 @@ ShellCommandRunMode ( ShellStatus = SHELL_INVALID_PARAMETER; } else if (ShellCommandLineGetCount (Package) == 3) { Temp = ShellCommandLineGetRawValue (Package, 1); - if (!ShellIsHexOrDecimalNumber (Temp, FALSE, FALSE)) { + if (Temp == NULL) { + ShellPrintHiiEx (-1, -1, NULL, STRING_TOKEN (STR_GEN_PARAM_INV), gShellDebug1HiiHandle, L"mode", Temp); + ShellStatus = SHELL_INVALID_PARAMETER; + } else if (!ShellIsHexOrDecimalNumber (Temp, FALSE, FALSE)) { ShellPrintHiiEx (-1, -1, NULL, STRING_TOKEN (STR_GEN_PARAM_INV), gShellDebug1HiiHandle, L"mode", Temp); ShellStatus = SHELL_INVALID_PARAMETER; } NewCol = ShellStrToUintn (Temp); Temp = ShellCommandLineGetRawValue (Package, 2); - if (!ShellIsHexOrDecimalNumber (Temp, FALSE, FALSE)) { + if (Temp == NULL) { + ShellPrintHiiEx (-1, -1, NULL, STRING_TOKEN (STR_GEN_PARAM_INV), gShellDebug1HiiHandle, L"mode", Temp); + ShellStatus = SHELL_INVALID_PARAMETER; + } else if (!ShellIsHexOrDecimalNumber (Temp, FALSE, FALSE)) { ShellPrintHiiEx (-1, -1, NULL, STRING_TOKEN (STR_GEN_PARAM_INV), gShellDebug1HiiHandle, L"mode", Temp); ShellStatus = SHELL_INVALID_PARAMETER; } diff --git a/ShellPkg/Library/UefiShellDebug1CommandsLib/Pci.c b/ShellPkg/Library/UefiShellDebug1CommandsLib/Pci.c index 93622733a5c1..ff5c44527aed 100644 --- a/ShellPkg/Library/UefiShellDebug1CommandsLib/Pci.c +++ b/ShellPkg/Library/UefiShellDebug1CommandsLib/Pci.c @@ -5765,7 +5765,7 @@ PrintInterpretedExtendedCompatibilityDynamicPowerAllocation ( ) { CONST PCI_EXPRESS_EXTENDED_CAPABILITIES_DYNAMIC_POWER_ALLOCATION *Header; - UINT8 LinkCount; + UINT32 LinkCount; Header = (PCI_EXPRESS_EXTENDED_CAPABILITIES_DYNAMIC_POWER_ALLOCATION *)HeaderAddress; @@ -5780,7 +5780,7 @@ PrintInterpretedExtendedCompatibilityDynamicPowerAllocation ( Header->DpaStatus, Header->DpaControl ); - for (LinkCount = 0; LinkCount < PCI_EXPRESS_EXTENDED_CAPABILITY_DYNAMIC_POWER_ALLOCATION_GET_SUBSTATE_MAX (Header) + 1; LinkCount++) { + for (LinkCount = 0; LinkCount < PCI_EXPRESS_EXTENDED_CAPABILITY_DYNAMIC_POWER_ALLOCATION_GET_SUBSTATE_MAX (Header) + (UINT32)1; LinkCount++) { ShellPrintHiiEx ( -1, -1, diff --git a/ShellPkg/Library/UefiShellDebug1CommandsLib/SerMode.c b/ShellPkg/Library/UefiShellDebug1CommandsLib/SerMode.c index 99cc44894295..a33343dc7250 100644 --- a/ShellPkg/Library/UefiShellDebug1CommandsLib/SerMode.c +++ b/ShellPkg/Library/UefiShellDebug1CommandsLib/SerMode.c @@ -288,7 +288,13 @@ ShellCommandRunSerMode ( goto Done; } - Temp = ShellCommandLineGetRawValue (Package, 5); + Temp = ShellCommandLineGetRawValue (Package, 5); + if (Temp == NULL) { + ShellPrintHiiEx (-1, -1, NULL, STRING_TOKEN (STR_GEN_PARAM_INV), gShellDebug1HiiHandle, L"sermode"); + ShellStatus = SHELL_INVALID_PARAMETER; + goto Done; + } + Value = ShellStrToUintn (Temp); switch (Value) { case 0: diff --git a/ShellPkg/Library/UefiShellDebug1CommandsLib/SetSize.c b/ShellPkg/Library/UefiShellDebug1CommandsLib/SetSize.c index e5bacde638a3..79c3aaafc419 100644 --- a/ShellPkg/Library/UefiShellDebug1CommandsLib/SetSize.c +++ b/ShellPkg/Library/UefiShellDebug1CommandsLib/SetSize.c @@ -62,7 +62,11 @@ ShellCommandRunSetSize ( NewSize = 0; } else { Temp1 = ShellCommandLineGetRawValue (Package, 1); - if (!ShellIsHexOrDecimalNumber (Temp1, FALSE, FALSE)) { + if (Temp1 == NULL) { + ShellPrintHiiEx (-1, -1, NULL, STRING_TOKEN (STR_GEN_PARAM_INV), gShellDebug1HiiHandle, L"setsize"); + ShellStatus = SHELL_INVALID_PARAMETER; + NewSize = 0; + } else if (!ShellIsHexOrDecimalNumber (Temp1, FALSE, FALSE)) { ShellPrintHiiEx (-1, -1, NULL, STRING_TOKEN (STR_SIZE_NOT_SPEC), gShellDebug1HiiHandle, L"setsize"); ShellStatus = SHELL_INVALID_PARAMETER; NewSize = 0; diff --git a/ShellPkg/Library/UefiShellDebug1CommandsLib/SetVar.c b/ShellPkg/Library/UefiShellDebug1CommandsLib/SetVar.c index 61788d199365..9f8dee2bbe02 100644 --- a/ShellPkg/Library/UefiShellDebug1CommandsLib/SetVar.c +++ b/ShellPkg/Library/UefiShellDebug1CommandsLib/SetVar.c @@ -285,7 +285,10 @@ GetVariableDataFromParameter ( for (Index = 2; Index < ShellCommandLineGetCount (Package); Index++) { TempData = ShellCommandLineGetRawValue (Package, Index); - ASSERT (TempData != NULL); + if (TempData == NULL) { + ASSERT (TempData != NULL); + return EFI_INVALID_PARAMETER; + } if (TempData[0] != L'=') { ShellPrintHiiEx (-1, -1, NULL, STRING_TOKEN (STR_GEN_PARAM_INV), gShellDebug1HiiHandle, L"setvar", TempData); @@ -401,11 +404,23 @@ ShellCommandRunSetVar ( ShellStatus = SHELL_INVALID_PARAMETER; } else { VariableName = ShellCommandLineGetRawValue (Package, 1); + if (VariableName == NULL) { + ShellCommandLineFreeVarList (Package); + return SHELL_INVALID_PARAMETER; + } + if (!ShellCommandLineGetFlag (Package, L"-guid")) { CopyGuid (&Guid, &gEfiGlobalVariableGuid); } else { StringGuid = ShellCommandLineGetValue (Package, L"-guid"); - RStatus = StrToGuid (StringGuid, &Guid); + if (StringGuid != NULL) { + RStatus = StrToGuid (StringGuid, &Guid); + } else { + ShellPrintHiiEx (-1, -1, NULL, STRING_TOKEN (STR_GEN_PARAM_INV), gShellDebug1HiiHandle, L"setvar", StringGuid); + ShellCommandLineFreeVarList (Package); + return SHELL_INVALID_PARAMETER; + } + if (RETURN_ERROR (RStatus) || (StringGuid[GUID_STRING_LENGTH] != L'\0')) { ShellPrintHiiEx (-1, -1, NULL, STRING_TOKEN (STR_GEN_PARAM_INV), gShellDebug1HiiHandle, L"setvar", StringGuid); ShellStatus = SHELL_INVALID_PARAMETER; @@ -419,6 +434,12 @@ ShellCommandRunSetVar ( Status = gRT->GetVariable ((CHAR16 *)VariableName, &Guid, &Attributes, &Size, Buffer); if (Status == EFI_BUFFER_TOO_SMALL) { Buffer = AllocateZeroPool (Size); + if (Buffer == NULL) { + ShellPrintHiiEx (-1, -1, NULL, STRING_TOKEN (STR_GEN_OUT_MEM), gShellDebug1HiiHandle, L"setvar"); + ShellCommandLineFreeVarList (Package); + return SHELL_OUT_OF_RESOURCES; + } + Status = gRT->GetVariable ((CHAR16 *)VariableName, &Guid, &Attributes, &Size, Buffer); } @@ -440,6 +461,12 @@ ShellCommandRunSetVar ( Status = gRT->GetVariable ((CHAR16 *)VariableName, &Guid, &Attributes, &Size, Buffer); if (Status == EFI_BUFFER_TOO_SMALL) { Buffer = AllocateZeroPool (Size); + if (Buffer == NULL) { + ShellPrintHiiEx (-1, -1, NULL, STRING_TOKEN (STR_GEN_OUT_MEM), gShellDebug1HiiHandle, L"setvar"); + ShellCommandLineFreeVarList (Package); + return SHELL_OUT_OF_RESOURCES; + } + Status = gRT->GetVariable ((CHAR16 *)VariableName, &Guid, &Attributes, &Size, Buffer); } diff --git a/ShellPkg/Library/UefiShellDebug1CommandsLib/SmbiosView/PrintInfo.c b/ShellPkg/Library/UefiShellDebug1CommandsLib/SmbiosView/PrintInfo.c index 2ee2bb44bce0..54e08874e3df 100644 --- a/ShellPkg/Library/UefiShellDebug1CommandsLib/SmbiosView/PrintInfo.c +++ b/ShellPkg/Library/UefiShellDebug1CommandsLib/SmbiosView/PrintInfo.c @@ -520,11 +520,11 @@ SmbiosPrintStructure ( ShellPrintEx (-1, -1, L"Thread Count 2: %u\n", Struct->Type4->ThreadCount2); } - if (AE_SMBIOS_VERSION (0x3, 0x6) && (Struct->Hdr->Length > 0x2E)) { + if (AE_SMBIOS_VERSION (0x3, 0x6) && (Struct->Hdr->Length > 0x30)) { ShellPrintEx (-1, -1, L"Thread Enabled: %u\n", Struct->Type4->ThreadEnabled); } - if (AE_SMBIOS_VERSION (0x3, 0x8) && (Struct->Hdr->Length > 0x30)) { + if (AE_SMBIOS_VERSION (0x3, 0x8) && (Struct->Hdr->Length > 0x32)) { ShellPrintEx (-1, -1, L"Socket Type: %a\n", LibGetSmbiosString (Struct, Struct->Type4->SocketType)); } @@ -676,7 +676,7 @@ SmbiosPrintStructure ( { UINTN NumOfDevice; NumOfDevice = (Struct->Type10->Hdr.Length - sizeof (SMBIOS_STRUCTURE)) / (2 * sizeof (UINT8)); - for (Index = 0; Index < NumOfDevice; Index++) { + for (Index = 0; (UINTN)Index < NumOfDevice; Index++) { ShellPrintEx (-1, -1, (((Struct->Type10->Device[Index].DeviceType) & 0x80) != 0) ? L"Device Enabled\n" : L"Device Disabled\n"); DisplayOnboardDeviceTypes ((Struct->Type10->Device[Index].DeviceType) & 0x7F, Option); ShellPrintHiiEx (-1, -1, NULL, STRING_TOKEN (STR_SMBIOSVIEW_PRINTINFO_DESC_STRING), gShellDebug1HiiHandle); @@ -2423,6 +2423,10 @@ DisplayProcessorFamily ( Print (L"Intel Core i9 processor\n"); break; + case 0xD0: + Print (L"Intel Xeon D Processor\n"); + break; + case 0xD2: Print (L"ViaC7M\n"); break; diff --git a/ShellPkg/Library/UefiShellDebug1CommandsLib/SmbiosView/SmbiosView.c b/ShellPkg/Library/UefiShellDebug1CommandsLib/SmbiosView/SmbiosView.c index 7e7eef3fd8ca..982e20ead4bf 100644 --- a/ShellPkg/Library/UefiShellDebug1CommandsLib/SmbiosView/SmbiosView.c +++ b/ShellPkg/Library/UefiShellDebug1CommandsLib/SmbiosView/SmbiosView.c @@ -790,7 +790,7 @@ InitSmbios64BitTableStatistics ( // Handle = INVALID_HANDLE; LibGetSmbios64BitStructure (&Handle, NULL, NULL); - for (Index = 1; Index <= mNumberOfSmbios64BitStructures; Index++) { + for (Index = 1; (UINTN)Index <= mNumberOfSmbios64BitStructures; Index++) { // // If reach the end of table, break.. // diff --git a/ShellPkg/Library/UefiShellDebug1CommandsLib/UefiShellDebug1CommandsLib.c b/ShellPkg/Library/UefiShellDebug1CommandsLib/UefiShellDebug1CommandsLib.c index a1a055928f3f..d61a61e734fe 100644 --- a/ShellPkg/Library/UefiShellDebug1CommandsLib/UefiShellDebug1CommandsLib.c +++ b/ShellPkg/Library/UefiShellDebug1CommandsLib/UefiShellDebug1CommandsLib.c @@ -269,6 +269,10 @@ EditGetDefaultFileName ( do { FileNameTmp = CatSPrint (NULL, L"NewFile%d.%s", Suffix, Extension); + if (FileNameTmp == NULL) { + ASSERT (FileNameTmp != NULL); + return NULL; + } // // after that filename changed to path diff --git a/ShellPkg/Library/UefiShellDebug1CommandsLib/UefiShellDebug1CommandsLib.h b/ShellPkg/Library/UefiShellDebug1CommandsLib/UefiShellDebug1CommandsLib.h index e738b3449014..35768dba00d8 100644 --- a/ShellPkg/Library/UefiShellDebug1CommandsLib/UefiShellDebug1CommandsLib.h +++ b/ShellPkg/Library/UefiShellDebug1CommandsLib/UefiShellDebug1CommandsLib.h @@ -50,6 +50,7 @@ #include #include #include +#include extern EFI_HII_HANDLE gShellDebug1HiiHandle; diff --git a/ShellPkg/Library/UefiShellDebug1CommandsLib/UefiShellDebug1CommandsLib.inf b/ShellPkg/Library/UefiShellDebug1CommandsLib/UefiShellDebug1CommandsLib.inf index 140e9dc64418..91b48e81f9c1 100644 --- a/ShellPkg/Library/UefiShellDebug1CommandsLib/UefiShellDebug1CommandsLib.inf +++ b/ShellPkg/Library/UefiShellDebug1CommandsLib/UefiShellDebug1CommandsLib.inf @@ -111,6 +111,7 @@ SortLib PrintLib BcfgCommandLib + SafeIntLib [Pcd] gEfiShellPkgTokenSpaceGuid.PcdShellFileOperationSize ## CONSUMES diff --git a/ShellPkg/Library/UefiShellDriver1CommandsLib/Connect.c b/ShellPkg/Library/UefiShellDriver1CommandsLib/Connect.c index 870c5b0d1da7..4f398632fb6c 100644 --- a/ShellPkg/Library/UefiShellDriver1CommandsLib/Connect.c +++ b/ShellPkg/Library/UefiShellDriver1CommandsLib/Connect.c @@ -509,9 +509,18 @@ ShellCommandRunConnect ( if (Param1 != NULL) { Status = ShellConvertStringToUint64 (Param1, &Intermediate, TRUE, FALSE); - if (!EFI_ERROR (Status)) { - Handle1 = ConvertHandleIndexToHandle ((UINTN)Intermediate); - } else { + if (EFI_ERROR (Status)) { + ShellPrintHiiEx (-1, -1, NULL, STRING_TOKEN (STR_GEN_INV_HANDLE), gShellDriver1HiiHandle, L"connect", Param1); + ShellStatus = SHELL_INVALID_PARAMETER; + if (Package != NULL) { + ShellCommandLineFreeVarList (Package); + } + + return (ShellStatus); + } + + Handle1 = ConvertHandleIndexToHandle ((UINTN)Intermediate); + if (EFI_ERROR (Status)) { ShellPrintHiiEx (-1, -1, NULL, STRING_TOKEN (STR_GEN_INV_HANDLE), gShellDriver1HiiHandle, L"connect", Param1); ShellStatus = SHELL_INVALID_PARAMETER; } diff --git a/ShellPkg/Library/UefiShellDriver1CommandsLib/DevTree.c b/ShellPkg/Library/UefiShellDriver1CommandsLib/DevTree.c index ddf063713c94..3f14560fda2e 100644 --- a/ShellPkg/Library/UefiShellDriver1CommandsLib/DevTree.c +++ b/ShellPkg/Library/UefiShellDriver1CommandsLib/DevTree.c @@ -195,6 +195,12 @@ ShellCommandRunDevTree ( Lang = ShellCommandLineGetValue (Package, L"-l"); if (Lang != NULL) { Language = AllocateZeroPool (StrSize (Lang)); + if (Language == NULL) { + ShellPrintHiiEx (-1, -1, NULL, STRING_TOKEN (STR_GEN_OUT_MEM), gShellDriver1HiiHandle, L"devtree"); + ShellCommandLineFreeVarList (Package); + return (SHELL_OUT_OF_RESOURCES); + } + AsciiSPrint (Language, StrSize (Lang), "%S", Lang); } else if (!ShellCommandLineGetFlag (Package, L"-l")) { ASSERT (Language == NULL); @@ -212,6 +218,13 @@ ShellCommandRunDevTree ( Lang = ShellCommandLineGetRawValue (Package, 1); HiiString = HiiGetString (gShellDriver1HiiHandle, STRING_TOKEN (STR_DEV_TREE_OUTPUT), Language); + if (HiiString == NULL) { + ASSERT (HiiString != NULL); + SHELL_FREE_NON_NULL (Language); + ShellCommandLineFreeVarList (Package); + return (SHELL_INVALID_PARAMETER); + } + if (Lang == NULL) { for (LoopVar = 1; ; LoopVar++) { TheHandle = ConvertHandleIndexToHandle (LoopVar); diff --git a/ShellPkg/Library/UefiShellDriver1CommandsLib/Devices.c b/ShellPkg/Library/UefiShellDriver1CommandsLib/Devices.c index e175cad192ca..0225b1a6d360 100644 --- a/ShellPkg/Library/UefiShellDriver1CommandsLib/Devices.c +++ b/ShellPkg/Library/UefiShellDriver1CommandsLib/Devices.c @@ -190,6 +190,12 @@ ShellCommandRunDevices ( Lang = ShellCommandLineGetValue (Package, L"-l"); if (Lang != NULL) { Language = AllocateZeroPool (StrSize (Lang)); + if (Language == NULL) { + ShellPrintHiiEx (-1, -1, NULL, STRING_TOKEN (STR_GEN_OUT_MEM), gShellDriver1HiiHandle, L"devices"); + ShellCommandLineFreeVarList (Package); + return (SHELL_OUT_OF_RESOURCES); + } + AsciiSPrint (Language, StrSize (Lang), "%S", Lang); } else if (!ShellCommandLineGetFlag (Package, L"-l")) { ASSERT (Language == NULL); diff --git a/ShellPkg/Library/UefiShellDriver1CommandsLib/Dh.c b/ShellPkg/Library/UefiShellDriver1CommandsLib/Dh.c index d17d50fe13fa..f8ddb51ab62d 100644 --- a/ShellPkg/Library/UefiShellDriver1CommandsLib/Dh.c +++ b/ShellPkg/Library/UefiShellDriver1CommandsLib/Dh.c @@ -218,7 +218,11 @@ GetDriverName ( return (EFI_NOT_FOUND); } - Lang = GetBestLanguageForDriver (CompName2->SupportedLanguages, Language, FALSE); + Lang = GetBestLanguageForDriver (CompName2->SupportedLanguages, Language, FALSE); + if (Lang == NULL) { + return (EFI_NOT_FOUND); + } + Status = CompName2->GetDriverName (CompName2, Lang, &NameToReturn); FreePool (Lang); @@ -1142,6 +1146,12 @@ ShellCommandRunDh ( Lang = ShellCommandLineGetValue (Package, L"-l"); if (Lang != NULL) { Language = AllocateZeroPool (StrSize (Lang)); + if (Language == NULL) { + ShellPrintHiiEx (-1, -1, NULL, STRING_TOKEN (STR_GEN_OUT_MEM), gShellDriver1HiiHandle, L"dh"); + ShellCommandLineFreeVarList (Package); + return (SHELL_OUT_OF_RESOURCES); + } + AsciiSPrint (Language, StrSize (Lang), "%S", Lang); } else { ASSERT (Language == NULL); @@ -1151,6 +1161,12 @@ ShellCommandRunDh ( } } else { Language = AllocateZeroPool (10); + if (Language == NULL) { + ShellPrintHiiEx (-1, -1, NULL, STRING_TOKEN (STR_GEN_OUT_MEM), gShellDriver1HiiHandle, L"dh"); + ShellCommandLineFreeVarList (Package); + return (SHELL_OUT_OF_RESOURCES); + } + AsciiSPrint (Language, 10, "en-us"); } diff --git a/ShellPkg/Library/UefiShellDriver1CommandsLib/Disconnect.c b/ShellPkg/Library/UefiShellDriver1CommandsLib/Disconnect.c index fac6463e3c28..0ff6a40c8c4d 100644 --- a/ShellPkg/Library/UefiShellDriver1CommandsLib/Disconnect.c +++ b/ShellPkg/Library/UefiShellDriver1CommandsLib/Disconnect.c @@ -98,7 +98,10 @@ ShellCommandRunDisconnect ( UINT64 Intermediate2; UINT64 Intermediate3; - ShellStatus = SHELL_SUCCESS; + Intermediate1 = 0; + Intermediate2 = 0; + Intermediate3 = 0; + ShellStatus = SHELL_SUCCESS; // // initialize the shell lib (we must be in non-auto-init...) diff --git a/ShellPkg/Library/UefiShellDriver1CommandsLib/Drivers.c b/ShellPkg/Library/UefiShellDriver1CommandsLib/Drivers.c index 2773039caac7..78484aebf6f1 100644 --- a/ShellPkg/Library/UefiShellDriver1CommandsLib/Drivers.c +++ b/ShellPkg/Library/UefiShellDriver1CommandsLib/Drivers.c @@ -327,6 +327,12 @@ ShellCommandRunDrivers ( Lang = ShellCommandLineGetValue (Package, L"-l"); if (Lang != NULL) { Language = AllocateZeroPool (StrSize (Lang)); + if (Language == NULL) { + ShellPrintHiiEx (-1, -1, NULL, STRING_TOKEN (STR_GEN_OUT_MEM), gShellDriver1HiiHandle, L"drivers"); + ShellCommandLineFreeVarList (Package); + return (SHELL_OUT_OF_RESOURCES); + } + AsciiSPrint (Language, StrSize (Lang), "%S", Lang); } else { ASSERT (Language == NULL); @@ -364,6 +370,13 @@ ShellCommandRunDrivers ( ); } + if (FormatString == NULL) { + // Assume the string is present because it is hard-coded and report out of memory + ShellPrintHiiEx (-1, -1, NULL, STRING_TOKEN (STR_GEN_OUT_MEM), gShellDriver1HiiHandle, L"drivers"); + ShellCommandLineFreeVarList (Package); + return (SHELL_OUT_OF_RESOURCES); + } + HandleList = GetHandleListByProtocol (&gEfiDriverBindingProtocolGuid); for (HandleWalker = HandleList; HandleWalker != NULL && *HandleWalker != NULL; HandleWalker++) { ChildCount = 0; @@ -382,6 +395,12 @@ ShellCommandRunDrivers ( TruncatedDriverName = NULL; if (!SfoFlag && (FullDriverName != NULL)) { TruncatedDriverName = AllocateZeroPool ((MAX_LEN_DRIVER_NAME + 1) * sizeof (CHAR16)); + if (TruncatedDriverName == NULL) { + ShellPrintHiiEx (-1, -1, NULL, STRING_TOKEN (STR_GEN_OUT_MEM), gShellDriver1HiiHandle, L"drivers"); + ShellCommandLineFreeVarList (Package); + return (SHELL_OUT_OF_RESOURCES); + } + StrnCpyS (TruncatedDriverName, MAX_LEN_DRIVER_NAME + 1, FullDriverName, MAX_LEN_DRIVER_NAME); } diff --git a/ShellPkg/Library/UefiShellDriver1CommandsLib/DrvCfg.c b/ShellPkg/Library/UefiShellDriver1CommandsLib/DrvCfg.c index 9bbbb1444dad..8b9f56972a36 100644 --- a/ShellPkg/Library/UefiShellDriver1CommandsLib/DrvCfg.c +++ b/ShellPkg/Library/UefiShellDriver1CommandsLib/DrvCfg.c @@ -236,7 +236,33 @@ ConfigToFile ( Status = HiiDatabase->ExportPackageLists (HiiDatabase, HiiHandle, &MainBufferSize, MainBuffer); if (Status == EFI_BUFFER_TOO_SMALL) { MainBuffer = AllocateZeroPool (MainBufferSize); - Status = HiiDatabase->ExportPackageLists (HiiDatabase, HiiHandle, &MainBufferSize, MainBuffer); + if (MainBuffer == NULL) { + ShellPrintHiiEx ( + -1, + -1, + NULL, + STRING_TOKEN (STR_GEN_OUT_MEM), + gShellDriver1HiiHandle, + L"drvcfg" + ); + ShellCloseFile (&FileHandle); + return (SHELL_OUT_OF_RESOURCES); + } + + Status = HiiDatabase->ExportPackageLists (HiiDatabase, HiiHandle, &MainBufferSize, MainBuffer); + if (EFI_ERROR (Status)) { + SHELL_FREE_NON_NULL (MainBuffer); + ShellPrintHiiEx ( + -1, + -1, + NULL, + STRING_TOKEN (STR_GEN_OUT_MEM), + gShellDriver1HiiHandle, + L"drvcfg" + ); + ShellCloseFile (&FileHandle); + return (SHELL_DEVICE_ERROR); + } } Status = ShellWriteFile (FileHandle, &MainBufferSize, MainBuffer); @@ -292,11 +318,13 @@ ConfigFromFile ( EFI_HII_PACKAGE_HEADER *PackageHeader; EFI_DEVICE_PATH_PROTOCOL *DevPath; UINTN HandleIndex; + SHELL_STATUS ShellStatus; HiiDatabase = NULL; MainBufferSize = 0; MainBuffer = NULL; FileHandle = NULL; + ShellStatus = SHELL_SUCCESS; Status = ShellOpenFileByName (FileName, &FileHandle, EFI_FILE_MODE_READ, 0); if (EFI_ERROR (Status)) { @@ -310,7 +338,9 @@ ConfigFromFile ( FileName, Status ); - return (SHELL_DEVICE_ERROR); + + ShellStatus = SHELL_DEVICE_ERROR; + goto Done; } // @@ -333,8 +363,9 @@ ConfigFromFile ( L"EfiHiiDatabaseProtocol", &gEfiHiiDatabaseProtocolGuid ); - ShellCloseFile (&FileHandle); - return (SHELL_NOT_FOUND); + + ShellStatus = SHELL_NOT_FOUND; + goto Done; } Status = ShellGetFileSize (FileHandle, &Temp); @@ -350,11 +381,25 @@ ConfigFromFile ( FileName ); - ShellCloseFile (&FileHandle); - return (SHELL_DEVICE_ERROR); + ShellStatus = SHELL_DEVICE_ERROR; + goto Done; } MainBuffer = AllocateZeroPool ((UINTN)MainBufferSize); + if (MainBuffer == NULL) { + ShellPrintHiiEx ( + -1, + -1, + NULL, + STRING_TOKEN (STR_GEN_OUT_MEM), + gShellDriver1HiiHandle, + L"drvcfg" + ); + + ShellStatus = SHELL_OUT_OF_RESOURCES; + goto Done; + } + if (EFI_ERROR (Status)) { ShellPrintHiiEx ( -1, @@ -364,8 +409,9 @@ ConfigFromFile ( gShellDriver1HiiHandle, L"drvcfg" ); - ShellCloseFile (&FileHandle); - return (SHELL_DEVICE_ERROR); + + ShellStatus = SHELL_DEVICE_ERROR; + goto Done; } Status = ShellReadFile (FileHandle, &MainBufferSize, MainBuffer); @@ -380,12 +426,12 @@ ConfigFromFile ( FileName ); - ShellCloseFile (&FileHandle); - SHELL_FREE_NON_NULL (MainBuffer); - return (SHELL_DEVICE_ERROR); + ShellStatus = SHELL_DEVICE_ERROR; + goto Done; } ShellCloseFile (&FileHandle); + FileHandle = NULL; if (Handle != NULL) { // @@ -404,8 +450,9 @@ ConfigFromFile ( ConvertHandleToHandleIndex (Handle), L"Device" ); - ShellCloseFile (&FileHandle); - return (SHELL_DEVICE_ERROR); + + ShellStatus = SHELL_DEVICE_ERROR; + goto Done; } Status = HiiDatabase->UpdatePackageList (HiiDatabase, HiiHandle, MainBuffer); @@ -420,7 +467,9 @@ ConfigFromFile ( L"HiiDatabase->UpdatePackageList", Status ); - return (SHELL_DEVICE_ERROR); + + ShellStatus = SHELL_DEVICE_ERROR; + goto Done; } } else { // @@ -443,6 +492,20 @@ ConfigFromFile ( // print out an error. // TempDevPathString = ConvertDevicePathToText ((EFI_DEVICE_PATH_PROTOCOL *)(((CHAR8 *)PackageHeader) + sizeof (EFI_HII_PACKAGE_HEADER)), TRUE, TRUE); + if (TempDevPathString == NULL) { + ShellPrintHiiEx ( + -1, + -1, + NULL, + STRING_TOKEN (STR_GEN_OUT_MEM), + gShellDriver1HiiHandle, + L"drvcfg" + ); + + ShellStatus = SHELL_OUT_OF_RESOURCES; + goto Done; + } + ShellPrintHiiEx ( -1, -1, @@ -465,7 +528,9 @@ ConfigFromFile ( L"HiiDatabase->UpdatePackageList", Status ); - return (SHELL_DEVICE_ERROR); + + ShellStatus = SHELL_DEVICE_ERROR; + goto Done; } else { DevPath = (EFI_DEVICE_PATH_PROTOCOL *)(((CHAR8 *)PackageHeader) + sizeof (EFI_HII_PACKAGE_HEADER)); gBS->LocateDevicePath (&gEfiHiiConfigAccessProtocolGuid, &DevPath, &Handle); @@ -485,16 +550,24 @@ ConfigFromFile ( } } +Done: SHELL_FREE_NON_NULL (MainBuffer); - ShellPrintHiiEx ( - -1, - -1, - NULL, - STRING_TOKEN (STR_DRVCFG_COMP), - gShellDriver1HiiHandle - ); - return (SHELL_SUCCESS); + if (FileHandle != NULL) { + ShellCloseFile (&FileHandle); + } + + if (ShellStatus == SHELL_SUCCESS) { + ShellPrintHiiEx ( + -1, + -1, + NULL, + STRING_TOKEN (STR_DRVCFG_COMP), + gShellDriver1HiiHandle + ); + } + + return ShellStatus; } /** @@ -661,7 +734,12 @@ PreHiiDrvCfg ( // keep consistent with the above clause // DriverImageHandleBuffer = AllocatePool (sizeof (EFI_HANDLE)); - ASSERT (DriverImageHandleBuffer); + if (DriverImageHandleBuffer == NULL) { + ASSERT (DriverImageHandleBuffer); + ShellStatus = SHELL_OUT_OF_RESOURCES; + goto Done; + } + DriverImageHandleBuffer[0] = DriverImageHandle; } @@ -1264,6 +1342,11 @@ ShellCommandRunDrvCfg ( Lang = ShellCommandLineGetValue (Package, L"-l"); if (Lang != NULL) { Language = AllocateZeroPool (StrSize (Lang)); + if (Language == NULL) { + ShellStatus = SHELL_OUT_OF_RESOURCES; + goto Done; + } + AsciiSPrint (Language, StrSize (Lang), "%S", Lang); } else if (ShellCommandLineGetFlag (Package, L"-l")) { ShellPrintHiiEx (-1, -1, NULL, STRING_TOKEN (STR_GEN_NO_VALUE), gShellDriver1HiiHandle, L"drvcfg", L"-l"); @@ -1287,6 +1370,12 @@ ShellCommandRunDrvCfg ( FileName = NULL; } + if (FileName == NULL) { + ASSERT (FileName != NULL); + ShellStatus = SHELL_INVALID_PARAMETER; + goto Done; + } + if (InFromFile && EFI_ERROR (ShellFileExists (FileName))) { ShellPrintHiiEx (-1, -1, NULL, STRING_TOKEN (STR_GEN_FIND_FAIL), gShellDriver1HiiHandle, L"drvcfg", FileName); ShellStatus = SHELL_INVALID_PARAMETER; diff --git a/ShellPkg/Library/UefiShellDriver1CommandsLib/DrvDiag.c b/ShellPkg/Library/UefiShellDriver1CommandsLib/DrvDiag.c index b845d694b269..cb74983e2806 100644 --- a/ShellPkg/Library/UefiShellDriver1CommandsLib/DrvDiag.c +++ b/ShellPkg/Library/UefiShellDriver1CommandsLib/DrvDiag.c @@ -108,8 +108,8 @@ DoDiagnostics ( if (ControllerHandle != NULL) { ControllerHandleList = AllocateZeroPool (2*sizeof (EFI_HANDLE)); if (ControllerHandleList == NULL) { - SHELL_FREE_NON_NULL (DriverHandleList); - return EFI_OUT_OF_RESOURCES; + Status2 = EFI_OUT_OF_RESOURCES; + goto Done; } ControllerHandleList[0] = ControllerHandle; @@ -121,9 +121,8 @@ DoDiagnostics ( if (ChildHandle != NULL) { ChildHandleList = AllocateZeroPool (2*sizeof (EFI_HANDLE)); if (ChildHandleList == NULL) { - SHELL_FREE_NON_NULL (ControllerHandleList); - SHELL_FREE_NON_NULL (DriverHandleList); - return EFI_OUT_OF_RESOURCES; + Status2 = EFI_OUT_OF_RESOURCES; + goto Done; } ChildHandleList[0] = ChildHandle; @@ -154,7 +153,7 @@ DoDiagnostics ( PARSE_HANDLE_DATABASE_DEVICES (DriverHandleList[DriverHandleListLoop], &ControllerHandleListCount, &ControllerHandleList); } - if (ControllerHandleListCount == 0) { + if ((ControllerHandleListCount == 0) || (ControllerHandleList == NULL)) { if (Mode == TestModeList) { ShellPrintHiiEx (-1, -1, NULL, STRING_TOKEN (STR_DRVDIAG_DRIVER_NO_HANDLES), gShellDriver1HiiHandle); } @@ -199,18 +198,24 @@ DoDiagnostics ( ); if (!EFI_ERROR (Status) && (DriverDiagnostics2 != NULL)) { Language = GetBestLanguageForDriver (DriverDiagnostics2->SupportedLanguages, Lang, FALSE); - Found = TRUE; - Status = DriverDiagnostics2->RunDiagnostics ( - DriverDiagnostics2, - ControllerHandleList[ControllerHandleListLoop], - ChildHandleList == NULL ? NULL : ChildHandleList[ChildHandleListLoop], - (EFI_DRIVER_DIAGNOSTIC_TYPE)Mode, - Language, - &ErrorType, - &OutBufferSize, - &OutBuffer - ); + if (Language == NULL) { + Status2 = EFI_NOT_FOUND; + goto Done; + } + + Found = TRUE; + Status = DriverDiagnostics2->RunDiagnostics ( + DriverDiagnostics2, + ControllerHandleList[ControllerHandleListLoop], + ChildHandleList == NULL ? NULL : ChildHandleList[ChildHandleListLoop], + (EFI_DRIVER_DIAGNOSTIC_TYPE)Mode, + Language, + &ErrorType, + &OutBufferSize, + &OutBuffer + ); FreePool (Language); + Language = NULL; } } @@ -225,17 +230,23 @@ DoDiagnostics ( ); if (!EFI_ERROR (Status)) { Language = GetBestLanguageForDriver (DriverDiagnostics->SupportedLanguages, Lang, FALSE); - Status = DriverDiagnostics->RunDiagnostics ( - DriverDiagnostics, - ControllerHandleList[ControllerHandleListLoop], - ChildHandleList == NULL ? NULL : ChildHandleList[ChildHandleListLoop], - (EFI_DRIVER_DIAGNOSTIC_TYPE)Mode, - Language, - &ErrorType, - &OutBufferSize, - &OutBuffer - ); + if (Language == NULL) { + Status2 = EFI_NOT_FOUND; + goto Done; + } + + Status = DriverDiagnostics->RunDiagnostics ( + DriverDiagnostics, + ControllerHandleList[ControllerHandleListLoop], + ChildHandleList == NULL ? NULL : ChildHandleList[ChildHandleListLoop], + (EFI_DRIVER_DIAGNOSTIC_TYPE)Mode, + Language, + &ErrorType, + &OutBufferSize, + &OutBuffer + ); FreePool (Language); + Language = NULL; } } @@ -307,17 +318,13 @@ DoDiagnostics ( } } - if (DriverHandleList != NULL) { - FreePool (DriverHandleList); - } - - if (ControllerHandleList != NULL) { - FreePool (ControllerHandleList); - } +Done: - if (ChildHandleList != NULL) { - FreePool (ChildHandleList); - } + SHELL_FREE_NON_NULL (DriverHandleList); + SHELL_FREE_NON_NULL (ControllerHandleList); + SHELL_FREE_NON_NULL (ChildHandleList); + SHELL_FREE_NON_NULL (Language); + SHELL_FREE_NON_NULL (OutBuffer); return (Status2); } @@ -431,6 +438,12 @@ ShellCommandRunDrvDiag ( return (SHELL_INVALID_PARAMETER); } else if (Lang != NULL) { Language = AllocateZeroPool (StrSize (Lang)); + if (Language == NULL) { + ShellPrintHiiEx (-1, -1, NULL, STRING_TOKEN (STR_GEN_OUT_MEM), gShellDriver1HiiHandle, L"drvdiag"); + ShellCommandLineFreeVarList (Package); + return (SHELL_OUT_OF_RESOURCES); + } + AsciiSPrint (Language, StrSize (Lang), "%S", Lang); } diff --git a/ShellPkg/Library/UefiShellDriver1CommandsLib/OpenInfo.c b/ShellPkg/Library/UefiShellDriver1CommandsLib/OpenInfo.c index a1a09046584a..0d3f901feab9 100644 --- a/ShellPkg/Library/UefiShellDriver1CommandsLib/OpenInfo.c +++ b/ShellPkg/Library/UefiShellDriver1CommandsLib/OpenInfo.c @@ -25,6 +25,7 @@ STATIC CONST CHAR16 StringUnknown[] = L"Unknown "; @retval EFI_SUCCESS The operation was successful. @retval EFI_INVALID_PARAMETER TheHandle was NULL. + @retval EFI_OUT_OF_RESOURCES A memory allocation failed. **/ EFI_STATUS TraverseHandleDatabase ( @@ -102,10 +103,16 @@ TraverseHandleDatabase ( break; } - HandleIndex = ConvertHandleToHandleIndex (OpenInfo[OpenInfoIndex].AgentHandle); + HandleIndex = ConvertHandleToHandleIndex (OpenInfo[OpenInfoIndex].AgentHandle); + if (HandleIndex == 0) { + FreePool (OpenInfo); + FreePool (ProtocolGuidArray); + return EFI_OUT_OF_RESOURCES; + } + Name = GetStringNameFromHandle (OpenInfo[OpenInfoIndex].AgentHandle, NULL); ControllerIndex = ConvertHandleToHandleIndex (OpenInfo[OpenInfoIndex].ControllerHandle); - if (ControllerIndex != 0) { + if ((ControllerIndex != 0) && (Name != NULL)) { ShellPrintHiiEx ( -1, -1, @@ -128,7 +135,7 @@ TraverseHandleDatabase ( HandleIndex, OpenInfo[OpenInfoIndex].OpenCount, OpenTypeString, - Name + Name ? Name : L"" ); } } @@ -199,13 +206,21 @@ ShellCommandRunOpenInfo ( ShellStatus = SHELL_INVALID_PARAMETER; } else { Param1 = ShellCommandLineGetRawValue (Package, 1); - Status = ShellConvertStringToUint64 (Param1, &Intermediate, TRUE, FALSE); + if (Param1 != NULL) { + Status = ShellConvertStringToUint64 (Param1, &Intermediate, TRUE, FALSE); + } + if (EFI_ERROR (Status) || (Param1 == NULL) || (ConvertHandleIndexToHandle ((UINTN)Intermediate) == NULL)) { ShellPrintHiiEx (-1, -1, NULL, STRING_TOKEN (STR_GEN_INV_HANDLE), gShellDriver1HiiHandle, L"openinfo", Param1); ShellStatus = SHELL_INVALID_PARAMETER; } else { TheHandle = ConvertHandleIndexToHandle ((UINTN)Intermediate); - ASSERT (TheHandle != NULL); + if (TheHandle == NULL) { + ASSERT (TheHandle != NULL); + ShellPrintHiiEx (-1, -1, NULL, STRING_TOKEN (STR_GEN_INV_HANDLE), gShellDriver1HiiHandle, L"openinfo", Param1); + return SHELL_INVALID_PARAMETER; + } + ShellPrintHiiEx (-1, -1, NULL, STRING_TOKEN (STR_OPENINFO_HEADER_LINE), gShellDriver1HiiHandle, (UINTN)Intermediate, TheHandle); Status = TraverseHandleDatabase (TheHandle); diff --git a/ShellPkg/Library/UefiShellDriver1CommandsLib/Unload.c b/ShellPkg/Library/UefiShellDriver1CommandsLib/Unload.c index 1dd947c17762..02e8ee2a023d 100644 --- a/ShellPkg/Library/UefiShellDriver1CommandsLib/Unload.c +++ b/ShellPkg/Library/UefiShellDriver1CommandsLib/Unload.c @@ -25,6 +25,9 @@ DumpLoadedImageProtocolInfo ( CHAR16 *TheString; TheString = GetProtocolInformationDump (TheHandle, &gEfiLoadedImageProtocolGuid, TRUE); + if (TheString == NULL) { + return (EFI_INVALID_PARAMETER); + } ShellPrintEx (-1, -1, L"%s", TheString); diff --git a/ShellPkg/Library/UefiShellLevel1CommandsLib/For.c b/ShellPkg/Library/UefiShellLevel1CommandsLib/For.c index 8a6a940f2821..9cd45c2f4cb3 100644 --- a/ShellPkg/Library/UefiShellLevel1CommandsLib/For.c +++ b/ShellPkg/Library/UefiShellLevel1CommandsLib/For.c @@ -334,7 +334,10 @@ ShellCommandRunFor ( } CurrentScriptFile = ShellCommandGetCurrentScriptFile (); - ASSERT (CurrentScriptFile != NULL); + if (CurrentScriptFile == NULL) { + ASSERT (CurrentScriptFile != NULL); + return (SHELL_INVALID_PARAMETER); + } if ((CurrentScriptFile->CurrentCommand != NULL) && (CurrentScriptFile->CurrentCommand->Data == NULL)) { FirstPass = TRUE; @@ -687,6 +690,12 @@ ShellCommandRunFor ( } TempString = AllocateZeroPool (50*sizeof (CHAR16)); + if (TempString == NULL) { + SHELL_FREE_NON_NULL (ArgSet); + SHELL_FREE_NON_NULL (Info); + return (SHELL_OUT_OF_RESOURCES); + } + UnicodeSPrint (TempString, 50*sizeof (CHAR16), L"%d", Info->Current); InternalUpdateAliasOnList (Info->ReplacementName, TempString, &CurrentScriptFile->SubstList); FreePool (TempString); diff --git a/ShellPkg/Library/UefiShellLevel1CommandsLib/Goto.c b/ShellPkg/Library/UefiShellLevel1CommandsLib/Goto.c index c0b9a010a7be..1773f6a751df 100644 --- a/ShellPkg/Library/UefiShellLevel1CommandsLib/Goto.c +++ b/ShellPkg/Library/UefiShellLevel1CommandsLib/Goto.c @@ -71,6 +71,11 @@ ShellCommandRunGoto ( ASSERT ((CompareString == NULL && Size == 0) || (CompareString != NULL)); CompareString = StrnCatGrow (&CompareString, &Size, L":", 0); CompareString = StrnCatGrow (&CompareString, &Size, ShellCommandLineGetRawValue (Package, 1), 0); + if (CompareString == NULL) { + ShellCommandLineFreeVarList (Package); + return SHELL_OUT_OF_RESOURCES; + } + // // Check forwards and then backwards for a label... // diff --git a/ShellPkg/Library/UefiShellLevel1CommandsLib/If.c b/ShellPkg/Library/UefiShellLevel1CommandsLib/If.c index b4a6966edb29..f1953a75d2c3 100644 --- a/ShellPkg/Library/UefiShellLevel1CommandsLib/If.c +++ b/ShellPkg/Library/UefiShellLevel1CommandsLib/If.c @@ -99,7 +99,11 @@ IsValidProfile ( CONST CHAR16 *TempLocation; ProfilesString = ShellGetEnvironmentVariable (L"profiles"); - ASSERT (ProfilesString != NULL); + if (ProfilesString == NULL) { + ASSERT (ProfilesString != NULL); + return (FALSE); + } + TempLocation = StrStr (ProfilesString, String); if ((TempLocation != NULL) && (*(TempLocation-1) == L';') && (*(TempLocation+StrLen (String)) == L';')) { return (TRUE); @@ -895,6 +899,10 @@ ShellCommandRunIf ( // Make sure that an End exists. // CurrentScriptFile = ShellCommandGetCurrentScriptFile (); + if (CurrentScriptFile == NULL) { + return (SHELL_INVALID_PARAMETER); + } + if (!MoveToTag (GetNextNode, L"endif", L"if", NULL, CurrentScriptFile, TRUE, TRUE, FALSE)) { ShellPrintHiiEx ( -1, @@ -1076,6 +1084,9 @@ ShellCommandRunElse ( } CurrentScriptFile = ShellCommandGetCurrentScriptFile (); + if (CurrentScriptFile == NULL) { + return (SHELL_INVALID_PARAMETER); + } if (!MoveToTag (GetPreviousNode, L"if", L"endif", NULL, CurrentScriptFile, FALSE, TRUE, FALSE)) { ShellPrintHiiEx ( @@ -1158,6 +1169,10 @@ ShellCommandRunEndIf ( } CurrentScriptFile = ShellCommandGetCurrentScriptFile (); + if (CurrentScriptFile == NULL) { + return (SHELL_INVALID_PARAMETER); + } + if (!MoveToTag (GetPreviousNode, L"if", L"endif", NULL, CurrentScriptFile, FALSE, TRUE, FALSE)) { ShellPrintHiiEx ( -1, diff --git a/ShellPkg/Library/UefiShellLevel1CommandsLib/Shift.c b/ShellPkg/Library/UefiShellLevel1CommandsLib/Shift.c index 4c0debea3fce..d550682421a3 100644 --- a/ShellPkg/Library/UefiShellLevel1CommandsLib/Shift.c +++ b/ShellPkg/Library/UefiShellLevel1CommandsLib/Shift.c @@ -35,7 +35,10 @@ ShellCommandRunShift ( } CurrentScriptFile = ShellCommandGetCurrentScriptFile (); - ASSERT (CurrentScriptFile != NULL); + if (CurrentScriptFile == NULL) { + ASSERT (CurrentScriptFile != NULL); + return (SHELL_INVALID_PARAMETER); + } if (CurrentScriptFile->Argc < 2) { ShellPrintHiiEx (-1, -1, NULL, STRING_TOKEN (STR_GEN_TOO_FEW), gShellLevel1HiiHandle, L"shift"); diff --git a/ShellPkg/Library/UefiShellLevel2CommandsLib/Cd.c b/ShellPkg/Library/UefiShellLevel2CommandsLib/Cd.c index 88791c442866..7052dc33a14e 100644 --- a/ShellPkg/Library/UefiShellLevel2CommandsLib/Cd.c +++ b/ShellPkg/Library/UefiShellLevel2CommandsLib/Cd.c @@ -304,7 +304,12 @@ ShellCommandRunCd ( if (!EFI_ERROR (Status)) { Param1Copy = PathCleanUpDirectories (Param1Copy); - Status = ExtractDriveAndPath (Param1Copy, &Drive, &Path); + if (Param1Copy == NULL) { + Status = EFI_NOT_FOUND; + ShellStatus = SHELL_INVALID_PARAMETER; + } else { + Status = ExtractDriveAndPath (Param1Copy, &Drive, &Path); + } } if (!EFI_ERROR (Status) && (Drive != NULL) && (Path != NULL)) { diff --git a/ShellPkg/Library/UefiShellLevel2CommandsLib/Cp.c b/ShellPkg/Library/UefiShellLevel2CommandsLib/Cp.c index c3927ca35b3c..993bcf7cb91d 100644 --- a/ShellPkg/Library/UefiShellLevel2CommandsLib/Cp.c +++ b/ShellPkg/Library/UefiShellLevel2CommandsLib/Cp.c @@ -203,12 +203,18 @@ CopySingleFile ( if (Status == EFI_BUFFER_TOO_SMALL) { DestVolumeInfo = AllocateZeroPool (DestVolumeInfoSize); - Status = DestVolumeFP->GetInfo ( - DestVolumeFP, - &gEfiFileSystemInfoGuid, - &DestVolumeInfoSize, - DestVolumeInfo - ); + if (DestVolumeInfo == NULL) { + ShellPrintHiiEx (-1, -1, NULL, STRING_TOKEN (STR_GEN_OUT_MEM), gShellLevel2HiiHandle, L"cp"); + ShellStatus = SHELL_OUT_OF_RESOURCES; + goto Done; + } + + Status = DestVolumeFP->GetInfo ( + DestVolumeFP, + &gEfiFileSystemInfoGuid, + &DestVolumeInfoSize, + DestVolumeInfo + ); } // @@ -251,6 +257,7 @@ CopySingleFile ( SHELL_FREE_NON_NULL (DestVolumeInfo); } +Done: // // close files // diff --git a/ShellPkg/Library/UefiShellLevel2CommandsLib/Ls.c b/ShellPkg/Library/UefiShellLevel2CommandsLib/Ls.c index c03967ee3a2b..acfd26cd102f 100644 --- a/ShellPkg/Library/UefiShellLevel2CommandsLib/Ls.c +++ b/ShellPkg/Library/UefiShellLevel2CommandsLib/Ls.c @@ -42,6 +42,9 @@ PrintSfoVolumeInfoTableEntry ( if (Node->Handle == NULL) { DirectoryName = GetFullyQualifiedPath (((EFI_SHELL_FILE_INFO *)GetFirstNode (&TheList->Link))->FullName); + if (DirectoryName == NULL) { + return (EFI_OUT_OF_RESOURCES); + } // // We need to open something up to get system information @@ -70,12 +73,17 @@ PrintSfoVolumeInfoTableEntry ( if (Status == EFI_BUFFER_TOO_SMALL) { SysInfo = AllocateZeroPool (SysInfoSize); - Status = EfiFpHandle->GetInfo ( - EfiFpHandle, - &gEfiFileSystemInfoGuid, - &SysInfoSize, - SysInfo - ); + if (SysInfo == NULL) { + gEfiShellProtocol->CloseFile (ShellFileHandle); + return (EFI_OUT_OF_RESOURCES); + } + + Status = EfiFpHandle->GetInfo ( + EfiFpHandle, + &gEfiFileSystemInfoGuid, + &SysInfoSize, + SysInfo + ); } ASSERT_EFI_ERROR (Status); @@ -97,12 +105,16 @@ PrintSfoVolumeInfoTableEntry ( if (Status == EFI_BUFFER_TOO_SMALL) { SysInfo = AllocateZeroPool (SysInfoSize); - Status = EfiFpHandle->GetInfo ( - EfiFpHandle, - &gEfiFileSystemInfoGuid, - &SysInfoSize, - SysInfo - ); + if (SysInfo == NULL) { + return (EFI_OUT_OF_RESOURCES); + } + + Status = EfiFpHandle->GetInfo ( + EfiFpHandle, + &gEfiFileSystemInfoGuid, + &SysInfoSize, + SysInfo + ); } ASSERT_EFI_ERROR (Status); @@ -616,7 +628,11 @@ PrintLsOutput ( } CorrectedPath = StrnCatGrow (&CorrectedPath, &LongestPath, L"*", 0); - Status = ShellOpenFileMetaArg ((CHAR16 *)CorrectedPath, EFI_FILE_MODE_READ, &ListHead); + if (CorrectedPath == NULL) { + return SHELL_OUT_OF_RESOURCES; + } + + Status = ShellOpenFileMetaArg ((CHAR16 *)CorrectedPath, EFI_FILE_MODE_READ, &ListHead); if (!EFI_ERROR (Status)) { for ( Node = (EFI_SHELL_FILE_INFO *)GetFirstNode (&ListHead->Link) diff --git a/ShellPkg/Library/UefiShellLevel2CommandsLib/Map.c b/ShellPkg/Library/UefiShellLevel2CommandsLib/Map.c index 1e7168364d5f..a031f9c7d1a1 100644 --- a/ShellPkg/Library/UefiShellLevel2CommandsLib/Map.c +++ b/ShellPkg/Library/UefiShellLevel2CommandsLib/Map.c @@ -82,7 +82,11 @@ SearchList ( ) { TempList = StrnCatGrow (&TempList, NULL, ListWalker, 0); - ASSERT (TempList != NULL); + if (TempList == NULL) { + ASSERT (TempList != NULL); + return (FALSE); + } + TempSpot = StrStr (TempList, Target); if (TempSpot != NULL) { *TempSpot = CHAR_NULL; diff --git a/ShellPkg/Library/UefiShellLevel2CommandsLib/Parse.c b/ShellPkg/Library/UefiShellLevel2CommandsLib/Parse.c index 955e082a93d9..213e28a8294b 100644 --- a/ShellPkg/Library/UefiShellLevel2CommandsLib/Parse.c +++ b/ShellPkg/Library/UefiShellLevel2CommandsLib/Parse.c @@ -315,7 +315,11 @@ ShellCommandRunParse ( ShellCommandInstance = ShellStrToUintn (ShellCommandLineGetValue (Package, L"-s")); } - ShellStatus = PerformParsing (FileName, TableName, ShellStrToUintn (ColumnString), TableNameInstance, ShellCommandInstance, StreamingUnicode); + if ((FileName != NULL) && (TableName != NULL) && (ColumnString != NULL)) { + ShellStatus = PerformParsing (FileName, TableName, ShellStrToUintn (ColumnString), TableNameInstance, ShellCommandInstance, StreamingUnicode); + } else { + ShellStatus = SHELL_INVALID_PARAMETER; + } } } diff --git a/ShellPkg/Library/UefiShellLevel2CommandsLib/Reset.c b/ShellPkg/Library/UefiShellLevel2CommandsLib/Reset.c index 361c47e43059..cab9a1da3091 100644 --- a/ShellPkg/Library/UefiShellLevel2CommandsLib/Reset.c +++ b/ShellPkg/Library/UefiShellLevel2CommandsLib/Reset.c @@ -138,7 +138,7 @@ ShellCommandRunReset ( } else { String = ShellCommandLineGetValue (Package, L"-s"); DEBUG_CODE ( - ShellPrintEx (-1, -1, L"Reset with %s (%d bytes)", String, String != NULL ? StrSize (String) : 0); + ShellPrintEx (-1, -1, L"Reset with %s (%d bytes)\n", String, String != NULL ? StrSize (String) : 0); ); if (String != NULL) { gRT->ResetSystem (EfiResetShutdown, EFI_SUCCESS, StrSize (String), (VOID *)String); diff --git a/ShellPkg/Library/UefiShellLevel2CommandsLib/Rm.c b/ShellPkg/Library/UefiShellLevel2CommandsLib/Rm.c index 2354cd06204b..de550b83c014 100644 --- a/ShellPkg/Library/UefiShellLevel2CommandsLib/Rm.c +++ b/ShellPkg/Library/UefiShellLevel2CommandsLib/Rm.c @@ -220,7 +220,7 @@ IsValidDeleteTarget ( } TempLocation = StrStr (Node->FullName, L":"); - if (StrLen (TempLocation) <= 2) { + if ((TempLocation == NULL) || (StrLen (TempLocation) <= 2)) { // // Deleting the root directory is invalid. // @@ -242,6 +242,11 @@ IsValidDeleteTarget ( Pattern = StrnCatGrow (&Pattern, &Size, L"\\", 0); Size = 0; SearchString = StrnCatGrow (&SearchString, &Size, Node->FullName, 0); + if (SearchString == NULL) { + RetVal = FALSE; + goto Done; + } + if (!EFI_ERROR (ShellIsDirectory (SearchString))) { SearchString = StrnCatGrow (&SearchString, &Size, L"\\", 0); SearchString = StrnCatGrow (&SearchString, &Size, L"*", 0); @@ -256,6 +261,7 @@ IsValidDeleteTarget ( } } +Done: SHELL_FREE_NON_NULL (Pattern); SHELL_FREE_NON_NULL (SearchString); diff --git a/ShellPkg/Library/UefiShellLevel2CommandsLib/UefiShellLevel2CommandsLib.c b/ShellPkg/Library/UefiShellLevel2CommandsLib/UefiShellLevel2CommandsLib.c index ae643996aa72..46460aeca94f 100644 --- a/ShellPkg/Library/UefiShellLevel2CommandsLib/UefiShellLevel2CommandsLib.c +++ b/ShellPkg/Library/UefiShellLevel2CommandsLib/UefiShellLevel2CommandsLib.c @@ -335,9 +335,11 @@ ShellLevel2StripQuotes ( return EFI_OUT_OF_RESOURCES; } - for (Walker = *CleanString; Walker != NULL && *Walker != CHAR_NULL; Walker++) { + for (Walker = *CleanString; Walker != NULL && *Walker != CHAR_NULL;) { if (*Walker == L'\"') { CopyMem (Walker, Walker+1, StrSize (Walker) - sizeof (Walker[0])); + } else { + Walker++; } } diff --git a/ShellPkg/Library/UefiShellLevel2CommandsLib/Vol.c b/ShellPkg/Library/UefiShellLevel2CommandsLib/Vol.c index c4accca6cdf0..768e9e490e66 100644 --- a/ShellPkg/Library/UefiShellLevel2CommandsLib/Vol.c +++ b/ShellPkg/Library/UefiShellLevel2CommandsLib/Vol.c @@ -88,15 +88,19 @@ HandleVol ( if (Status == EFI_BUFFER_TOO_SMALL) { SysInfo = AllocateZeroPool (SysInfoSize); - Status = EfiFpHandle->GetInfo ( - EfiFpHandle, - &gEfiFileSystemInfoGuid, - &SysInfoSize, - SysInfo - ); - } + if (SysInfo == NULL) { + ShellPrintHiiEx (-1, -1, NULL, STRING_TOKEN (STR_GEN_OUT_MEM), gShellLevel2HiiHandle, L"vol"); + ASSERT (FALSE); + return SHELL_OUT_OF_RESOURCES; + } - ASSERT (SysInfo != NULL); + Status = EfiFpHandle->GetInfo ( + EfiFpHandle, + &gEfiFileSystemInfoGuid, + &SysInfoSize, + SysInfo + ); + } if (Delete) { *((CHAR16 *)SysInfo->VolumeLabel) = CHAR_NULL; @@ -155,12 +159,17 @@ HandleVol ( if (Status == EFI_BUFFER_TOO_SMALL) { SysInfo = AllocateZeroPool (SysInfoSize); - Status = EfiFpHandle->GetInfo ( - EfiFpHandle, - &gEfiFileSystemInfoGuid, - &SysInfoSize, - SysInfo - ); + if (SysInfo == NULL) { + ShellPrintHiiEx (-1, -1, NULL, STRING_TOKEN (STR_GEN_OUT_MEM), gShellLevel2HiiHandle, L"vol"); + return SHELL_OUT_OF_RESOURCES; + } + + Status = EfiFpHandle->GetInfo ( + EfiFpHandle, + &gEfiFileSystemInfoGuid, + &SysInfoSize, + SysInfo + ); } gEfiShellProtocol->CloseFile (ShellFileHandle); diff --git a/ShellPkg/Library/UefiShellLevel3CommandsLib/Help.c b/ShellPkg/Library/UefiShellLevel3CommandsLib/Help.c index 7f146bb9fbf4..076ad1e1986b 100644 --- a/ShellPkg/Library/UefiShellLevel3CommandsLib/Help.c +++ b/ShellPkg/Library/UefiShellLevel3CommandsLib/Help.c @@ -308,7 +308,6 @@ ShellCommandRunHelp ( CONST CHAR16 *CurrentCommand; CHAR16 *CommandToGetHelpOn; CHAR16 *SectionToGetHelpOn; - CHAR16 *HiiString; BOOLEAN Found; BOOLEAN PrintCommandText; UINTN SortedCommandListSize; @@ -398,9 +397,7 @@ ShellCommandRunHelp ( // we need info on the special characters // ShellPrintHiiEx (-1, -1, NULL, STRING_TOKEN (STR_HELP_SC_HEADER), gShellLevel3HiiHandle); - HiiString = HiiGetString (gShellLevel3HiiHandle, STRING_TOKEN (STR_HELP_SC_DATA), NULL); - ShellPrintEx (-1, -1, L"%s", HiiString); - FreePool (HiiString); + ShellPrintHiiEx (-1, -1, NULL, STRING_TOKEN (STR_HELP_SC_DATA), gShellLevel3HiiHandle); Found = TRUE; } else { SortedCommandList = NULL; diff --git a/ShellPkg/Library/UefiShellLib/UefiShellLib.c b/ShellPkg/Library/UefiShellLib/UefiShellLib.c index 93e36197b26b..f0235053009d 100644 --- a/ShellPkg/Library/UefiShellLib/UefiShellLib.c +++ b/ShellPkg/Library/UefiShellLib/UefiShellLib.c @@ -3820,7 +3820,10 @@ ShellPromptForResponseHii ( Prompt = HiiGetString (HiiFormatHandle, HiiFormatStringId, NULL); Status = ShellPromptForResponse (Type, Prompt, Response); - FreePool (Prompt); + if (Prompt != NULL) { + FreePool (Prompt); + } + return (Status); } diff --git a/ShellPkg/Library/UefiShellNetwork2CommandsLib/Ifconfig6.c b/ShellPkg/Library/UefiShellNetwork2CommandsLib/Ifconfig6.c index 5cb92c485b47..7e2326de8f2d 100644 --- a/ShellPkg/Library/UefiShellNetwork2CommandsLib/Ifconfig6.c +++ b/ShellPkg/Library/UefiShellNetwork2CommandsLib/Ifconfig6.c @@ -468,7 +468,10 @@ IfConfig6ParseManualAddressList ( } AddrBuf = AllocateZeroPool (AddrCnt * sizeof (EFI_IP6_CONFIG_MANUAL_ADDRESS)); - ASSERT (AddrBuf != NULL); + if (AddrBuf == NULL) { + ASSERT (AddrBuf != NULL); + return EFI_OUT_OF_RESOURCES; + } AddrCnt = 0; VarArg = *Arg; @@ -569,7 +572,10 @@ IfConfig6ParseGwDnsAddressList ( } AddrBuf = AllocateZeroPool (AddrCnt * sizeof (EFI_IPv6_ADDRESS)); - ASSERT (AddrBuf != NULL); + if (AddrBuf == NULL) { + ASSERT (AddrBuf != NULL); + return EFI_OUT_OF_RESOURCES; + } AddrCnt = 0; VarArg = *Arg; @@ -1194,7 +1200,7 @@ IfConfig6SetInterfaceInfo ( BOOLEAN IsAddressOk; UINTN DataSize; - UINT32 Index; + UINTN Index; UINT32 Index2; BOOLEAN IsAddressSet; EFI_IP6_CONFIG_INTERFACE_INFO *IfInfo; diff --git a/ShellPkg/ShellPkg.dsc b/ShellPkg/ShellPkg.dsc index 029a22fc7997..5303a6895975 100644 --- a/ShellPkg/ShellPkg.dsc +++ b/ShellPkg/ShellPkg.dsc @@ -65,6 +65,8 @@ DxeServicesLib|MdePkg/Library/DxeServicesLib/DxeServicesLib.inf ReportStatusCodeLib|MdePkg/Library/BaseReportStatusCodeLibNull/BaseReportStatusCodeLibNull.inf + SafeIntLib|MdePkg/Library/BaseSafeIntLib/BaseSafeIntLib.inf + # StackCheckLib is not linked for SEC modules by default, this package can link it against its SEC modules [LibraryClasses.common.SEC] NULL|MdePkg/Library/StackCheckLibNull/StackCheckLibNull.inf diff --git a/StandaloneMmPkg/Core/Dispatcher.c b/StandaloneMmPkg/Core/Dispatcher.c index b9fe3238465e..8e6b85caeece 100644 --- a/StandaloneMmPkg/Core/Dispatcher.c +++ b/StandaloneMmPkg/Core/Dispatcher.c @@ -655,7 +655,10 @@ FvIsBeingProcessed ( DEBUG ((DEBUG_INFO, "FvIsBeingProcessed - 0x%08x\n", FwVolHeader)); KnownFwVol = AllocatePool (sizeof (KNOWN_FWVOL)); - ASSERT (KnownFwVol != NULL); + if (KnownFwVol == NULL) { + ASSERT (FALSE); + return; + } KnownFwVol->Signature = KNOWN_FWVOL_SIGNATURE; KnownFwVol->FwVolHeader = FwVolHeader; @@ -763,6 +766,13 @@ MmDriverDispatchHandler ( MmiHandlerUnRegister (DispatchHandle); + // + // Free shadowed standalone BFV + // + if (mBfv != NULL) { + FreePool (mBfv); + } + return EFI_SUCCESS; } diff --git a/StandaloneMmPkg/Core/StandaloneMmCore.c b/StandaloneMmPkg/Core/StandaloneMmCore.c index f38d7d748343..292e556b372b 100644 --- a/StandaloneMmPkg/Core/StandaloneMmCore.c +++ b/StandaloneMmPkg/Core/StandaloneMmCore.c @@ -83,9 +83,10 @@ MM_CORE_MMI_HANDLERS mMmCoreMmiHandlers[] = { { NULL, NULL, NULL, FALSE }, }; -BOOLEAN mMmEntryPointRegistered = FALSE; -MM_COMM_BUFFER *mMmCommunicationBuffer; -VOID *mInternalCommBufferCopy; +BOOLEAN mMmEntryPointRegistered = FALSE; +MM_COMM_BUFFER *mMmCommunicationBuffer; +VOID *mInternalCommBufferCopy; +EFI_FIRMWARE_VOLUME_HEADER *mBfv = NULL; /** Place holder function until all the MM System Table Service are available. @@ -574,11 +575,12 @@ MmEntryPoint ( } // - // Update CommunicationBuffer, BufferSize and ReturnStatus - // Communicate service finished, reset the pointer to CommBuffer to NULL + // Update ReturnBufferSize and ReturnStatus + // Communicate service finished, reset IsCommBufferValid to FALSE // - CommunicationStatus->ReturnBufferSize = BufferSize; - CommunicationStatus->ReturnStatus = (Status == EFI_SUCCESS) ? EFI_SUCCESS : EFI_NOT_FOUND; + CommunicationStatus->IsCommBufferValid = FALSE; + CommunicationStatus->ReturnBufferSize = BufferSize; + CommunicationStatus->ReturnStatus = (Status == EFI_SUCCESS) ? EFI_SUCCESS : EFI_NOT_FOUND; } else { DEBUG ((DEBUG_ERROR, "Input buffer size is larger than the size of MM Communication Buffer\n")); ASSERT (FALSE); @@ -663,13 +665,7 @@ MigrateMemoryAllocationHobs ( Hob.Raw = GetNextHob (EFI_HOB_TYPE_MEMORY_ALLOCATION, HobStart); while (Hob.Raw != NULL) { MemoryAllocationHob = (EFI_HOB_MEMORY_ALLOCATION *)Hob.Raw; - if ((MemoryAllocationHob->AllocDescriptor.MemoryType == EfiBootServicesData) && - (MmIsBufferOutsideMmValid ( - MemoryAllocationHob->AllocDescriptor.MemoryBaseAddress, - MemoryAllocationHob->AllocDescriptor.MemoryLength - )) - ) - { + if (MemoryAllocationHob->AllocDescriptor.MemoryType == EfiBootServicesData) { if (!IsZeroGuid (&MemoryAllocationHob->AllocDescriptor.Name)) { MemoryInMmram = AllocatePages (EFI_SIZE_TO_PAGES (MemoryAllocationHob->AllocDescriptor.MemoryLength)); if (MemoryInMmram != NULL) { @@ -703,30 +699,81 @@ MigrateMemoryAllocationHobs ( } } -/** Returns the HOB list size. +/** + This function is responsible for validating the input HOB list and + initializing a new HOB list in MMRAM based on the input HOB list. - @param [in] HobStart Pointer to the start of the HOB list. + @param [in] HobStart Pointer to the start of the HOB list. + @param [in] MmramRanges Pointer to the Mmram ranges. + @param [in] MmramRangeCount Count of Mmram ranges. - @retval Size of the HOB list. + @retval Pointer to the new location of hob list in MMRAM. **/ -UINTN -GetHobListSize ( - IN VOID *HobStart +VOID * +InitializeMmHobList ( + IN VOID *HobStart, + IN EFI_MMRAM_DESCRIPTOR *MmramRanges, + IN UINTN MmramRangeCount ) { + VOID *MmHobStart; + UINTN HobSize; + EFI_STATUS Status; EFI_PEI_HOB_POINTERS Hob; + UINTN Index; + EFI_PHYSICAL_ADDRESS MmramBase; + EFI_PHYSICAL_ADDRESS MmramEnd; + EFI_PHYSICAL_ADDRESS ResourceHobBase; + EFI_PHYSICAL_ADDRESS ResourceHobEnd; ASSERT (HobStart != NULL); Hob.Raw = (UINT8 *)HobStart; while (!END_OF_HOB_LIST (Hob)) { Hob.Raw = GET_NEXT_HOB (Hob); + if (Hob.Header->HobType == EFI_HOB_TYPE_RESOURCE_DESCRIPTOR) { + ResourceHobBase = Hob.ResourceDescriptor->PhysicalStart; + ResourceHobEnd = Hob.ResourceDescriptor->PhysicalStart + Hob.ResourceDescriptor->ResourceLength; + + for (Index = 0; Index < MmramRangeCount; Index++) { + MmramBase = MmramRanges[Index].PhysicalStart; + MmramEnd = MmramRanges[Index].PhysicalStart + MmramRanges[Index].PhysicalSize; + + if ((MmramBase < ResourceHobEnd) && (MmramEnd > ResourceHobBase)) { + // + // The Resource HOB is to describe the accessible non-Mmram range. + // All Resource HOB should not overlapp with any Mmram range. + // + DEBUG (( + DEBUG_ERROR, + "The resource HOB range [0x%lx, 0x%lx] overlaps with MMRAM range\n", + ResourceHobBase, + ResourceHobEnd + )); + CpuDeadLoop (); + } + } + } } // // Need plus END_OF_HOB_LIST // - return (UINTN)Hob.Raw - (UINTN)HobStart + sizeof (EFI_HOB_GENERIC_HEADER); + HobSize = (UINTN)Hob.Raw - (UINTN)HobStart + sizeof (EFI_HOB_GENERIC_HEADER); + DEBUG ((DEBUG_INFO, "HobSize - 0x%x\n", HobSize)); + + MmHobStart = AllocatePool (HobSize); + DEBUG ((DEBUG_INFO, "MmHobStart - 0x%x\n", MmHobStart)); + ASSERT (MmHobStart != NULL); + CopyMem (MmHobStart, HobStart, HobSize); + + DEBUG ((DEBUG_INFO, "MmInstallConfigurationTable For HobList\n")); + Status = MmInstallConfigurationTable (&gMmCoreMmst, &gEfiHobListGuid, MmHobStart, HobSize); + ASSERT_EFI_ERROR (Status); + + MigrateMemoryAllocationHobs (MmHobStart); + + return MmHobStart; } /** @@ -750,8 +797,6 @@ StandaloneMmMain ( { EFI_STATUS Status; UINTN Index; - VOID *MmHobStart; - UINTN HobSize; VOID *Registration; EFI_HOB_GUID_TYPE *MmramRangesHob; EFI_MMRAM_HOB_DESCRIPTOR_BLOCK *MmramRangesHobData; @@ -804,21 +849,11 @@ StandaloneMmMain ( // It is done in the constructor of StandaloneMmCoreMemoryAllocationLib(), // so that the library linked with StandaloneMmCore can use AllocatePool() in // the constructor. - - DEBUG ((DEBUG_INFO, "MmInstallConfigurationTable For HobList\n")); + // // // Install HobList // - HobSize = GetHobListSize (HobStart); - DEBUG ((DEBUG_INFO, "HobSize - 0x%x\n", HobSize)); - MmHobStart = AllocatePool (HobSize); - DEBUG ((DEBUG_INFO, "MmHobStart - 0x%x\n", MmHobStart)); - ASSERT (MmHobStart != NULL); - CopyMem (MmHobStart, HobStart, HobSize); - Status = MmInstallConfigurationTable (&gMmCoreMmst, &gEfiHobListGuid, MmHobStart, HobSize); - ASSERT_EFI_ERROR (Status); - MigrateMemoryAllocationHobs (MmHobStart); - gHobList = MmHobStart; + gHobList = InitializeMmHobList (HobStart, MmramRanges, MmramRangeCount); // // Register notification for EFI_MM_CONFIGURATION_PROTOCOL registration and @@ -843,9 +878,19 @@ StandaloneMmMain ( // Dispatch standalone BFV // if (BfvHob->BaseAddress != 0) { - DEBUG ((DEBUG_INFO, "Mm Dispatch StandaloneBfvAddress - 0x%08x\n", BfvHob->BaseAddress)); - MmCoreFfsFindMmDriver ((EFI_FIRMWARE_VOLUME_HEADER *)(UINTN)BfvHob->BaseAddress, 0); - MmDispatcher (); + // + // Shadow standalone BFV into MMRAM + // + mBfv = AllocatePool (BfvHob->Length); + if (mBfv != NULL) { + CopyMem ((VOID *)mBfv, (VOID *)(UINTN)BfvHob->BaseAddress, BfvHob->Length); + DEBUG ((DEBUG_INFO, "Mm Dispatch StandaloneBfvAddress - 0x%08x\n", mBfv)); + MmCoreFfsFindMmDriver (mBfv, 0); + MmDispatcher (); + if (!FeaturePcdGet (PcdRestartMmDispatcherOnceMmEntryRegistered)) { + FreePool (mBfv); + } + } } } diff --git a/StandaloneMmPkg/Core/StandaloneMmCore.h b/StandaloneMmPkg/Core/StandaloneMmCore.h index 093a35fb56be..7bff1cde1433 100644 --- a/StandaloneMmPkg/Core/StandaloneMmCore.h +++ b/StandaloneMmPkg/Core/StandaloneMmCore.h @@ -178,9 +178,10 @@ typedef struct { // // MM Core Global Variables // -extern EFI_MM_SYSTEM_TABLE gMmCoreMmst; -extern LIST_ENTRY gHandleList; -extern BOOLEAN mMmEntryPointRegistered; +extern EFI_MM_SYSTEM_TABLE gMmCoreMmst; +extern LIST_ENTRY gHandleList; +extern BOOLEAN mMmEntryPointRegistered; +extern EFI_FIRMWARE_VOLUME_HEADER *mBfv; /** Called to initialize the memory service. diff --git a/StandaloneMmPkg/Drivers/StandaloneMmIplPei/MmFoundationHob.c b/StandaloneMmPkg/Drivers/StandaloneMmIplPei/MmFoundationHob.c index a0f8d1f14f7d..b2611f2b4961 100644 --- a/StandaloneMmPkg/Drivers/StandaloneMmIplPei/MmFoundationHob.c +++ b/StandaloneMmPkg/Drivers/StandaloneMmIplPei/MmFoundationHob.c @@ -117,10 +117,9 @@ MmIplBuildFvHob ( EFI_HOB_FIRMWARE_VOLUME *FvHob; UINT16 HobLength; - ASSERT (Hob != NULL); - HobLength = ALIGN_VALUE (sizeof (EFI_HOB_FIRMWARE_VOLUME), 8); if (*HobBufferSize >= HobLength) { + ASSERT (Hob != NULL); MmIplCreateHob (Hob, EFI_HOB_TYPE_FV, sizeof (EFI_HOB_FIRMWARE_VOLUME)); FvHob = (EFI_HOB_FIRMWARE_VOLUME *)Hob; @@ -153,10 +152,9 @@ MmIplBuildMmAcpiS3EnableHob ( MM_ACPI_S3_ENABLE *MmAcpiS3Enable; UINT16 HobLength; - ASSERT (Hob != NULL); - HobLength = ALIGN_VALUE (sizeof (EFI_HOB_GUID_TYPE) + sizeof (MM_ACPI_S3_ENABLE), 8); if (*HobBufferSize >= HobLength) { + ASSERT (Hob != NULL); MmIplCreateHob (Hob, EFI_HOB_TYPE_GUID_EXTENSION, HobLength); GuidHob = (EFI_HOB_GUID_TYPE *)Hob; @@ -191,12 +189,11 @@ MmIplBuildMmCpuSyncConfigHob ( MM_CPU_SYNC_CONFIG *MmSyncModeInfoHob; UINT16 HobLength; - ASSERT (Hob != NULL); - GuidHob = (EFI_HOB_GUID_TYPE *)(UINTN)Hob; HobLength = ALIGN_VALUE (sizeof (EFI_HOB_GUID_TYPE) + sizeof (MM_CPU_SYNC_CONFIG), 8); if (*HobBufferSize >= HobLength) { + ASSERT (Hob != NULL); MmIplCreateHob (GuidHob, EFI_HOB_TYPE_GUID_EXTENSION, HobLength); CopyGuid (&GuidHob->Name, &gMmCpuSyncConfigHobGuid); @@ -240,6 +237,7 @@ MmIplCopyGuidHob ( while (GuidHob != NULL) { if (*HobBufferSize >= UsedSize + GuidHob->HobLength) { + ASSERT (HobBuffer != NULL); CopyMem (HobBuffer + UsedSize, GuidHob, GuidHob->HobLength); } @@ -285,13 +283,13 @@ MmIplBuildMmCoreModuleHob ( UINT16 HobLength; EFI_HOB_MEMORY_ALLOCATION_MODULE *MmCoreModuleHob; - ASSERT (Hob != NULL); ASSERT (ADDRESS_IS_ALIGNED (Base, EFI_PAGE_SIZE)); ASSERT (IS_ALIGNED (Length, EFI_PAGE_SIZE)); ASSERT (EntryPoint >= Base && EntryPoint < Base + Length); HobLength = ALIGN_VALUE (sizeof (EFI_HOB_MEMORY_ALLOCATION_MODULE), 8); if (*HobBufferSize >= HobLength) { + ASSERT (Hob != NULL); MmIplCreateHob (Hob, EFI_HOB_TYPE_MEMORY_ALLOCATION, sizeof (EFI_HOB_MEMORY_ALLOCATION_MODULE)); MmCoreModuleHob = (EFI_HOB_MEMORY_ALLOCATION_MODULE *)Hob; @@ -389,6 +387,7 @@ MmIplBuildMmProfileHobs ( // Build memory allocation HOB // ASSERT (Hob.MemoryAllocation->Header.HobLength == ALIGN_VALUE (sizeof (EFI_HOB_MEMORY_ALLOCATION), 8)); + ASSERT (HobBuffer != NULL); CopyMem (HobBuffer, Hob.Raw, Hob.MemoryAllocation->Header.HobLength); // @@ -567,6 +566,49 @@ MemoryRegionBaseAddressCompare ( return 0; } +/** + The routine returns TRUE when CPU supports it (CPUID[7,0].ECX.BIT[16] is set) and + the max physical address bits is bigger than 48. Because 4-level paging can support + to address physical address up to 2^48 - 1, there is no need to enable 5-level paging + with max physical address bits <= 48. + + @retval TRUE 5-level paging enabling is needed. + @retval FALSE 5-level paging enabling is not needed. +**/ +BOOLEAN +MmIplIs5LevelPagingNeeded ( + VOID + ) +{ + CPUID_VIR_PHY_ADDRESS_SIZE_EAX VirPhyAddressSize; + CPUID_STRUCTURED_EXTENDED_FEATURE_FLAGS_ECX ExtFeatureEcx; + UINT32 MaxExtendedFunctionId; + + AsmCpuid (CPUID_EXTENDED_FUNCTION, &MaxExtendedFunctionId, NULL, NULL, NULL); + if (MaxExtendedFunctionId >= CPUID_VIR_PHY_ADDRESS_SIZE) { + AsmCpuid (CPUID_VIR_PHY_ADDRESS_SIZE, &VirPhyAddressSize.Uint32, NULL, NULL, NULL); + } else { + VirPhyAddressSize.Bits.PhysicalAddressBits = 36; + } + + AsmCpuidEx ( + CPUID_STRUCTURED_EXTENDED_FEATURE_FLAGS, + CPUID_STRUCTURED_EXTENDED_FEATURE_FLAGS_SUB_LEAF_INFO, + NULL, + NULL, + &ExtFeatureEcx.Uint32, + NULL + ); + + if ((VirPhyAddressSize.Bits.PhysicalAddressBits > 4 * 9 + 12) && + (ExtFeatureEcx.Bits.FiveLevelPage == 1)) + { + return TRUE; + } else { + return FALSE; + } +} + /** Calculate the maximum support address. @@ -597,6 +639,18 @@ MmIplCalculateMaximumSupportAddress ( } } + // + // 4-level paging supports translating 48-bit linear addresses to 52-bit physical addresses. + // Since linear addresses are sign-extended, the linear-address space of 4-level paging is: + // [0, 2^47-1] and [0xffff8000_00000000, 0xffffffff_ffffffff]. + // So only [0, 2^47-1] linear-address range maps to the identical physical-address range when + // 5-Level paging is disabled. + // + ASSERT (PhysicalAddressBits <= 52); + if (!MmIplIs5LevelPagingNeeded () && (PhysicalAddressBits > 47)) { + PhysicalAddressBits = 47; + } + return PhysicalAddressBits; } diff --git a/StandaloneMmPkg/Drivers/StandaloneMmIplPei/StandaloneMmIplPei.c b/StandaloneMmPkg/Drivers/StandaloneMmIplPei/StandaloneMmIplPei.c index b1cd3c1d81e1..1a01d7a465c5 100644 --- a/StandaloneMmPkg/Drivers/StandaloneMmIplPei/StandaloneMmIplPei.c +++ b/StandaloneMmPkg/Drivers/StandaloneMmIplPei/StandaloneMmIplPei.c @@ -513,14 +513,6 @@ ExecuteMmCoreFromMmram ( Status = LocateMmCoreFv (&MmFvBase, &MmFvSize, &MmCoreFileName, &ImageContext.Handle); ASSERT_EFI_ERROR (Status); - // - // Unblock the MM FV range to be accessible from inside MM - // - if ((MmFvBase != 0) && (MmFvSize != 0)) { - Status = MmUnblockMemoryRequest (MmFvBase, EFI_SIZE_TO_PAGES (MmFvSize)); - ASSERT_EFI_ERROR (Status); - } - // // Initialize ImageContext // diff --git a/StandaloneMmPkg/Library/FvLib/FvLib.c b/StandaloneMmPkg/Library/FvLib/FvLib.c index e0f344af3873..2faa7cd054f7 100644 --- a/StandaloneMmPkg/Library/FvLib/FvLib.c +++ b/StandaloneMmPkg/Library/FvLib/FvLib.c @@ -167,7 +167,7 @@ FfsFindNextFile ( FileOffset = (UINT32)((UINT8 *)FfsFileHeader - (UINT8 *)FwVolHeader); - while (FileOffset < (FvLength - sizeof (EFI_FFS_FILE_HEADER))) { + while ((UINT64)FileOffset < (FvLength - sizeof (EFI_FFS_FILE_HEADER))) { // // Get FileState which is the highest bit of the State // diff --git a/StandaloneMmPkg/Library/StandaloneMmMemLib/ArmStandaloneMmMemLibInternal.c b/StandaloneMmPkg/Library/StandaloneMmMemLib/ArmStandaloneMmMemLibInternal.c index fddcecf6da3b..2f96ab094fea 100644 --- a/StandaloneMmPkg/Library/StandaloneMmMemLib/ArmStandaloneMmMemLibInternal.c +++ b/StandaloneMmPkg/Library/StandaloneMmMemLib/ArmStandaloneMmMemLibInternal.c @@ -6,15 +6,13 @@ all MMRAM range via MM_ACCESS_PROTOCOL, including the range for firmware (like MM Core and MM driver) and/or specific dedicated hardware. - Copyright (c) 2015, Intel Corporation. All rights reserved.
+ Copyright (c) 2015 - 2024, Intel Corporation. All rights reserved.
Copyright (c) 2016 - 2018, ARM Limited. All rights reserved.
SPDX-License-Identifier: BSD-2-Clause-Patent **/ -#include -#include -#include +#include "StandaloneMmMemLibInternal.h" // // Maximum support address used to check input buffer // @@ -25,7 +23,7 @@ extern EFI_PHYSICAL_ADDRESS mMmMemLibInternalMaximumSupportAddress; **/ VOID -MmMemLibInternalCalculateMaximumSupportAddress ( +MmMemLibCalculateMaximumSupportAddress ( VOID ) { @@ -35,29 +33,43 @@ MmMemLibInternalCalculateMaximumSupportAddress ( } /** - Initialize cached Mmram Ranges from HOB. - - @retval EFI_UNSUPPORTED The routine is unable to extract MMRAM information. - @retval EFI_SUCCESS MmRanges are populated successfully. + Initialize valid non-Mmram Ranges from Resource HOB. **/ -EFI_STATUS -MmMemLibInternalPopulateMmramRanges ( +VOID +MmMemLibInitializeValidNonMmramRanges ( VOID ) { // Not implemented for AARCH64. - return EFI_SUCCESS; } /** - Deinitialize cached Mmram Ranges. + Deinitialize cached non-Mmram Ranges. **/ VOID -MmMemLibInternalFreeMmramRanges ( +MmMemLibFreeValidNonMmramRanges ( VOID ) { // Not implemented for AARCH64. } + +/** + This function check if the buffer is valid non-MMRAM memory range. + + @param[in] Buffer The buffer start address to be checked. + @param[in] Length The buffer length to be checked. + + @retval TRUE This buffer is valid non-MMRAM memory range. + @retval FALSE This buffer is not valid non-MMRAM memory range. +**/ +BOOLEAN +MmMemLibIsValidNonMmramRange ( + IN EFI_PHYSICAL_ADDRESS Buffer, + IN UINT64 Length + ) +{ + return TRUE; +} diff --git a/StandaloneMmPkg/Library/StandaloneMmMemLib/StandaloneMmMemLib.c b/StandaloneMmPkg/Library/StandaloneMmMemLib/StandaloneMmMemLib.c index 814352369ed3..fab4503fe4df 100644 --- a/StandaloneMmPkg/Library/StandaloneMmMemLib/StandaloneMmMemLib.c +++ b/StandaloneMmPkg/Library/StandaloneMmMemLib/StandaloneMmMemLib.c @@ -6,57 +6,20 @@ all MMRAM range via MM_ACCESS_PROTOCOL, including the range for firmware (like MM Core and MM driver) and/or specific dedicated hardware. - Copyright (c) 2015, Intel Corporation. All rights reserved.
+ Copyright (c) 2015 - 2024, Intel Corporation. All rights reserved.
Copyright (c) 2016 - 2021, Arm Limited. All rights reserved.
SPDX-License-Identifier: BSD-2-Clause-Patent **/ -#include - -#include -#include -#include - -EFI_MMRAM_DESCRIPTOR *mMmMemLibInternalMmramRanges; -UINTN mMmMemLibInternalMmramCount; +#include "StandaloneMmMemLibInternal.h" // // Maximum support address used to check input buffer // EFI_PHYSICAL_ADDRESS mMmMemLibInternalMaximumSupportAddress = 0; -/** - Calculate and save the maximum support address. - -**/ -VOID -MmMemLibInternalCalculateMaximumSupportAddress ( - VOID - ); - -/** - Initialize cached Mmram Ranges from HOB. - - @retval EFI_UNSUPPORTED The routine is unable to extract MMRAM information. - @retval EFI_SUCCESS MmRanges are populated successfully. - -**/ -EFI_STATUS -MmMemLibInternalPopulateMmramRanges ( - VOID - ); - -/** - Deinitialize cached Mmram Ranges. - -**/ -VOID -MmMemLibInternalFreeMmramRanges ( - VOID - ); - /** This function check if the buffer is valid per processor architecture and not overlap with MMRAM. @@ -73,8 +36,6 @@ MmIsBufferOutsideMmValid ( IN UINT64 Length ) { - UINTN Index; - // // Check override. // NOTE: (B:0->L:4G) is invalid for IA32, but (B:1->L:4G-1)/(B:4G-1->L:1) is valid. @@ -96,29 +57,7 @@ MmIsBufferOutsideMmValid ( return FALSE; } - for (Index = 0; Index < mMmMemLibInternalMmramCount; Index++) { - if (((Buffer >= mMmMemLibInternalMmramRanges[Index].CpuStart) && - (Buffer < mMmMemLibInternalMmramRanges[Index].CpuStart + mMmMemLibInternalMmramRanges[Index].PhysicalSize)) || - ((mMmMemLibInternalMmramRanges[Index].CpuStart >= Buffer) && - (mMmMemLibInternalMmramRanges[Index].CpuStart < Buffer + Length))) - { - DEBUG (( - DEBUG_ERROR, - "MmIsBufferOutsideMmValid: Overlap: Buffer (0x%lx) - Length (0x%lx), ", - Buffer, - Length - )); - DEBUG (( - DEBUG_ERROR, - "CpuStart (0x%lx) - PhysicalSize (0x%lx)\n", - mMmMemLibInternalMmramRanges[Index].CpuStart, - mMmMemLibInternalMmramRanges[Index].PhysicalSize - )); - return FALSE; - } - } - - return TRUE; + return MmMemLibIsValidNonMmramRange (Buffer, Length); } /** @@ -288,19 +227,17 @@ MemLibConstructor ( IN EFI_MM_SYSTEM_TABLE *MmSystemTable ) { - EFI_STATUS Status; - // // Calculate and save maximum support address // - MmMemLibInternalCalculateMaximumSupportAddress (); + MmMemLibCalculateMaximumSupportAddress (); // - // Initialize cached Mmram Ranges from HOB. + // Initialize valid non-Mmram Ranges from Resource HOB. // - Status = MmMemLibInternalPopulateMmramRanges (); + MmMemLibInitializeValidNonMmramRanges (); - return Status; + return EFI_SUCCESS; } /** @@ -320,9 +257,8 @@ MemLibDestructor ( ) { // - // Deinitialize cached Mmram Ranges. + // Deinitialize cached non-Mmram Ranges. // - MmMemLibInternalFreeMmramRanges (); - + MmMemLibFreeValidNonMmramRanges (); return EFI_SUCCESS; } diff --git a/StandaloneMmPkg/Library/StandaloneMmMemLib/StandaloneMmMemLib.inf b/StandaloneMmPkg/Library/StandaloneMmMemLib/StandaloneMmMemLib.inf index a748af5ea539..4987deb8c9f2 100644 --- a/StandaloneMmPkg/Library/StandaloneMmMemLib/StandaloneMmMemLib.inf +++ b/StandaloneMmPkg/Library/StandaloneMmMemLib/StandaloneMmMemLib.inf @@ -6,7 +6,7 @@ # all MMRAM range via MM_ACCESS_PROTOCOL, including the range for firmware (like MM Core # and MM driver) and/or specific dedicated hardware. # -# Copyright (c) 2015, Intel Corporation. All rights reserved.
+# Copyright (c) 2015 - 2024, Intel Corporation. All rights reserved.
# Copyright (c) 2016 - 2018, ARM Limited. All rights reserved.
# Copyright (c) Microsoft Corporation. # @@ -33,6 +33,7 @@ [Sources.Common] StandaloneMmMemLib.c + StandaloneMmMemLibInternal.h [Sources.IA32, Sources.X64] X86StandaloneMmMemLibInternal.c @@ -49,7 +50,3 @@ DebugLib HobLib MemoryAllocationLib - -[Guids] - gEfiMmPeiMmramMemoryReserveGuid ## SOMETIMES_CONSUMES ## HOB - gEfiSmmSmramMemoryGuid ## SOMETIMES_CONSUMES ## HOB diff --git a/StandaloneMmPkg/Library/StandaloneMmMemLib/StandaloneMmMemLibInternal.h b/StandaloneMmPkg/Library/StandaloneMmMemLib/StandaloneMmMemLibInternal.h new file mode 100644 index 000000000000..bb3701a3a0a0 --- /dev/null +++ b/StandaloneMmPkg/Library/StandaloneMmMemLib/StandaloneMmMemLibInternal.h @@ -0,0 +1,60 @@ +/** @file + Internal header for StandaloneMmMemLib. + + Copyright (c) 2024, Intel Corporation. All rights reserved.
+ SPDX-License-Identifier: BSD-2-Clause-Patent + +**/ + +#ifndef STANDALONE_MM_MEM_LIB_INTERNAL_H_ +#define STANDALONE_MM_MEM_LIB_INTERNAL_H_ + +#include + +#include +#include +#include + +/** + Calculate and save the maximum support address. + +**/ +VOID +MmMemLibCalculateMaximumSupportAddress ( + VOID + ); + +/** + Initialize valid non-Mmram Ranges from Resource HOB. + +**/ +VOID +MmMemLibInitializeValidNonMmramRanges ( + VOID + ); + +/** + Deinitialize cached non-Mmram Ranges. + +**/ +VOID +MmMemLibFreeValidNonMmramRanges ( + VOID + ); + +/** + This function check if the buffer is valid non-MMRAM memory range. + + @param[in] Buffer The buffer start address to be checked. + @param[in] Length The buffer length to be checked. + + @retval TRUE This buffer is valid non-MMRAM memory range. + @retval FALSE This buffer is not valid non-MMRAM memory range. +**/ +BOOLEAN +MmMemLibIsValidNonMmramRange ( + IN EFI_PHYSICAL_ADDRESS Buffer, + IN UINT64 Length + ); + +#endif diff --git a/StandaloneMmPkg/Library/StandaloneMmMemLib/X86StandaloneMmMemLibInternal.c b/StandaloneMmPkg/Library/StandaloneMmMemLib/X86StandaloneMmMemLibInternal.c index 19e1736ae174..ee7aa7482562 100644 --- a/StandaloneMmPkg/Library/StandaloneMmMemLib/X86StandaloneMmMemLibInternal.c +++ b/StandaloneMmPkg/Library/StandaloneMmMemLib/X86StandaloneMmMemLibInternal.c @@ -6,35 +6,37 @@ all MMRAM range via MM_ACCESS_PROTOCOL, including the range for firmware (like MM Core and MM driver) and/or specific dedicated hardware. - Copyright (c) 2015, Intel Corporation. All rights reserved.
+ Copyright (c) 2015 - 2024, Intel Corporation. All rights reserved.
Copyright (c) 2016 - 2018, ARM Limited. All rights reserved.
Copyright (c) Microsoft Corporation. SPDX-License-Identifier: BSD-2-Clause-Patent **/ +#include "StandaloneMmMemLibInternal.h" #include -#include -#include #include -#include #include -#include +typedef struct { + EFI_PHYSICAL_ADDRESS Base; + UINT64 Length; +} NON_MM_MEMORY_RANGE; + +NON_MM_MEMORY_RANGE *mValidNonMmramRanges; +UINTN mValidNonMmramCount; // // Maximum support address used to check input buffer // extern EFI_PHYSICAL_ADDRESS mMmMemLibInternalMaximumSupportAddress; -extern EFI_MMRAM_DESCRIPTOR *mMmMemLibInternalMmramRanges; -extern UINTN mMmMemLibInternalMmramCount; /** Calculate and save the maximum support address. **/ VOID -MmMemLibInternalCalculateMaximumSupportAddress ( +MmMemLibCalculateMaximumSupportAddress ( VOID ) { @@ -74,66 +76,192 @@ MmMemLibInternalCalculateMaximumSupportAddress ( } /** - Initialize cached Mmram Ranges from HOB. + Merge the overlapped or continuous ranges in input MemoryRange. This function is to optimize + the process of checking whether a buffer range belongs to the range reported by resource HOB, + since the buffer to be checked may be covered by multi resource HOB. + + @param[in, out] MemoryRange A pointer to the NonMmramRanges reported by resource HOB. + @param[in, out] MemoryRangeSize A pointer to the size, in bytes, of the MemoryRange buffer. + On input, it is the size of the current memory map. + On output, it is the size of new memory map after merge. +**/ +STATIC +VOID +MergeOverlappedOrContinuousRanges ( + IN OUT NON_MM_MEMORY_RANGE *MemoryRange, + IN OUT UINTN *MemoryRangeSize + ) +{ + NON_MM_MEMORY_RANGE *MemoryRangeEntry; + NON_MM_MEMORY_RANGE *MemoryRangeEnd; + NON_MM_MEMORY_RANGE *NewMemoryRangeEntry; + NON_MM_MEMORY_RANGE *NextMemoryRangeEntry; + EFI_PHYSICAL_ADDRESS End; + + MemoryRangeEntry = MemoryRange; + NewMemoryRangeEntry = MemoryRange; + MemoryRangeEnd = (NON_MM_MEMORY_RANGE *)((UINT8 *)MemoryRange + *MemoryRangeSize); + while ((UINTN)MemoryRangeEntry < (UINTN)MemoryRangeEnd) { + NextMemoryRangeEntry = MemoryRangeEntry + 1; + + do { + if (((UINTN)NextMemoryRangeEntry < (UINTN)MemoryRangeEnd) && + ((MemoryRangeEntry->Base + MemoryRangeEntry->Length) >= NextMemoryRangeEntry->Base)) + { + // + // Merge the overlapped or continuous ranges. + // + End = MAX ( + MemoryRangeEntry->Base + MemoryRangeEntry->Length, + NextMemoryRangeEntry->Base + NextMemoryRangeEntry->Length + ); + MemoryRangeEntry->Length = End - MemoryRangeEntry->Base; + + NextMemoryRangeEntry++; + continue; + } else { + // + // Copy the processed independent range to the new index location. + // + CopyMem (NewMemoryRangeEntry, MemoryRangeEntry, sizeof (NON_MM_MEMORY_RANGE)); + break; + } + } while (TRUE); + + MemoryRangeEntry = NextMemoryRangeEntry; + NewMemoryRangeEntry++; + } + + *MemoryRangeSize = (UINTN)NewMemoryRangeEntry - (UINTN)MemoryRange; +} + +/** + Function to compare 2 NON_MM_MEMORY_RANGE pointer based on Base. + + @param[in] Buffer1 pointer to NON_MM_MEMORY_RANGE pointer to compare + @param[in] Buffer2 pointer to second NON_MM_MEMORY_RANGE pointer to compare + + @retval 0 Buffer1 equal to Buffer2 + @retval <0 Buffer1 is less than Buffer2 + @retval >0 Buffer1 is greater than Buffer2 +**/ +INTN +EFIAPI +NonMmMapCompare ( + IN CONST VOID *Buffer1, + IN CONST VOID *Buffer2 + ) +{ + if (((NON_MM_MEMORY_RANGE *)Buffer1)->Base > ((NON_MM_MEMORY_RANGE *)Buffer2)->Base) { + return 1; + } else if (((NON_MM_MEMORY_RANGE *)Buffer1)->Base < ((NON_MM_MEMORY_RANGE *)Buffer2)->Base) { + return -1; + } - @retval EFI_UNSUPPORTED The routine is unable to extract MMRAM information. - @retval EFI_SUCCESS MmRanges are populated successfully. + return 0; +} + +/** + Initialize valid non-Mmram Ranges from Resource HOB. **/ -EFI_STATUS -MmMemLibInternalPopulateMmramRanges ( +VOID +MmMemLibInitializeValidNonMmramRanges ( VOID ) { - VOID *HobStart; - EFI_HOB_GUID_TYPE *MmramRangesHob; - EFI_MMRAM_HOB_DESCRIPTOR_BLOCK *MmramRangesHobData; - EFI_MMRAM_DESCRIPTOR *MmramDescriptors; + EFI_PEI_HOB_POINTERS Hob; + UINTN Count; + UINTN Index; + UINTN RangeSize; + NON_MM_MEMORY_RANGE SortBuffer; + + mValidNonMmramRanges = NULL; + mValidNonMmramCount = 0; - HobStart = GetHobList (); - DEBUG ((DEBUG_INFO, "%a - 0x%x\n", __func__, HobStart)); + Count = 0; + Index = 0; + RangeSize = 0; // - // Search for a Hob containing the MMRAM ranges + // 1. Get the count. // - MmramRangesHob = GetFirstGuidHob (&gEfiSmmSmramMemoryGuid); - if (MmramRangesHob == NULL) { - MmramRangesHob = GetFirstGuidHob (&gEfiMmPeiMmramMemoryReserveGuid); - if (MmramRangesHob == NULL) { - return EFI_UNSUPPORTED; - } + Hob.Raw = GetFirstHob (EFI_HOB_TYPE_RESOURCE_DESCRIPTOR); + while (Hob.Raw != NULL) { + Count++; + Hob.Raw = GET_NEXT_HOB (Hob); + Hob.Raw = GetNextHob (EFI_HOB_TYPE_RESOURCE_DESCRIPTOR, Hob.Raw); } - MmramRangesHobData = GET_GUID_HOB_DATA (MmramRangesHob); - if ((MmramRangesHobData == NULL) || (MmramRangesHobData->Descriptor == NULL)) { - return EFI_UNSUPPORTED; - } + // + // 2. Store the initial data. + // + RangeSize = sizeof (NON_MM_MEMORY_RANGE) * Count; + mValidNonMmramRanges = (NON_MM_MEMORY_RANGE *)AllocateZeroPool (RangeSize); + ASSERT (mValidNonMmramRanges != NULL); - mMmMemLibInternalMmramCount = MmramRangesHobData->NumberOfMmReservedRegions; - MmramDescriptors = MmramRangesHobData->Descriptor; + Hob.Raw = GetFirstHob (EFI_HOB_TYPE_RESOURCE_DESCRIPTOR); + while (Hob.Raw != NULL) { + mValidNonMmramRanges[Index].Base = Hob.ResourceDescriptor->PhysicalStart; + mValidNonMmramRanges[Index].Length = Hob.ResourceDescriptor->ResourceLength; + Index++; - mMmMemLibInternalMmramRanges = AllocatePool (mMmMemLibInternalMmramCount * sizeof (EFI_MMRAM_DESCRIPTOR)); - if (mMmMemLibInternalMmramRanges) { - CopyMem ( - mMmMemLibInternalMmramRanges, - MmramDescriptors, - mMmMemLibInternalMmramCount * sizeof (EFI_MMRAM_DESCRIPTOR) - ); + Hob.Raw = GET_NEXT_HOB (Hob); + Hob.Raw = GetNextHob (EFI_HOB_TYPE_RESOURCE_DESCRIPTOR, Hob.Raw); } - return EFI_SUCCESS; + ASSERT (Index == Count); + + // + // 3. Sort the data. + // + QuickSort (mValidNonMmramRanges, Count, sizeof (NON_MM_MEMORY_RANGE), (BASE_SORT_COMPARE)NonMmMapCompare, &SortBuffer); + + // + // 4. Merge the overlapped or continuous ranges. + // + MergeOverlappedOrContinuousRanges (mValidNonMmramRanges, &RangeSize); + mValidNonMmramCount = RangeSize/sizeof (NON_MM_MEMORY_RANGE); } /** - Deinitialize cached Mmram Ranges. + Deinitialize cached non-Mmram Ranges. **/ VOID -MmMemLibInternalFreeMmramRanges ( +MmMemLibFreeValidNonMmramRanges ( VOID ) { - if (mMmMemLibInternalMmramRanges != NULL) { - FreePool (mMmMemLibInternalMmramRanges); + if (mValidNonMmramRanges != NULL) { + FreePool (mValidNonMmramRanges); } } + +/** + This function check if the buffer is valid non-MMRAM memory range. + + @param[in] Buffer The buffer start address to be checked. + @param[in] Length The buffer length to be checked. + + @retval TRUE This buffer is valid non-MMRAM memory range. + @retval FALSE This buffer is not valid non-MMRAM memory range. +**/ +BOOLEAN +MmMemLibIsValidNonMmramRange ( + IN EFI_PHYSICAL_ADDRESS Buffer, + IN UINT64 Length + ) +{ + UINTN Index; + + for (Index = 0; Index < mValidNonMmramCount; Index++) { + if ((Buffer >= mValidNonMmramRanges[Index].Base) && + (Buffer + Length <= mValidNonMmramRanges[Index].Base + mValidNonMmramRanges[Index].Length)) + { + return TRUE; + } + } + + return FALSE; +} diff --git a/UefiCpuPkg/CpuDxeRiscV64/CpuDxe.c b/UefiCpuPkg/CpuDxeRiscV64/CpuDxe.c index c6bae100a9e4..6a22e0171108 100644 --- a/UefiCpuPkg/CpuDxeRiscV64/CpuDxe.c +++ b/UefiCpuPkg/CpuDxeRiscV64/CpuDxe.c @@ -359,6 +359,12 @@ InitializeCpu ( Status = RiscVConfigureMmu (); ASSERT_EFI_ERROR (Status); + // + // Initialize FPU + // + Status = RiscVInitializeFpu (); + ASSERT_EFI_ERROR (Status); + // // Install Boot protocol // diff --git a/UefiCpuPkg/CpuDxeRiscV64/CpuDxe.h b/UefiCpuPkg/CpuDxeRiscV64/CpuDxe.h index d4d67778eb1c..40077d65bd5a 100644 --- a/UefiCpuPkg/CpuDxeRiscV64/CpuDxe.h +++ b/UefiCpuPkg/CpuDxeRiscV64/CpuDxe.h @@ -14,6 +14,7 @@ #include #include +#include #include #include #include diff --git a/UefiCpuPkg/CpuDxeRiscV64/CpuDxeRiscV64.inf b/UefiCpuPkg/CpuDxeRiscV64/CpuDxeRiscV64.inf index 9d9a5ef8f247..cb0f71e42eb0 100644 --- a/UefiCpuPkg/CpuDxeRiscV64/CpuDxeRiscV64.inf +++ b/UefiCpuPkg/CpuDxeRiscV64/CpuDxeRiscV64.inf @@ -38,6 +38,7 @@ PeCoffGetEntryPointLib RiscVSbiLib RiscVMmuLib + RiscVFpuLib CacheMaintenanceLib [Sources] diff --git a/UefiCpuPkg/Include/Library/BaseRiscVFpuLib.h b/UefiCpuPkg/Include/Library/BaseRiscVFpuLib.h new file mode 100644 index 000000000000..d75320ff744f --- /dev/null +++ b/UefiCpuPkg/Include/Library/BaseRiscVFpuLib.h @@ -0,0 +1,21 @@ +/** @file + + Copyright (c) 2024, Canonical Services Ltd
+ SPDX-License-Identifier: BSD-2-Clause-Patent + +**/ + +#ifndef BASE_RISCV_FPU_LIB_H_ +#define BASE_RISCV_FPU_LIB_H_ + +/** + Initialize floating point unit + +**/ +EFI_STATUS +EFIAPI +RiscVInitializeFpu ( + VOID + ); + +#endif /* BASE_RISCV_FPU_LIB_H_ */ diff --git a/UefiCpuPkg/Include/Library/SmmCpuPlatformHookLib.h b/UefiCpuPkg/Include/Library/SmmCpuPlatformHookLib.h index f9cc3f7249e8..149a6948915a 100644 --- a/UefiCpuPkg/Include/Library/SmmCpuPlatformHookLib.h +++ b/UefiCpuPkg/Include/Library/SmmCpuPlatformHookLib.h @@ -1,7 +1,7 @@ /** @file Public include file for the SMM CPU Platform Hook Library. - Copyright (c) 2010 - 2015, Intel Corporation. All rights reserved.
+ Copyright (c) 2010 - 2024, Intel Corporation. All rights reserved.
SPDX-License-Identifier: BSD-2-Clause-Patent **/ @@ -100,4 +100,19 @@ GetPlatformPageTableAttribute ( OUT UINTN *PageAttribute ); +/** + SMM CPU Platform Hook before executing MMI Handler. + + This function can be used to perform the platform specific items before executing MMI Handler. + + @retval EFI_SUCCESS The smm cpu platform hook before executing MMI Handler is executed successfully. + @retval EFI_UNSUPPORTED The smm cpu platform hook before executing MMI Handler is unsupported. + +**/ +EFI_STATUS +EFIAPI +SmmCpuPlatformHookBeforeMmiHandler ( + VOID + ); + #endif diff --git a/UefiCpuPkg/Library/BaseRiscVFpuLib/BaseRiscVFpuLib.inf b/UefiCpuPkg/Library/BaseRiscVFpuLib/BaseRiscVFpuLib.inf new file mode 100644 index 000000000000..81304303100e --- /dev/null +++ b/UefiCpuPkg/Library/BaseRiscVFpuLib/BaseRiscVFpuLib.inf @@ -0,0 +1,26 @@ +## @file +# RISC-V FPU library. +# +# Copyright (c) 2024, Canonical Services Ltd +# +# SPDX-License-Identifier: BSD-2-Clause-Patent +# +## + +[Defines] + INF_VERSION = 0x0001001b + BASE_NAME = BaseRiscVFpuLib + FILE_GUID = e600fe4d-8595-40f3-90a0-5f043ce155c2 + MODULE_TYPE = BASE + VERSION_STRING = 1.0 + LIBRARY_CLASS = RiscVFpuLib + +[Sources] + RiscVFpuCore.S + +[Packages] + MdePkg/MdePkg.dec + UefiCpuPkg/UefiCpuPkg.dec + +[LibraryClasses] + BaseLib diff --git a/UefiCpuPkg/Library/BaseRiscVFpuLib/RiscVFpuCore.S b/UefiCpuPkg/Library/BaseRiscVFpuLib/RiscVFpuCore.S new file mode 100644 index 000000000000..b439af4e42cd --- /dev/null +++ b/UefiCpuPkg/Library/BaseRiscVFpuLib/RiscVFpuCore.S @@ -0,0 +1,22 @@ +/** @file +* +* Copyright (c) 2024, Canonical Services Ltd +* +* SPDX-License-Identifier: BSD-2-Clause-Patent +* +**/ + +#include +#include + +// +// Initialize floating point unit +// +ASM_FUNC (RiscVInitializeFpu) + csrr a0, CSR_SSTATUS + li a1, MSTATUS_FS + or a0, a0, a1 + csrw CSR_SSTATUS, a0 + csrw CSR_FCSR, x0 + li a0, 0 + ret diff --git a/UefiCpuPkg/Library/MmSaveStateLib/AmdMmSaveState.c b/UefiCpuPkg/Library/MmSaveStateLib/AmdMmSaveState.c index 3315a6cc44ff..f9485b7cd87c 100644 --- a/UefiCpuPkg/Library/MmSaveStateLib/AmdMmSaveState.c +++ b/UefiCpuPkg/Library/MmSaveStateLib/AmdMmSaveState.c @@ -2,7 +2,7 @@ Provides services to access SMRAM Save State Map Copyright (c) 2010 - 2019, Intel Corporation. All rights reserved.
-Copyright (C) 2023 Advanced Micro Devices, Inc. All rights reserved.
+Copyright (C) 2023 - 2024 Advanced Micro Devices, Inc. All rights reserved.
SPDX-License-Identifier: BSD-2-Clause-Patent **/ @@ -20,59 +20,66 @@ SPDX-License-Identifier: BSD-2-Clause-Patent // Macro used to simplify the lookup table entries of type CPU_MM_SAVE_STATE_LOOKUP_ENTRY #define MM_CPU_OFFSET(Field) OFFSET_OF (AMD_SMRAM_SAVE_STATE_MAP, Field) +// // Lookup table used to retrieve the widths and offsets associated with each // supported EFI_MM_SAVE_STATE_REGISTER value +// +// Per AMD64 Architecture Programmer's Manual Volume 2: System +// Programming - 10.2.3 SMRAM State-Save Area (Rev 24593), the AMD64 +// architecture does not use the legacy SMM state-save area format +// (Table 10-2) for 32-bit SMRAM Save State Map. +// CONST CPU_MM_SAVE_STATE_LOOKUP_ENTRY mCpuWidthOffset[] = { - { 0, 0, 0, 0, FALSE }, // Reserved + { 0, 0, 0, 0, 0, FALSE }, // Reserved // // Internally defined CPU Save State Registers. Not defined in PI SMM CPU Protocol. // - { 4, 4, MM_CPU_OFFSET (x86.SMMRevId), MM_CPU_OFFSET (x64.SMMRevId), 0, FALSE}, // AMD_MM_SAVE_STATE_REGISTER_SMMREVID_INDEX = 1 + { 0, 4, 0, MM_CPU_OFFSET (x64.SMMRevId), 0, FALSE }, // AMD_MM_SAVE_STATE_REGISTER_SMMREVID_INDEX = 1 // // CPU Save State registers defined in PI SMM CPU Protocol. // - { 4, 8, MM_CPU_OFFSET (x86.GDTBase), MM_CPU_OFFSET (x64._GDTRBaseLoDword), MM_CPU_OFFSET (x64._GDTRBaseHiDword), FALSE}, // EFI_MM_SAVE_STATE_REGISTER_GDTBASE = 4 - { 0, 8, 0, MM_CPU_OFFSET (x64._IDTRBaseLoDword), MM_CPU_OFFSET (x64._IDTRBaseLoDword), FALSE}, // EFI_MM_SAVE_STATE_REGISTER_IDTBASE = 5 - { 0, 8, 0, MM_CPU_OFFSET (x64._LDTRBaseLoDword), MM_CPU_OFFSET (x64._LDTRBaseLoDword), FALSE}, // EFI_MM_SAVE_STATE_REGISTER_LDTBASE = 6 - { 0, 2, 0, MM_CPU_OFFSET (x64._GDTRLimit), 0, FALSE}, // EFI_MM_SAVE_STATE_REGISTER_GDTLIMIT = 7 - { 0, 2, 0, MM_CPU_OFFSET (x64._IDTRLimit), 0, FALSE}, // EFI_MM_SAVE_STATE_REGISTER_IDTLIMIT = 8 - { 0, 4, 0, MM_CPU_OFFSET (x64._LDTRLimit), 0, FALSE}, // EFI_MM_SAVE_STATE_REGISTER_LDTLIMIT = 9 - { 0, 0, 0, 0, 0, FALSE}, // EFI_MM_SAVE_STATE_REGISTER_LDTINFO = 10 - { 4, 2, MM_CPU_OFFSET (x86._ES), MM_CPU_OFFSET (x64._ES), 0, FALSE}, // EFI_MM_SAVE_STATE_REGISTER_ES = 20 - { 4, 2, MM_CPU_OFFSET (x86._CS), MM_CPU_OFFSET (x64._CS), 0, FALSE}, // EFI_MM_SAVE_STATE_REGISTER_CS = 21 - { 4, 2, MM_CPU_OFFSET (x86._SS), MM_CPU_OFFSET (x64._SS), 0, FALSE}, // EFI_MM_SAVE_STATE_REGISTER_SS = 22 - { 4, 2, MM_CPU_OFFSET (x86._DS), MM_CPU_OFFSET (x64._DS), 0, FALSE}, // EFI_MM_SAVE_STATE_REGISTER_DS = 23 - { 4, 2, MM_CPU_OFFSET (x86._FS), MM_CPU_OFFSET (x64._FS), 0, FALSE}, // EFI_MM_SAVE_STATE_REGISTER_FS = 24 - { 4, 2, MM_CPU_OFFSET (x86._GS), MM_CPU_OFFSET (x64._GS), 0, FALSE}, // EFI_MM_SAVE_STATE_REGISTER_GS = 25 - { 0, 2, 0, MM_CPU_OFFSET (x64._LDTR), 0, FALSE}, // EFI_MM_SAVE_STATE_REGISTER_LDTR_SEL = 26 - { 0, 2, 0, MM_CPU_OFFSET (x64._TR), 0, FALSE}, // EFI_MM_SAVE_STATE_REGISTER_TR_SEL = 27 - { 4, 8, MM_CPU_OFFSET (x86._DR7), MM_CPU_OFFSET (x64._DR7), MM_CPU_OFFSET (x64._DR7) + 4, FALSE}, // EFI_MM_SAVE_STATE_REGISTER_DR7 = 28 - { 4, 8, MM_CPU_OFFSET (x86._DR6), MM_CPU_OFFSET (x64._DR6), MM_CPU_OFFSET (x64._DR6) + 4, FALSE}, // EFI_MM_SAVE_STATE_REGISTER_DR6 = 29 - { 0, 8, 0, MM_CPU_OFFSET (x64._R8), MM_CPU_OFFSET (x64._R8) + 4, TRUE}, // EFI_MM_SAVE_STATE_REGISTER_R8 = 30 - { 0, 8, 0, MM_CPU_OFFSET (x64._R9), MM_CPU_OFFSET (x64._R9) + 4, TRUE}, // EFI_MM_SAVE_STATE_REGISTER_R9 = 31 - { 0, 8, 0, MM_CPU_OFFSET (x64._R10), MM_CPU_OFFSET (x64._R10) + 4, TRUE}, // EFI_MM_SAVE_STATE_REGISTER_R10 = 32 - { 0, 8, 0, MM_CPU_OFFSET (x64._R11), MM_CPU_OFFSET (x64._R11) + 4, TRUE}, // EFI_MM_SAVE_STATE_REGISTER_R11 = 33 - { 0, 8, 0, MM_CPU_OFFSET (x64._R12), MM_CPU_OFFSET (x64._R12) + 4, TRUE}, // EFI_MM_SAVE_STATE_REGISTER_R12 = 34 - { 0, 8, 0, MM_CPU_OFFSET (x64._R13), MM_CPU_OFFSET (x64._R13) + 4, TRUE}, // EFI_MM_SAVE_STATE_REGISTER_R13 = 35 - { 0, 8, 0, MM_CPU_OFFSET (x64._R14), MM_CPU_OFFSET (x64._R14) + 4, TRUE}, // EFI_MM_SAVE_STATE_REGISTER_R14 = 36 - { 0, 8, 0, MM_CPU_OFFSET (x64._R15), MM_CPU_OFFSET (x64._R15) + 4, TRUE}, // EFI_MM_SAVE_STATE_REGISTER_R15 = 37 - { 4, 8, MM_CPU_OFFSET (x86._EAX), MM_CPU_OFFSET (x64._RAX), MM_CPU_OFFSET (x64._RAX) + 4, TRUE}, // EFI_MM_SAVE_STATE_REGISTER_RAX = 38 - { 4, 8, MM_CPU_OFFSET (x86._EBX), MM_CPU_OFFSET (x64._RBX), MM_CPU_OFFSET (x64._RBX) + 4, TRUE}, // EFI_MM_SAVE_STATE_REGISTER_RBX = 39 - { 4, 8, MM_CPU_OFFSET (x86._ECX), MM_CPU_OFFSET (x64._RCX), MM_CPU_OFFSET (x64._RCX) + 4, TRUE}, // EFI_MM_SAVE_STATE_REGISTER_RBX = 39 - { 4, 8, MM_CPU_OFFSET (x86._EDX), MM_CPU_OFFSET (x64._RDX), MM_CPU_OFFSET (x64._RDX) + 4, TRUE}, // EFI_MM_SAVE_STATE_REGISTER_RDX = 41 - { 4, 8, MM_CPU_OFFSET (x86._ESP), MM_CPU_OFFSET (x64._RSP), MM_CPU_OFFSET (x64._RSP) + 4, TRUE}, // EFI_MM_SAVE_STATE_REGISTER_RSP = 42 - { 4, 8, MM_CPU_OFFSET (x86._EBP), MM_CPU_OFFSET (x64._RBP), MM_CPU_OFFSET (x64._RBP) + 4, TRUE}, // EFI_MM_SAVE_STATE_REGISTER_RBP = 43 - { 4, 8, MM_CPU_OFFSET (x86._ESI), MM_CPU_OFFSET (x64._RSI), MM_CPU_OFFSET (x64._RSI) + 4, TRUE}, // EFI_MM_SAVE_STATE_REGISTER_RSI = 44 - { 4, 8, MM_CPU_OFFSET (x86._EDI), MM_CPU_OFFSET (x64._RDI), MM_CPU_OFFSET (x64._RDI) + 4, TRUE}, // EFI_MM_SAVE_STATE_REGISTER_RDI = 45 - { 4, 8, MM_CPU_OFFSET (x86._EIP), MM_CPU_OFFSET (x64._RIP), MM_CPU_OFFSET (x64._RIP) + 4, TRUE}, // EFI_MM_SAVE_STATE_REGISTER_RIP = 46 - - { 4, 8, MM_CPU_OFFSET (x86._EFLAGS), MM_CPU_OFFSET (x64._RFLAGS), MM_CPU_OFFSET (x64._RFLAGS) + 4, TRUE}, // EFI_MM_SAVE_STATE_REGISTER_RFLAGS = 51 - { 4, 8, MM_CPU_OFFSET (x86._CR0), MM_CPU_OFFSET (x64._CR0), MM_CPU_OFFSET (x64._CR0) + 4, FALSE}, // EFI_MM_SAVE_STATE_REGISTER_CR0 = 52 - { 4, 8, MM_CPU_OFFSET (x86._CR3), MM_CPU_OFFSET (x64._CR3), MM_CPU_OFFSET (x64._CR3) + 4, FALSE}, // EFI_MM_SAVE_STATE_REGISTER_CR3 = 53 - { 0, 8, 0, MM_CPU_OFFSET (x64._CR4), MM_CPU_OFFSET (x64._CR4) + 4, FALSE}, // EFI_MM_SAVE_STATE_REGISTER_CR4 = 54 - { 0, 0, 0, 0, 0 } + { 0, 8, 0, MM_CPU_OFFSET (x64._GDTRBaseLoDword), MM_CPU_OFFSET (x64._GDTRBaseHiDword), FALSE }, // EFI_MM_SAVE_STATE_REGISTER_GDTBASE = 4 + { 0, 8, 0, MM_CPU_OFFSET (x64._IDTRBaseLoDword), MM_CPU_OFFSET (x64._IDTRBaseLoDword), FALSE }, // EFI_MM_SAVE_STATE_REGISTER_IDTBASE = 5 + { 0, 8, 0, MM_CPU_OFFSET (x64._LDTRBaseLoDword), MM_CPU_OFFSET (x64._LDTRBaseLoDword), FALSE }, // EFI_MM_SAVE_STATE_REGISTER_LDTBASE = 6 + { 0, 2, 0, MM_CPU_OFFSET (x64._GDTRLimit), 0, FALSE }, // EFI_MM_SAVE_STATE_REGISTER_GDTLIMIT = 7 + { 0, 2, 0, MM_CPU_OFFSET (x64._IDTRLimit), 0, FALSE }, // EFI_MM_SAVE_STATE_REGISTER_IDTLIMIT = 8 + { 0, 4, 0, MM_CPU_OFFSET (x64._LDTRLimit), 0, FALSE }, // EFI_MM_SAVE_STATE_REGISTER_LDTLIMIT = 9 + { 0, 0, 0, 0, 0, FALSE }, // EFI_MM_SAVE_STATE_REGISTER_LDTINFO = 10 + { 0, 2, 0, MM_CPU_OFFSET (x64._ES), 0, FALSE }, // EFI_MM_SAVE_STATE_REGISTER_ES = 20 + { 0, 2, 0, MM_CPU_OFFSET (x64._CS), 0, FALSE }, // EFI_MM_SAVE_STATE_REGISTER_CS = 21 + { 0, 2, 0, MM_CPU_OFFSET (x64._SS), 0, FALSE }, // EFI_MM_SAVE_STATE_REGISTER_SS = 22 + { 0, 2, 0, MM_CPU_OFFSET (x64._DS), 0, FALSE }, // EFI_MM_SAVE_STATE_REGISTER_DS = 23 + { 0, 2, 0, MM_CPU_OFFSET (x64._FS), 0, FALSE }, // EFI_MM_SAVE_STATE_REGISTER_FS = 24 + { 0, 2, 0, MM_CPU_OFFSET (x64._GS), 0, FALSE }, // EFI_MM_SAVE_STATE_REGISTER_GS = 25 + { 0, 2, 0, MM_CPU_OFFSET (x64._LDTR), 0, FALSE }, // EFI_MM_SAVE_STATE_REGISTER_LDTR_SEL = 26 + { 0, 2, 0, MM_CPU_OFFSET (x64._TR), 0, FALSE }, // EFI_MM_SAVE_STATE_REGISTER_TR_SEL = 27 + { 0, 8, 0, MM_CPU_OFFSET (x64._DR7), MM_CPU_OFFSET (x64._DR7) + 4, FALSE }, // EFI_MM_SAVE_STATE_REGISTER_DR7 = 28 + { 0, 8, 0, MM_CPU_OFFSET (x64._DR6), MM_CPU_OFFSET (x64._DR6) + 4, FALSE }, // EFI_MM_SAVE_STATE_REGISTER_DR6 = 29 + { 0, 8, 0, MM_CPU_OFFSET (x64._R8), MM_CPU_OFFSET (x64._R8) + 4, TRUE }, // EFI_MM_SAVE_STATE_REGISTER_R8 = 30 + { 0, 8, 0, MM_CPU_OFFSET (x64._R9), MM_CPU_OFFSET (x64._R9) + 4, TRUE }, // EFI_MM_SAVE_STATE_REGISTER_R9 = 31 + { 0, 8, 0, MM_CPU_OFFSET (x64._R10), MM_CPU_OFFSET (x64._R10) + 4, TRUE }, // EFI_MM_SAVE_STATE_REGISTER_R10 = 32 + { 0, 8, 0, MM_CPU_OFFSET (x64._R11), MM_CPU_OFFSET (x64._R11) + 4, TRUE }, // EFI_MM_SAVE_STATE_REGISTER_R11 = 33 + { 0, 8, 0, MM_CPU_OFFSET (x64._R12), MM_CPU_OFFSET (x64._R12) + 4, TRUE }, // EFI_MM_SAVE_STATE_REGISTER_R12 = 34 + { 0, 8, 0, MM_CPU_OFFSET (x64._R13), MM_CPU_OFFSET (x64._R13) + 4, TRUE }, // EFI_MM_SAVE_STATE_REGISTER_R13 = 35 + { 0, 8, 0, MM_CPU_OFFSET (x64._R14), MM_CPU_OFFSET (x64._R14) + 4, TRUE }, // EFI_MM_SAVE_STATE_REGISTER_R14 = 36 + { 0, 8, 0, MM_CPU_OFFSET (x64._R15), MM_CPU_OFFSET (x64._R15) + 4, TRUE }, // EFI_MM_SAVE_STATE_REGISTER_R15 = 37 + { 0, 8, 0, MM_CPU_OFFSET (x64._RAX), MM_CPU_OFFSET (x64._RAX) + 4, TRUE }, // EFI_MM_SAVE_STATE_REGISTER_RAX = 38 + { 0, 8, 0, MM_CPU_OFFSET (x64._RBX), MM_CPU_OFFSET (x64._RBX) + 4, TRUE }, // EFI_MM_SAVE_STATE_REGISTER_RBX = 39 + { 0, 8, 0, MM_CPU_OFFSET (x64._RCX), MM_CPU_OFFSET (x64._RCX) + 4, TRUE }, // EFI_MM_SAVE_STATE_REGISTER_RBX = 39 + { 0, 8, 0, MM_CPU_OFFSET (x64._RDX), MM_CPU_OFFSET (x64._RDX) + 4, TRUE }, // EFI_MM_SAVE_STATE_REGISTER_RDX = 41 + { 0, 8, 0, MM_CPU_OFFSET (x64._RSP), MM_CPU_OFFSET (x64._RSP) + 4, TRUE }, // EFI_MM_SAVE_STATE_REGISTER_RSP = 42 + { 0, 8, 0, MM_CPU_OFFSET (x64._RBP), MM_CPU_OFFSET (x64._RBP) + 4, TRUE }, // EFI_MM_SAVE_STATE_REGISTER_RBP = 43 + { 0, 8, 0, MM_CPU_OFFSET (x64._RSI), MM_CPU_OFFSET (x64._RSI) + 4, TRUE }, // EFI_MM_SAVE_STATE_REGISTER_RSI = 44 + { 0, 8, 0, MM_CPU_OFFSET (x64._RDI), MM_CPU_OFFSET (x64._RDI) + 4, TRUE }, // EFI_MM_SAVE_STATE_REGISTER_RDI = 45 + { 0, 8, 0, MM_CPU_OFFSET (x64._RIP), MM_CPU_OFFSET (x64._RIP) + 4, TRUE }, // EFI_MM_SAVE_STATE_REGISTER_RIP = 46 + + { 0, 8, 0, MM_CPU_OFFSET (x64._RFLAGS), MM_CPU_OFFSET (x64._RFLAGS) + 4, TRUE }, // EFI_MM_SAVE_STATE_REGISTER_RFLAGS = 51 + { 0, 8, 0, MM_CPU_OFFSET (x64._CR0), MM_CPU_OFFSET (x64._CR0) + 4, FALSE }, // EFI_MM_SAVE_STATE_REGISTER_CR0 = 52 + { 0, 8, 0, MM_CPU_OFFSET (x64._CR3), MM_CPU_OFFSET (x64._CR3) + 4, FALSE }, // EFI_MM_SAVE_STATE_REGISTER_CR3 = 53 + { 0, 8, 0, MM_CPU_OFFSET (x64._CR4), MM_CPU_OFFSET (x64._CR4) + 4, FALSE }, // EFI_MM_SAVE_STATE_REGISTER_CR4 = 54 + { 0, 0, 0, 0, 0, FALSE } }; /** @@ -236,53 +243,28 @@ MmSaveStateWriteRegister ( } // - // Check CPU mode + // If 64-bit mode width is zero, then the specified register can not be accessed // - if (MmSaveStateGetRegisterLma () == EFI_MM_SAVE_STATE_REGISTER_LMA_32BIT) { - // - // If 32-bit mode width is zero, then the specified register can not be accessed - // - if (mCpuWidthOffset[RegisterIndex].Width32 == 0) { - return EFI_NOT_FOUND; - } - - // - // If Width is bigger than the 32-bit mode width, then the specified register can not be accessed - // - if (Width > mCpuWidthOffset[RegisterIndex].Width32) { - return EFI_INVALID_PARAMETER; - } - - // - // Write SMM State register - // - ASSERT (CpuSaveState != NULL); - CopyMem ((UINT8 *)CpuSaveState + mCpuWidthOffset[RegisterIndex].Offset32, Buffer, Width); - } else { - // - // If 64-bit mode width is zero, then the specified register can not be accessed - // - if (mCpuWidthOffset[RegisterIndex].Width64 == 0) { - return EFI_NOT_FOUND; - } + if (mCpuWidthOffset[RegisterIndex].Width64 == 0) { + return EFI_NOT_FOUND; + } - // - // If Width is bigger than the 64-bit mode width, then the specified register can not be accessed - // - if (Width > mCpuWidthOffset[RegisterIndex].Width64) { - return EFI_INVALID_PARAMETER; - } + // + // If Width is bigger than the 64-bit mode width, then the specified register can not be accessed + // + if (Width > mCpuWidthOffset[RegisterIndex].Width64) { + return EFI_INVALID_PARAMETER; + } + // + // Write lower 32-bits of SMM State register + // + CopyMem ((UINT8 *)CpuSaveState + mCpuWidthOffset[RegisterIndex].Offset64Lo, Buffer, MIN (4, Width)); + if (Width >= 4) { // - // Write lower 32-bits of SMM State register + // Write upper 32-bits of SMM State register // - CopyMem ((UINT8 *)CpuSaveState + mCpuWidthOffset[RegisterIndex].Offset64Lo, Buffer, MIN (4, Width)); - if (Width >= 4) { - // - // Write upper 32-bits of SMM State register - // - CopyMem ((UINT8 *)CpuSaveState + mCpuWidthOffset[RegisterIndex].Offset64Hi, (UINT8 *)Buffer + 4, Width - 4); - } + CopyMem ((UINT8 *)CpuSaveState + mCpuWidthOffset[RegisterIndex].Offset64Hi, (UINT8 *)Buffer + 4, Width - 4); } return EFI_SUCCESS; @@ -298,12 +280,8 @@ MmSaveStateGetRegisterLma ( VOID ) { - UINT32 LMAValue; - - LMAValue = (UINT32)AsmReadMsr64 (EFER_ADDRESS) & LMA; - if (LMAValue) { - return EFI_MM_SAVE_STATE_REGISTER_LMA_64BIT; - } - - return EFI_MM_SAVE_STATE_REGISTER_LMA_32BIT; + // + // AMD64 processors support EFI_SMM_SAVE_STATE_REGISTER_LMA_64BIT only + // + return EFI_MM_SAVE_STATE_REGISTER_LMA_64BIT; } diff --git a/UefiCpuPkg/Library/MmUnblockMemoryLib/MmUnblockMemoryLib.c b/UefiCpuPkg/Library/MmUnblockMemoryLib/MmUnblockMemoryLib.c index 790392b19d0d..c42ca106ebdb 100644 --- a/UefiCpuPkg/Library/MmUnblockMemoryLib/MmUnblockMemoryLib.c +++ b/UefiCpuPkg/Library/MmUnblockMemoryLib/MmUnblockMemoryLib.c @@ -18,6 +18,85 @@ #include #include #include +#include + +/** + This function checks if the input buffer range [UnblockBase, UnblockEnd] is unblockable. + The input range should be covered by the EfiRuntimeServicesData, EfiACPIMemoryNVS or + EfiReservedMemoryType memory allocation HOB. + + @param[in] HobStart The starting HOB pointer to search from. + @param[in] UnblockAddress Base address of the range to unblock. + @param[in] UnblockEnd End address of the range to unblock. + + @retval RETURN_SUCCESS The range is unblockable. + @retval RETURN_INVALID_PARAMETER The range to unblock contains invalid memory. +**/ +EFI_STATUS +MmUnblockMemoryLibIsUnblockableRegion ( + IN VOID *HobStart, + IN EFI_PHYSICAL_ADDRESS UnblockBase, + IN EFI_PHYSICAL_ADDRESS UnblockEnd + ) +{ + EFI_PHYSICAL_ADDRESS HobBase; + EFI_PHYSICAL_ADDRESS HobEnd; + EFI_STATUS Status; + EFI_HOB_MEMORY_ALLOCATION *MemoryAllocationHob; + + while ((MemoryAllocationHob = GetNextHob (EFI_HOB_TYPE_MEMORY_ALLOCATION, HobStart)) != NULL) { + HobBase = MemoryAllocationHob->AllocDescriptor.MemoryBaseAddress; + HobEnd = MemoryAllocationHob->AllocDescriptor.MemoryBaseAddress + + MemoryAllocationHob->AllocDescriptor.MemoryLength; + if ((UnblockBase < HobEnd) && (UnblockEnd > HobBase)) { + // + // The overlapped memory allocation HOB type must be one of the three specific types. + // + if ((MemoryAllocationHob->AllocDescriptor.MemoryType != EfiRuntimeServicesData) && + (MemoryAllocationHob->AllocDescriptor.MemoryType != EfiACPIMemoryNVS) && + (MemoryAllocationHob->AllocDescriptor.MemoryType != EfiReservedMemoryType)) + { + DEBUG ((DEBUG_ERROR, "Error: range [0x%lx, 0x%lx] to unblock contains invalid type memory\n", UnblockBase, UnblockEnd)); + return RETURN_INVALID_PARAMETER; + } + + if (UnblockBase < HobBase) { + // + // Recursively call to check [UnblockBase, HobBase] + // + Status = MmUnblockMemoryLibIsUnblockableRegion ( + GET_NEXT_HOB (MemoryAllocationHob), + UnblockBase, + HobBase + ); + if (EFI_ERROR (Status)) { + return Status; + } + } + + if (UnblockEnd > HobEnd) { + // + // Recursively call to check [HobEnd, UnblockEnd] + // + Status = MmUnblockMemoryLibIsUnblockableRegion ( + GET_NEXT_HOB (MemoryAllocationHob), + HobEnd, + UnblockEnd + ); + if (EFI_ERROR (Status)) { + return Status; + } + } + + return EFI_SUCCESS; + } + + HobStart = GET_NEXT_HOB (MemoryAllocationHob); + } + + DEBUG ((DEBUG_ERROR, "Error: range [0x%lx, 0x%lx] to unblock doesn't belong to any memory allocation HOB\n", UnblockBase, UnblockEnd)); + return RETURN_INVALID_PARAMETER; +} /** This API provides a way to unblock certain data pages to be accessible inside MM environment. @@ -32,6 +111,10 @@ @retval RETURN_SECURITY_VIOLATION The requested address failed to pass security check for unblocking. @retval RETURN_INVALID_PARAMETER Input address either NULL pointer or not page aligned. + @retval RETURN_INVALID_PARAMETER Input range to unblock contains invalid types memory other than + EfiRuntimeServicesData, EfiACPIMemoryNVS, and EfiReservedMemory. + @retval RETURN_INVALID_PARAMETER Input range to unblock contains memory that doesn't belong to + any memory allocation HOB. @retval RETURN_ACCESS_DENIED The request is rejected due to system has passed certain boot phase. **/ @@ -45,12 +128,19 @@ MmUnblockMemoryRequest ( EFI_STATUS Status; MM_UNBLOCK_REGION *MmUnblockMemoryHob; EFI_PEI_MM_COMMUNICATION_PPI *MmCommunicationPpi; + VOID *HobList; if (!IS_ALIGNED (UnblockAddress, SIZE_4KB)) { DEBUG ((DEBUG_ERROR, "Error: UnblockAddress is not 4KB aligned: %p\n", UnblockAddress)); return EFI_INVALID_PARAMETER; } + HobList = GetHobList (); + Status = MmUnblockMemoryLibIsUnblockableRegion (HobList, UnblockAddress, UnblockAddress + EFI_PAGES_TO_SIZE (NumberOfPages)); + if (EFI_ERROR (Status)) { + return Status; + } + // // Unblock requests are rejected when MmIpl finishes execution. // diff --git a/UefiCpuPkg/Library/MpInitLib/PeiMpInitLib.inf b/UefiCpuPkg/Library/MpInitLib/PeiMpInitLib.inf index e4a7485fefd3..d2b6a43cdc14 100644 --- a/UefiCpuPkg/Library/MpInitLib/PeiMpInitLib.inf +++ b/UefiCpuPkg/Library/MpInitLib/PeiMpInitLib.inf @@ -87,7 +87,6 @@ gEdkiiPeiShadowMicrocodePpiGuid ## SOMETIMES_CONSUMES [Guids] - gEdkiiS3SmmInitDoneGuid gEdkiiMicrocodePatchHobGuid gGhcbApicIdsGuid ## SOMETIMES_CONSUMES gEdkiiEndOfS3ResumeGuid diff --git a/UefiCpuPkg/Library/MpInitLib/PeiMpLib.c b/UefiCpuPkg/Library/MpInitLib/PeiMpLib.c index 16a858d54259..495dc108b232 100644 --- a/UefiCpuPkg/Library/MpInitLib/PeiMpLib.c +++ b/UefiCpuPkg/Library/MpInitLib/PeiMpLib.c @@ -14,68 +14,6 @@ STATIC UINT64 mSevEsPeiWakeupBuffer = BASE_1MB; -/** - S3 SMM Init Done notification function. - - @param PeiServices Indirect reference to the PEI Services Table. - @param NotifyDesc Address of the notification descriptor data structure. - @param InvokePpi Address of the PPI that was invoked. - - @retval EFI_SUCCESS The function completes successfully. - -**/ -EFI_STATUS -EFIAPI -NotifyOnS3SmmInitDonePpi ( - IN EFI_PEI_SERVICES **PeiServices, - IN EFI_PEI_NOTIFY_DESCRIPTOR *NotifyDesc, - IN VOID *InvokePpi - ); - -// -// Global function -// -EFI_PEI_NOTIFY_DESCRIPTOR mS3SmmInitDoneNotifyDesc = { - EFI_PEI_PPI_DESCRIPTOR_NOTIFY_CALLBACK | EFI_PEI_PPI_DESCRIPTOR_TERMINATE_LIST, - &gEdkiiS3SmmInitDoneGuid, - NotifyOnS3SmmInitDonePpi -}; - -/** - S3 SMM Init Done notification function. - - @param PeiServices Indirect reference to the PEI Services Table. - @param NotifyDesc Address of the notification descriptor data structure. - @param InvokePpi Address of the PPI that was invoked. - - @retval EFI_SUCCESS The function completes successfully. - -**/ -EFI_STATUS -EFIAPI -NotifyOnS3SmmInitDonePpi ( - IN EFI_PEI_SERVICES **PeiServices, - IN EFI_PEI_NOTIFY_DESCRIPTOR *NotifyDesc, - IN VOID *InvokePpi - ) -{ - CPU_MP_DATA *CpuMpData; - - CpuMpData = GetCpuMpData (); - - // - // PiSmmCpuDxeSmm driver hardcode change the loop mode to HLT mode. - // So in this notify function, code need to check the current loop - // mode, if it is not HLT mode, code need to change loop mode back - // to the original mode. - // - if (CpuMpData->ApLoopMode != ApInHltLoop) { - CpuMpData->WakeUpByInitSipiSipi = TRUE; - } - - return EFI_SUCCESS; -} - /** Enable Debug Agent to support source debugging on AP function. @@ -510,8 +448,6 @@ InitMpGlobalData ( /// /// Install Notify /// - Status = PeiServicesNotifyPpi (&mS3SmmInitDoneNotifyDesc); - ASSERT_EFI_ERROR (Status); Status = PeiServicesNotifyPpi (&mEndOfS3ResumeNotifyDesc); ASSERT_EFI_ERROR (Status); diff --git a/UefiCpuPkg/Library/MtrrLib/UnitTest/Support.c b/UefiCpuPkg/Library/MtrrLib/UnitTest/Support.c index 7df5b9745f90..ef3016db8322 100644 --- a/UefiCpuPkg/Library/MtrrLib/UnitTest/Support.c +++ b/UefiCpuPkg/Library/MtrrLib/UnitTest/Support.c @@ -745,7 +745,7 @@ GetNextDifferentElementInSortedArray ( UINT64 CurrentElement; CurrentElement = Array[Index]; - while (CurrentElement == Array[Index] && Index < Count) { + while ((Index < Count) && (CurrentElement == Array[Index])) { Index++; } diff --git a/UefiCpuPkg/Library/SmmCpuFeaturesLib/AmdSmmCpuFeaturesLib.c b/UefiCpuPkg/Library/SmmCpuFeaturesLib/AmdSmmCpuFeaturesLib.c index a424532aaa58..561f578b015e 100644 --- a/UefiCpuPkg/Library/SmmCpuFeaturesLib/AmdSmmCpuFeaturesLib.c +++ b/UefiCpuPkg/Library/SmmCpuFeaturesLib/AmdSmmCpuFeaturesLib.c @@ -47,13 +47,10 @@ CpuFeaturesLibInitialization ( VOID ) { - UINT32 LMAValue; - - LMAValue = (UINT32)AsmReadMsr64 (EFER_ADDRESS) & LMA; - mSmmSaveStateRegisterLma = EFI_SMM_SAVE_STATE_REGISTER_LMA_32BIT; - if (LMAValue) { - mSmmSaveStateRegisterLma = EFI_SMM_SAVE_STATE_REGISTER_LMA_64BIT; - } + // + // AMD64 processors support EFI_SMM_SAVE_STATE_REGISTER_LMA_64BIT only + // + mSmmSaveStateRegisterLma = EFI_SMM_SAVE_STATE_REGISTER_LMA_64BIT; // // If gSmmBaseHobGuid found, means SmBase info has been relocated and recorded @@ -96,7 +93,6 @@ SmmCpuFeaturesInitializeProcessor ( ) { AMD_SMRAM_SAVE_STATE_MAP *CpuState; - UINT32 LMAValue; // // No need to configure SMBASE if SmBase relocation has been done. @@ -109,14 +105,6 @@ SmmCpuFeaturesInitializeProcessor ( CpuState->x64.SMBASE = (UINT32)CpuHotPlugData->SmBase[CpuIndex]; } - // Re-initialize the value of mSmmSaveStateRegisterLma flag which might have been changed in PiCpuSmmDxeSmm Driver - // Entry point, to make sure correct value on AMD platform is assigned to be used by SmmCpuFeaturesLib. - LMAValue = (UINT32)AsmReadMsr64 (EFER_ADDRESS) & LMA; - mSmmSaveStateRegisterLma = EFI_SMM_SAVE_STATE_REGISTER_LMA_32BIT; - if (LMAValue) { - mSmmSaveStateRegisterLma = EFI_SMM_SAVE_STATE_REGISTER_LMA_64BIT; - } - // // If SMRR is supported, then program SMRR base/mask MSRs. // The EFI_MSR_SMRR_PHYS_MASK_VALID bit is not set until the first normal SMI. @@ -193,31 +181,20 @@ SmmCpuFeaturesHookReturnFromSmm ( AmdCpuState = (AMD_SMRAM_SAVE_STATE_MAP *)CpuState; - if (mSmmSaveStateRegisterLma == EFI_SMM_SAVE_STATE_REGISTER_LMA_32BIT) { - OriginalInstructionPointer = (UINT64)AmdCpuState->x86._EIP; - AmdCpuState->x86._EIP = (UINT32)NewInstructionPointer; - // - // Clear the auto HALT restart flag so the RSM instruction returns - // program control to the instruction following the HLT instruction. - // - if ((AmdCpuState->x86.AutoHALTRestart & BIT0) != 0) { - AmdCpuState->x86.AutoHALTRestart &= ~BIT0; - } + OriginalInstructionPointer = AmdCpuState->x64._RIP; + + if ((AmdCpuState->x64.EFER & LMA) == 0) { + AmdCpuState->x64._RIP = NewInstructionPointer32; } else { - OriginalInstructionPointer = AmdCpuState->x64._RIP; - if ((AmdCpuState->x64.EFER & LMA) == 0) { - AmdCpuState->x64._RIP = (UINT32)NewInstructionPointer32; - } else { - AmdCpuState->x64._RIP = (UINT32)NewInstructionPointer; - } + AmdCpuState->x64._RIP = NewInstructionPointer; + } - // - // Clear the auto HALT restart flag so the RSM instruction returns - // program control to the instruction following the HLT instruction. - // - if ((AmdCpuState->x64.AutoHALTRestart & BIT0) != 0) { - AmdCpuState->x64.AutoHALTRestart &= ~BIT0; - } + // + // Clear the auto HALT restart flag so the RSM instruction returns + // program control to the instruction following the HLT instruction. + // + if ((AmdCpuState->x64.AutoHALTRestart & BIT0) != 0) { + AmdCpuState->x64.AutoHALTRestart &= ~BIT0; } return OriginalInstructionPointer; diff --git a/UefiCpuPkg/Library/SmmCpuPlatformHookLibNull/SmmCpuPlatformHookLibNull.c b/UefiCpuPkg/Library/SmmCpuPlatformHookLibNull/SmmCpuPlatformHookLibNull.c index 085a03e52a4a..b03a72d17777 100644 --- a/UefiCpuPkg/Library/SmmCpuPlatformHookLibNull/SmmCpuPlatformHookLibNull.c +++ b/UefiCpuPkg/Library/SmmCpuPlatformHookLibNull/SmmCpuPlatformHookLibNull.c @@ -1,7 +1,7 @@ /** @file SMM CPU Platform Hook NULL library instance. -Copyright (c) 2006 - 2015, Intel Corporation. All rights reserved.
+Copyright (c) 2006 - 2024, Intel Corporation. All rights reserved.
SPDX-License-Identifier: BSD-2-Clause-Patent **/ @@ -100,3 +100,21 @@ GetPlatformPageTableAttribute ( { return EFI_UNSUPPORTED; } + +/** + SMM CPU Platform Hook before executing MMI Handler. + + This function can be used to perform the platform specific items before executing MMI Handler. + + @retval EFI_SUCCESS The smm cpu platform hook before executing MMI Handler is executed successfully. + @retval EFI_UNSUPPORTED The smm cpu platform hook before executing MMI Handler is unsupported. + +**/ +EFI_STATUS +EFIAPI +SmmCpuPlatformHookBeforeMmiHandler ( + VOID + ) +{ + return EFI_UNSUPPORTED; +} diff --git a/UefiCpuPkg/Library/SmmRelocationLib/AmdSmramSaveStateConfig.c b/UefiCpuPkg/Library/SmmRelocationLib/AmdSmramSaveStateConfig.c index 068ae6088779..27d661445a1a 100644 --- a/UefiCpuPkg/Library/SmmRelocationLib/AmdSmramSaveStateConfig.c +++ b/UefiCpuPkg/Library/SmmRelocationLib/AmdSmramSaveStateConfig.c @@ -1,7 +1,7 @@ /** @file Config SMRAM Save State for SmmBases Relocation. - Copyright (C) 2023 Advanced Micro Devices, Inc. All rights reserved.
+ Copyright (C) 2023 - 2024 Advanced Micro Devices, Inc. All rights reserved.
Copyright (c) 2024, Intel Corporation. All rights reserved.
SPDX-License-Identifier: BSD-2-Clause-Patent @@ -94,31 +94,20 @@ HookReturnFromSmm ( AmdCpuState = (AMD_SMRAM_SAVE_STATE_MAP *)CpuState; - if (GetMmSaveStateRegisterLma () == EFI_MM_SAVE_STATE_REGISTER_LMA_32BIT) { - OriginalInstructionPointer = (UINT64)AmdCpuState->x86._EIP; - AmdCpuState->x86._EIP = (UINT32)NewInstructionPointer; - // - // Clear the auto HALT restart flag so the RSM instruction returns - // program control to the instruction following the HLT instruction. - // - if ((AmdCpuState->x86.AutoHALTRestart & BIT0) != 0) { - AmdCpuState->x86.AutoHALTRestart &= ~BIT0; - } + OriginalInstructionPointer = AmdCpuState->x64._RIP; + + if ((AmdCpuState->x64.EFER & LMA) == 0) { + AmdCpuState->x64._RIP = NewInstructionPointer32; } else { - OriginalInstructionPointer = AmdCpuState->x64._RIP; - if ((AmdCpuState->x64.EFER & LMA) == 0) { - AmdCpuState->x64._RIP = (UINT32)NewInstructionPointer32; - } else { - AmdCpuState->x64._RIP = (UINT32)NewInstructionPointer; - } - - // - // Clear the auto HALT restart flag so the RSM instruction returns - // program control to the instruction following the HLT instruction. - // - if ((AmdCpuState->x64.AutoHALTRestart & BIT0) != 0) { - AmdCpuState->x64.AutoHALTRestart &= ~BIT0; - } + AmdCpuState->x64._RIP = NewInstructionPointer; + } + + // + // Clear the auto HALT restart flag so the RSM instruction returns + // program control to the instruction following the HLT instruction. + // + if ((AmdCpuState->x64.AutoHALTRestart & BIT0) != 0) { + AmdCpuState->x64.AutoHALTRestart &= ~BIT0; } return OriginalInstructionPointer; diff --git a/UefiCpuPkg/PiSmmCpuDxeSmm/MpService.c b/UefiCpuPkg/PiSmmCpuDxeSmm/MpService.c index 210b23af21d8..e3986fdc15a3 100644 --- a/UefiCpuPkg/PiSmmCpuDxeSmm/MpService.c +++ b/UefiCpuPkg/PiSmmCpuDxeSmm/MpService.c @@ -520,16 +520,19 @@ BSPHandler ( ApCount = CpuCount - 1; // - // Wait for all APs to get ready for programming MTRRs + // Wait for all APs of arrival at this point // - SmmCpuSyncWaitForAPs (mSmmMpSyncData->SyncContext, ApCount, CpuIndex); + SmmCpuSyncWaitForAPs (mSmmMpSyncData->SyncContext, ApCount, CpuIndex); /// #1: Wait APs + + // + // Signal all APs it's time for: + // 1. Backup MTRRs if needed. + // 2. Perform SMM CPU Platform Hook before executing MMI Handler. + // + ReleaseAllAPs (); /// #2: Signal APs if (SmmCpuFeaturesNeedConfigureMtrrs ()) { // - // Signal all APs it's time for backup MTRRs - // - ReleaseAllAPs (); - // // SmmCpuSyncWaitForAPs() may wait for ever if an AP happens to enter SMM at // exactly this point. Please make sure PcdCpuSmmMaxSyncLoops has been set @@ -543,12 +546,12 @@ BSPHandler ( // // Wait for all APs to complete their MTRR saving // - SmmCpuSyncWaitForAPs (mSmmMpSyncData->SyncContext, ApCount, CpuIndex); + SmmCpuSyncWaitForAPs (mSmmMpSyncData->SyncContext, ApCount, CpuIndex); /// #3: Wait APs // // Let all processors program SMM MTRRs together // - ReleaseAllAPs (); + ReleaseAllAPs (); /// #4: Signal APs // // SmmCpuSyncWaitForAPs() may wait for ever if an AP happens to enter SMM at @@ -560,10 +563,15 @@ BSPHandler ( // // Wait for all APs to complete their MTRR programming // - SmmCpuSyncWaitForAPs (mSmmMpSyncData->SyncContext, ApCount, CpuIndex); + SmmCpuSyncWaitForAPs (mSmmMpSyncData->SyncContext, ApCount, CpuIndex); /// #5: Wait APs } } + // + // Perform SMM CPU Platform Hook before executing MMI Handler + // + SmmCpuPlatformHookBeforeMmiHandler (); + // // The BUSY lock is initialized to Acquired state // @@ -625,18 +633,18 @@ BSPHandler ( // Notify all APs to exit // *mSmmMpSyncData->InsideSmm = FALSE; - ReleaseAllAPs (); + ReleaseAllAPs (); /// #6: Signal APs if (SmmCpuFeaturesNeedConfigureMtrrs ()) { // // Wait for all APs the readiness to program MTRRs // - SmmCpuSyncWaitForAPs (mSmmMpSyncData->SyncContext, ApCount, CpuIndex); + SmmCpuSyncWaitForAPs (mSmmMpSyncData->SyncContext, ApCount, CpuIndex); /// #7: Wait APs // // Signal APs to restore MTRRs // - ReleaseAllAPs (); + ReleaseAllAPs (); /// #8: Signal APs // // Restore OS MTRRs @@ -649,12 +657,12 @@ BSPHandler ( // // Wait for all APs to complete their pending tasks including MTRR programming if needed. // - SmmCpuSyncWaitForAPs (mSmmMpSyncData->SyncContext, ApCount, CpuIndex); + SmmCpuSyncWaitForAPs (mSmmMpSyncData->SyncContext, ApCount, CpuIndex); /// #9: Wait APs // // Signal APs to Reset states/semaphore for this processor // - ReleaseAllAPs (); + ReleaseAllAPs (); /// #10: Signal APs } if (mSmmDebugAgentSupport) { @@ -679,7 +687,7 @@ BSPHandler ( // Gather APs to exit SMM synchronously. Note the Present flag is cleared by now but // WaitForAllAps does not depend on the Present flag. // - SmmCpuSyncWaitForAPs (mSmmMpSyncData->SyncContext, ApCount, CpuIndex); + SmmCpuSyncWaitForAPs (mSmmMpSyncData->SyncContext, ApCount, CpuIndex); /// #11: Wait APs // // At this point, all APs should have exited from APHandler(). @@ -805,15 +813,17 @@ APHandler ( // // Notify BSP of arrival at this point // - SmmCpuSyncReleaseBsp (mSmmMpSyncData->SyncContext, CpuIndex, BspIndex); - } + SmmCpuSyncReleaseBsp (mSmmMpSyncData->SyncContext, CpuIndex, BspIndex); /// #1: Signal BSP - if (SmmCpuFeaturesNeedConfigureMtrrs ()) { // - // Wait for the signal from BSP to backup MTRRs + // Wait for the signal from BSP to: + // 1. Backup MTRRs if needed. + // 2. Perform SMM CPU Platform Hook before executing MMI Handler. // - SmmCpuSyncWaitForBsp (mSmmMpSyncData->SyncContext, CpuIndex, BspIndex); + SmmCpuSyncWaitForBsp (mSmmMpSyncData->SyncContext, CpuIndex, BspIndex); /// #2: Wait BSP + } + if (SmmCpuFeaturesNeedConfigureMtrrs ()) { // // Backup OS MTRRs // @@ -822,12 +832,12 @@ APHandler ( // // Signal BSP the completion of this AP // - SmmCpuSyncReleaseBsp (mSmmMpSyncData->SyncContext, CpuIndex, BspIndex); + SmmCpuSyncReleaseBsp (mSmmMpSyncData->SyncContext, CpuIndex, BspIndex); /// #3: Signal BSP // // Wait for BSP's signal to program MTRRs // - SmmCpuSyncWaitForBsp (mSmmMpSyncData->SyncContext, CpuIndex, BspIndex); + SmmCpuSyncWaitForBsp (mSmmMpSyncData->SyncContext, CpuIndex, BspIndex); /// #4: Wait BSP // // Replace OS MTRRs with SMI MTRRs @@ -837,14 +847,19 @@ APHandler ( // // Signal BSP the completion of this AP // - SmmCpuSyncReleaseBsp (mSmmMpSyncData->SyncContext, CpuIndex, BspIndex); + SmmCpuSyncReleaseBsp (mSmmMpSyncData->SyncContext, CpuIndex, BspIndex); /// #5: Signal BSP } + // + // Perform SMM CPU Platform Hook before executing MMI Handler + // + SmmCpuPlatformHookBeforeMmiHandler (); + while (TRUE) { // // Wait for something to happen // - SmmCpuSyncWaitForBsp (mSmmMpSyncData->SyncContext, CpuIndex, BspIndex); + SmmCpuSyncWaitForBsp (mSmmMpSyncData->SyncContext, CpuIndex, BspIndex); /// #6: Wait BSP // // Check if BSP wants to exit SMM @@ -884,12 +899,12 @@ APHandler ( // // Notify BSP the readiness of this AP to program MTRRs // - SmmCpuSyncReleaseBsp (mSmmMpSyncData->SyncContext, CpuIndex, BspIndex); + SmmCpuSyncReleaseBsp (mSmmMpSyncData->SyncContext, CpuIndex, BspIndex); /// #7: Signal BSP // // Wait for the signal from BSP to program MTRRs // - SmmCpuSyncWaitForBsp (mSmmMpSyncData->SyncContext, CpuIndex, BspIndex); + SmmCpuSyncWaitForBsp (mSmmMpSyncData->SyncContext, CpuIndex, BspIndex); /// #8: Wait BSP // // Restore OS MTRRs @@ -902,12 +917,12 @@ APHandler ( // // Notify BSP the readiness of this AP to Reset states/semaphore for this processor // - SmmCpuSyncReleaseBsp (mSmmMpSyncData->SyncContext, CpuIndex, BspIndex); + SmmCpuSyncReleaseBsp (mSmmMpSyncData->SyncContext, CpuIndex, BspIndex); /// #9: Signal BSP // // Wait for the signal from BSP to Reset states/semaphore for this processor // - SmmCpuSyncWaitForBsp (mSmmMpSyncData->SyncContext, CpuIndex, BspIndex); + SmmCpuSyncWaitForBsp (mSmmMpSyncData->SyncContext, CpuIndex, BspIndex); /// #10: Wait BSP } // @@ -918,7 +933,7 @@ APHandler ( // // Notify BSP the readiness of this AP to exit SMM // - SmmCpuSyncReleaseBsp (mSmmMpSyncData->SyncContext, CpuIndex, BspIndex); + SmmCpuSyncReleaseBsp (mSmmMpSyncData->SyncContext, CpuIndex, BspIndex); /// #11: Signal BSP } /** diff --git a/UefiCpuPkg/PiSmmCpuDxeSmm/NonMmramMapDxeSmm.c b/UefiCpuPkg/PiSmmCpuDxeSmm/NonMmramMapDxeSmm.c index 8c189ff6a057..00205b236de4 100644 --- a/UefiCpuPkg/PiSmmCpuDxeSmm/NonMmramMapDxeSmm.c +++ b/UefiCpuPkg/PiSmmCpuDxeSmm/NonMmramMapDxeSmm.c @@ -634,7 +634,7 @@ CreateExtendedProtectionRange ( &MemorySpaceMap ); for (Index = 0; Index < NumberOfSpaceDescriptors; Index++) { - if ((MemorySpaceMap[Index].GcdMemoryType == EfiGcdMemoryTypeMemoryMappedIo)) { + if (MemorySpaceMap[Index].GcdMemoryType == EfiGcdMemoryTypeMemoryMappedIo) { if (ADDRESS_IS_ALIGNED (MemorySpaceMap[Index].BaseAddress, SIZE_4KB) && (MemorySpaceMap[Index].Length % SIZE_4KB == 0)) { diff --git a/UefiCpuPkg/PiSmmCpuDxeSmm/X64/PageTbl.c b/UefiCpuPkg/PiSmmCpuDxeSmm/X64/PageTbl.c index 160e33b4ed6a..f4aa26798486 100644 --- a/UefiCpuPkg/PiSmmCpuDxeSmm/X64/PageTbl.c +++ b/UefiCpuPkg/PiSmmCpuDxeSmm/X64/PageTbl.c @@ -851,7 +851,15 @@ SaveCr2 ( OUT UINTN *Cr2 ) { - *Cr2 = AsmReadCr2 (); + // + // A page fault (#PF) that triggers an update to the page + // table only occurs if SmiProfile is enabled. Therefore, it is + // necessary to save the CR2 register if SmiProfile is + // configured to be enabled. + // + if (mSmmProfileEnabled) { + *Cr2 = AsmReadCr2 (); + } } /** @@ -864,5 +872,13 @@ RestoreCr2 ( IN UINTN Cr2 ) { - AsmWriteCr2 (Cr2); + // + // A page fault (#PF) that triggers an update to the page + // table only occurs if SmiProfile is enabled. Therefore, it is + // necessary to restore the CR2 register if SmiProfile is + // configured to be enabled. + // + if (mSmmProfileEnabled) { + AsmWriteCr2 (Cr2); + } } diff --git a/UefiCpuPkg/SecCore/SecCore.inf b/UefiCpuPkg/SecCore/SecCore.inf index 4f732cccb7fc..20a2ccef0be2 100644 --- a/UefiCpuPkg/SecCore/SecCore.inf +++ b/UefiCpuPkg/SecCore/SecCore.inf @@ -78,6 +78,7 @@ [Pcd] gUefiCpuPkgTokenSpaceGuid.PcdPeiTemporaryRamStackSize ## CONSUMES + gUefiCpuPkgTokenSpaceGuid.PcdMaxMappingAddressBeforeTempRamExit ## CONSUMES gEfiMdeModulePkgTokenSpaceGuid.PcdMigrateTemporaryRamFirmwareVolumes ## CONSUMES [UserExtensions.TianoCore."ExtraFiles"] diff --git a/UefiCpuPkg/SecCore/SecCoreNative.inf b/UefiCpuPkg/SecCore/SecCoreNative.inf index 454a3629e505..6d6d306294da 100644 --- a/UefiCpuPkg/SecCore/SecCoreNative.inf +++ b/UefiCpuPkg/SecCore/SecCoreNative.inf @@ -75,6 +75,7 @@ [Pcd] gUefiCpuPkgTokenSpaceGuid.PcdPeiTemporaryRamStackSize ## CONSUMES + gUefiCpuPkgTokenSpaceGuid.PcdMaxMappingAddressBeforeTempRamExit ## CONSUMES gEfiMdeModulePkgTokenSpaceGuid.PcdMigrateTemporaryRamFirmwareVolumes ## CONSUMES [UserExtensions.TianoCore."ExtraFiles"] diff --git a/UefiCpuPkg/SecCore/SecMain.c b/UefiCpuPkg/SecCore/SecMain.c index b0ab6cdae462..23a75d307667 100644 --- a/UefiCpuPkg/SecCore/SecMain.c +++ b/UefiCpuPkg/SecCore/SecMain.c @@ -73,40 +73,21 @@ MigrateGdt ( } /** - Migrate page table to permanent memory mapping entire physical address space. - - @retval EFI_SUCCESS The PageTable was migrated successfully. - @retval EFI_UNSUPPORTED Unsupport to migrate page table to permanent memory if IA-32e Mode not actived. - @retval EFI_OUT_OF_RESOURCES The PageTable could not be migrated due to lack of available memory. + Get Paging Mode + @retval Paging Mode. **/ -EFI_STATUS -MigratePageTable ( +PAGING_MODE +GetPagingMode ( VOID ) { - EFI_STATUS Status; - IA32_CR4 Cr4; - BOOLEAN Page5LevelSupport; - UINT32 RegEax; - CPUID_EXTENDED_CPU_SIG_EDX RegEdx; - BOOLEAN Page1GSupport; - PAGING_MODE PagingMode; - CPUID_VIR_PHY_ADDRESS_SIZE_EAX VirPhyAddressSize; - UINT32 MaxExtendedFunctionId; - UINTN PageTable; - EFI_PHYSICAL_ADDRESS Buffer; - UINTN BufferSize; - IA32_MAP_ATTRIBUTE MapAttribute; - IA32_MAP_ATTRIBUTE MapMask; - - VirPhyAddressSize.Uint32 = 0; - PageTable = 0; - BufferSize = 0; - MapAttribute.Uint64 = 0; - MapMask.Uint64 = MAX_UINT64; - MapAttribute.Bits.Present = 1; - MapAttribute.Bits.ReadWrite = 1; + IA32_CR4 Cr4; + BOOLEAN Page5LevelSupport; + UINT32 RegEax; + CPUID_EXTENDED_CPU_SIG_EDX RegEdx; + BOOLEAN Page1GSupport; + PAGING_MODE PagingMode; // // Check Page5Level Support or not. @@ -135,6 +116,27 @@ MigratePageTable ( PagingMode = Page1GSupport ? Paging4Level1GB : Paging4Level; } + return PagingMode; +} + +/** + Get max physical address supported by specific page mode + + @param[in] PagingMode The paging mode. + + @retval Max Address. +**/ +UINT32 +GetMaxAddress ( + IN PAGING_MODE PagingMode + ) +{ + CPUID_VIR_PHY_ADDRESS_SIZE_EAX VirPhyAddressSize; + UINT32 MaxExtendedFunctionId; + UINT32 MaxAddressBits; + + VirPhyAddressSize.Uint32 = 0; + // // Get Maximum Physical Address Bits // Get the number of address lines; Maximum Physical Address is 2^PhysicalAddressBits - 1. @@ -143,62 +145,19 @@ MigratePageTable ( AsmCpuid (CPUID_EXTENDED_FUNCTION, &MaxExtendedFunctionId, NULL, NULL, NULL); if (MaxExtendedFunctionId >= CPUID_VIR_PHY_ADDRESS_SIZE) { AsmCpuid (CPUID_VIR_PHY_ADDRESS_SIZE, &VirPhyAddressSize.Uint32, NULL, NULL, NULL); + MaxAddressBits = VirPhyAddressSize.Bits.PhysicalAddressBits; } else { - VirPhyAddressSize.Bits.PhysicalAddressBits = 36; + MaxAddressBits = 36; } if ((PagingMode == Paging4Level1GB) || (PagingMode == Paging4Level)) { // - // The max lineaddress bits is 48 for 4 level page table. + // The max liner address bits is 48 for 4 level page table. // - VirPhyAddressSize.Bits.PhysicalAddressBits = MIN (VirPhyAddressSize.Bits.PhysicalAddressBits, 48); - } - - // - // Get required buffer size for the pagetable that will be created. - // - Status = PageTableMap (&PageTable, PagingMode, 0, &BufferSize, 0, LShiftU64 (1, VirPhyAddressSize.Bits.PhysicalAddressBits), &MapAttribute, &MapMask, NULL); - ASSERT (Status == EFI_BUFFER_TOO_SMALL); - if (Status != EFI_BUFFER_TOO_SMALL) { - return Status; + MaxAddressBits = MIN (VirPhyAddressSize.Bits.PhysicalAddressBits, 48); } - // - // Allocate required Buffer. - // - Status = PeiServicesAllocatePages ( - EfiBootServicesData, - EFI_SIZE_TO_PAGES (BufferSize), - &Buffer - ); - if (EFI_ERROR (Status)) { - return EFI_OUT_OF_RESOURCES; - } - - // - // Create PageTable in permanent memory. - // - Status = PageTableMap (&PageTable, PagingMode, (VOID *)(UINTN)Buffer, &BufferSize, 0, LShiftU64 (1, VirPhyAddressSize.Bits.PhysicalAddressBits), &MapAttribute, &MapMask, NULL); - ASSERT_EFI_ERROR (Status); - if (EFI_ERROR (Status) || (PageTable == 0)) { - return EFI_OUT_OF_RESOURCES; - } - - // - // Write the Pagetable to CR3. - // - AsmWriteCr3 (PageTable); - - DEBUG (( - DEBUG_INFO, - "MigratePageTable: Created PageTable = 0x%lx, BufferSize = %x, PagingMode = 0x%lx, Support Max Physical Address Bits = %d\n", - PageTable, - BufferSize, - (UINTN)PagingMode, - VirPhyAddressSize.Bits.PhysicalAddressBits - )); - - return Status; + return MaxAddressBits; } // @@ -583,6 +542,22 @@ SecTemporaryRamDone ( EFI_PEI_PPI_DESCRIPTOR *PeiPpiDescriptor; REPUBLISH_SEC_PPI_PPI *RepublishSecPpiPpi; IA32_CR0 Cr0; + PAGING_MODE PagingMode; + UINT32 MaxAddressBits; + UINTN PageTable; + EFI_PHYSICAL_ADDRESS Buffer; + UINTN BufferSize; + UINT64 Length; + UINT64 Address; + IA32_MAP_ATTRIBUTE MapAttribute; + IA32_MAP_ATTRIBUTE MapMask; + + PageTable = 0; + BufferSize = 0; + MapAttribute.Uint64 = 0; + MapAttribute.Bits.Present = 1; + MapAttribute.Bits.ReadWrite = 1; + MapMask.Uint64 = MAX_UINT64; // // Republish Sec Platform Information(2) PPI @@ -634,10 +609,43 @@ SecTemporaryRamDone ( // ASSERT (sizeof (UINTN) == sizeof (UINT64)); - Status = MigratePageTable (); - if (EFI_ERROR (Status)) { - DEBUG ((DEBUG_ERROR, "SecTemporaryRamDone: Failed to migrate page table to permanent memory: %r.\n", Status)); - CpuDeadLoop (); + // + // Get PagingMode & MaxAddressBits. + // + PagingMode = GetPagingMode (); + MaxAddressBits = GetMaxAddress (PagingMode); + DEBUG ((DEBUG_INFO, "SecTemporaryRamDone: PagingMode = 0x%lx, MaxAddressBits = %d\n", PagingMode, MaxAddressBits)); + + // + // Create page table to cover the max mapping address in physical memory before Temp + // Ram Exit. The max mapping address is defined by PcdMaxMappingAddressBeforeTempRamExit. + // + Length = FixedPcdGet64 (PcdMaxMappingAddressBeforeTempRamExit); + Length = MIN (LShiftU64 (1, MaxAddressBits), Length); + if (Length != 0) { + Status = PageTableMap (&PageTable, PagingMode, 0, &BufferSize, 0, Length, &MapAttribute, &MapMask, NULL); + ASSERT (Status == EFI_BUFFER_TOO_SMALL); + if (Status != EFI_BUFFER_TOO_SMALL) { + return Status; + } + + Status = PeiServicesAllocatePages ( + EfiBootServicesData, + EFI_SIZE_TO_PAGES (BufferSize), + &Buffer + ); + if (EFI_ERROR (Status)) { + return EFI_OUT_OF_RESOURCES; + } + + Status = PageTableMap (&PageTable, PagingMode, (VOID *)(UINTN)Buffer, &BufferSize, 0, Length, &MapAttribute, &MapMask, NULL); + ASSERT (BufferSize == 0); + if (EFI_ERROR (Status)) { + DEBUG ((DEBUG_ERROR, "SecTemporaryRamDone: Failed to create page table in physical memory before Temp Ram Exit: %r.\n", Status)); + CpuDeadLoop (); + } + + AsmWriteCr3 (PageTable); } } @@ -646,6 +654,41 @@ SecTemporaryRamDone ( // SecPlatformDisableTemporaryMemory (); + // + // Expanding the page table to cover the entire memory space since the physical memory is WB after TempRamExit. + // + if ((Cr0.Bits.PG != 0) && (Length < LShiftU64 (1, MaxAddressBits))) { + Address = Length; + Length = LShiftU64 (1, MaxAddressBits) - Length; + + MapAttribute.Uint64 = Address; + MapAttribute.Bits.Present = 1; + MapAttribute.Bits.ReadWrite = 1; + + Status = PageTableMap (&PageTable, PagingMode, 0, &BufferSize, Address, Length, &MapAttribute, &MapMask, NULL); + ASSERT (Status == EFI_BUFFER_TOO_SMALL); + if (Status != EFI_BUFFER_TOO_SMALL) { + return Status; + } + + Status = PeiServicesAllocatePages ( + EfiBootServicesData, + EFI_SIZE_TO_PAGES (BufferSize), + &Buffer + ); + if (EFI_ERROR (Status)) { + return EFI_OUT_OF_RESOURCES; + } + + Status = PageTableMap (&PageTable, PagingMode, (VOID *)(UINTN)Buffer, &BufferSize, Address, Length, &MapAttribute, &MapMask, NULL); + if (EFI_ERROR (Status)) { + DEBUG ((DEBUG_ERROR, "SecTemporaryRamDone: Failed to create full range page table in physical memory after Temp Ram Exit: %r.\n", Status)); + CpuDeadLoop (); + } + + AsmWriteCr3 (PageTable); + } + // // Restore original interrupt state // diff --git a/UefiCpuPkg/UefiCpuPkg.dec b/UefiCpuPkg/UefiCpuPkg.dec index 33ac8cf91c4a..5d5342ded6af 100644 --- a/UefiCpuPkg/UefiCpuPkg.dec +++ b/UefiCpuPkg/UefiCpuPkg.dec @@ -75,6 +75,8 @@ SmmRelocationLib|Include/Library/SmmRelocationLib.h [LibraryClasses.RISCV64] + ## @libraryclass Provides function to initialize the FPU. + RiscVFpuLib|Include/Library/BaseRiscVFpuLib.h ## @libraryclass Provides functions to manage MMU features on RISCV64 CPUs. ## RiscVMmuLib|Include/Library/BaseRiscVMmuLib.h @@ -260,6 +262,14 @@ # @Prompt BSP Broadcast Method for the first-time wakeup of APs gUefiCpuPkgTokenSpaceGuid.PcdFirstTimeWakeUpAPsBySipi|TRUE|BOOLEAN|0x30002007 + ## The max mapping address in page table before Temp Ram Exit. + # After physical memory is initialized and before Temp Ram Exit, the physical memory is in UC state. + # The PCD controls the page table max mapping address in physical memory before Temp Ram Exit + # because creating a big page table in UC physical memory to cover the entire memory space + # is slow. The value of 0xFFFFFFFFFFFFFFFF, then firmware will map entire physical address space. + # @Prompt Configure max mapping address in page table before Temp Ram Exit. + gUefiCpuPkgTokenSpaceGuid.PcdMaxMappingAddressBeforeTempRamExit|0xFFFFFFFFFFFFFFFF|UINT64|0x30002008 + [PcdsFixedAtBuild, PcdsPatchableInModule] ## This value is the CPU Local APIC base address, which aligns the address on a 4-KByte boundary. # @Prompt Configure base address of CPU Local APIC diff --git a/UefiCpuPkg/UefiCpuPkg.dsc b/UefiCpuPkg/UefiCpuPkg.dsc index f173bba87e4b..d7f8e422d42c 100644 --- a/UefiCpuPkg/UefiCpuPkg.dsc +++ b/UefiCpuPkg/UefiCpuPkg.dsc @@ -224,6 +224,7 @@ [Components.RISCV64] UefiCpuPkg/Library/BaseRiscV64CpuExceptionHandlerLib/BaseRiscV64CpuExceptionHandlerLib.inf UefiCpuPkg/Library/BaseRiscV64CpuTimerLib/BaseRiscV64CpuTimerLib.inf + UefiCpuPkg/Library/BaseRiscVFpuLib/BaseRiscVFpuLib.inf UefiCpuPkg/Library/BaseRiscVMmuLib/BaseRiscVMmuLib.inf UefiCpuPkg/CpuTimerDxeRiscV64/CpuTimerDxeRiscV64.inf UefiCpuPkg/CpuDxeRiscV64/CpuDxeRiscV64.inf diff --git a/UefiCpuPkg/Universal/Acpi/S3Resume2Pei/S3Resume.c b/UefiCpuPkg/Universal/Acpi/S3Resume2Pei/S3Resume.c index 3e64a115bf6b..3f14cfb95829 100644 --- a/UefiCpuPkg/Universal/Acpi/S3Resume2Pei/S3Resume.c +++ b/UefiCpuPkg/Universal/Acpi/S3Resume2Pei/S3Resume.c @@ -871,7 +871,7 @@ S3ResumeExecuteBootScript ( SignalToSmmByCommunication (&gEdkiiS3SmmInitDoneGuid); } - if ((FeaturePcdGet (PcdDxeIplSwitchToLongMode)) || (sizeof (UINTN) == sizeof (UINT64))) { + if (FeaturePcdGet (PcdDxeIplSwitchToLongMode)) { AsmWriteCr3 ((UINTN)AcpiS3Context->S3NvsPageTableAddress); } @@ -1083,7 +1083,7 @@ S3RestoreConfig2 ( CpuDeadLoop (); } - if ((FeaturePcdGet (PcdDxeIplSwitchToLongMode)) || (sizeof (UINTN) == sizeof (UINT64))) { + if (FeaturePcdGet (PcdDxeIplSwitchToLongMode)) { // // Need reconstruct page table here, since we do not trust ACPINvs. // @@ -1217,7 +1217,9 @@ S3RestoreConfig2 ( AsmWriteCr0 (Cr0.UintN); } - AsmWriteCr3 ((UINTN)SmmS3ResumeState->SmmS3Cr3); + if (FeaturePcdGet (PcdDxeIplSwitchToLongMode)) { + AsmWriteCr3 ((UINTN)SmmS3ResumeState->SmmS3Cr3); + } // // Disable interrupt of Debug timer, since IDT table cannot work in long mode. diff --git a/UefiPayloadPkg/Library/BuildFdtLib/X86_BuildFdtLib.c b/UefiPayloadPkg/Library/BuildFdtLib/X86_BuildFdtLib.c index 8df78a0afc0e..ddee8209b394 100644 --- a/UefiPayloadPkg/Library/BuildFdtLib/X86_BuildFdtLib.c +++ b/UefiPayloadPkg/Library/BuildFdtLib/X86_BuildFdtLib.c @@ -19,6 +19,7 @@ #include #include #include +#include #include #include #include @@ -119,10 +120,10 @@ BuildFdtForMemory ( RegTmp[0] = CpuToFdt64 (ResourceHob->PhysicalStart); RegTmp[1] = CpuToFdt64 (ResourceHob->ResourceLength); - Status = FdtSetProp (Fdt, TempNode, "reg", &RegTmp, sizeof (RegTmp)); + Status = FdtSetProperty (Fdt, TempNode, "reg", &RegTmp, sizeof (RegTmp)); ASSERT_EFI_ERROR (Status); - Status = FdtSetProp (Fdt, TempNode, "device_type", "memory", (UINT32)(AsciiStrLen ("memory")+1)); + Status = FdtSetProperty (Fdt, TempNode, "device_type", "memory", (UINT32)(AsciiStrLen ("memory")+1)); ASSERT_EFI_ERROR (Status); } } @@ -142,19 +143,22 @@ BuildFdtForMemAlloc ( IN VOID *FdtBase ) { - EFI_STATUS Status; - EFI_PEI_HOB_POINTERS Hob; - VOID *HobStart; - VOID *Fdt; - INT32 ParentNode; - INT32 TempNode; - CHAR8 TempStr[32]; - UINT64 RegTmp[2]; - UINT32 AllocMemType; - EFI_GUID *AllocMemName; - UINT8 IsStackHob; - UINT8 IsBspStore; - UINT32 Data32; + EFI_STATUS Status; + EFI_PEI_HOB_POINTERS Hob; + VOID *HobStart; + VOID *Fdt; + INT32 ParentNode; + INT32 TempNode; + CHAR8 TempStr[32]; + UINT64 RegTmp[2]; + UINT32 AllocMemType; + EFI_GUID *AllocMemName; + UINT8 IsStackHob; + UINT8 IsBspStore; + UINT32 Data32; + UNIVERSAL_PAYLOAD_SMBIOS_TABLE *SmbiosTable; + UNIVERSAL_PAYLOAD_ACPI_TABLE *AcpiTable; + EFI_HOB_GUID_TYPE *GuidHob; Fdt = FdtBase; @@ -162,8 +166,32 @@ BuildFdtForMemAlloc ( ASSERT (ParentNode > 0); Data32 = CpuToFdt32 (2); - Status = FdtSetProp (Fdt, ParentNode, "#address-cells", &Data32, sizeof (UINT32)); - Status = FdtSetProp (Fdt, ParentNode, "#size-cells", &Data32, sizeof (UINT32)); + Status = FdtSetProperty (Fdt, ParentNode, "#address-cells", &Data32, sizeof (UINT32)); + Status = FdtSetProperty (Fdt, ParentNode, "#size-cells", &Data32, sizeof (UINT32)); + + GuidHob = NULL; + SmbiosTable = NULL; + GuidHob = GetFirstGuidHob (&gUniversalPayloadSmbios3TableGuid); + if (GuidHob != NULL) { + SmbiosTable = GET_GUID_HOB_DATA (GuidHob); + DEBUG ((DEBUG_INFO, "To build Smbios memory FDT ,SmbiosTable :%lx, SmBiosEntryPoint :%lx\n", (UINTN)SmbiosTable, SmbiosTable->SmBiosEntryPoint)); + Status = AsciiSPrint (TempStr, sizeof (TempStr), "memory@%lX", SmbiosTable->SmBiosEntryPoint); + DEBUG ((DEBUG_INFO, "To build Smbios memory FDT #2, SmbiosTable->Header.Length :%x\n", SmbiosTable->Header.Length)); + TempNode = 0; + TempNode = FdtAddSubnode (Fdt, ParentNode, TempStr); + DEBUG ((DEBUG_INFO, "FdtAddSubnode %x", TempNode)); + RegTmp[0] = CpuToFdt64 (SmbiosTable->SmBiosEntryPoint); + RegTmp[1] = CpuToFdt64 (SmbiosTable->Header.Length); + FdtSetProperty (Fdt, TempNode, "reg", &RegTmp, sizeof (RegTmp)); + ASSERT_EFI_ERROR (Status); + FdtSetProperty (Fdt, TempNode, "compatible", "smbios", (UINT32)(AsciiStrLen ("smbios")+1)); + ASSERT_EFI_ERROR (Status); + } + + GuidHob = GetFirstGuidHob (&gUniversalPayloadAcpiTableGuid); + if (GuidHob != NULL) { + AcpiTable = (UNIVERSAL_PAYLOAD_ACPI_TABLE *)GET_GUID_HOB_DATA (GuidHob); + } HobStart = GetFirstHob (EFI_HOB_TYPE_MEMORY_ALLOCATION); // @@ -239,11 +267,27 @@ BuildFdtForMemAlloc ( RegTmp[0] = CpuToFdt64 (Hob.MemoryAllocation->AllocDescriptor.MemoryBaseAddress); RegTmp[1] = CpuToFdt64 (Hob.MemoryAllocation->AllocDescriptor.MemoryLength); - Status = FdtSetProp (Fdt, TempNode, "reg", &RegTmp, sizeof (RegTmp)); + Status = FdtSetProperty (Fdt, TempNode, "reg", &RegTmp, sizeof (RegTmp)); ASSERT_EFI_ERROR (Status); - if (!(AsciiStrCmp (mMemoryAllocType[AllocMemType], "mmio") == 0)) { - Status = FdtSetProp (Fdt, TempNode, "compatible", mMemoryAllocType[AllocMemType], (UINT32)(AsciiStrLen (mMemoryAllocType[AllocMemType])+1)); + if ((AsciiStrCmp (mMemoryAllocType[AllocMemType], "mmio") == 0)) { + continue; + } + + if (!(AsciiStrCmp (mMemoryAllocType[AllocMemType], "acpi-nvs") == 0) && (AsciiStrCmp (mMemoryAllocType[AllocMemType], "acpi") == 0)) { + DEBUG ((DEBUG_INFO, "find acpi memory hob MemoryBaseAddress:%x , AcpiTable->Rsdp :%x\n", Hob.MemoryAllocation->AllocDescriptor.MemoryBaseAddress, AcpiTable->Rsdp)); + if (Hob.MemoryAllocation->AllocDescriptor.MemoryBaseAddress == AcpiTable->Rsdp) { + DEBUG ((DEBUG_INFO, "keep acpi memory hob \n")); + Status = FdtSetProperty (Fdt, TempNode, "compatible", mMemoryAllocType[AllocMemType], (UINT32)(AsciiStrLen (mMemoryAllocType[AllocMemType])+1)); + ASSERT_EFI_ERROR (Status); + } else { + DEBUG ((DEBUG_INFO, "change acpi memory hob \n")); + Status = FdtSetProperty (Fdt, TempNode, "compatible", mMemoryAllocType[4], (UINT32)(AsciiStrLen (mMemoryAllocType[4])+1)); + ASSERT_EFI_ERROR (Status); + } + } else { + DEBUG ((DEBUG_INFO, "other memory hob \n")); + Status = FdtSetProperty (Fdt, TempNode, "compatible", mMemoryAllocType[AllocMemType], (UINT32)(AsciiStrLen (mMemoryAllocType[AllocMemType])+1)); ASSERT_EFI_ERROR (Status); } } @@ -285,7 +329,7 @@ BuildFdtForSerial ( ASSERT (TempNode > 0); Data32 = CpuToFdt32 (PcdGet32 (PcdSerialBaudRate)); - Status = FdtSetProp (Fdt, TempNode, "current-speed", &Data32, sizeof (Data32)); + Status = FdtSetProperty (Fdt, TempNode, "current-speed", &Data32, sizeof (Data32)); ASSERT_EFI_ERROR (Status); if (PcdGetBool (PcdSerialUseMmio)) { @@ -300,14 +344,14 @@ BuildFdtForSerial ( Data32 = (UINT32)((Data64 & 0x0FFFFFFFF)); RegData[1] = CpuToFdt32 (Data32); RegData[2] = CpuToFdt32 (8); - Status = FdtSetProp (Fdt, TempNode, "reg", &RegData, sizeof (RegData)); + Status = FdtSetProperty (Fdt, TempNode, "reg", &RegData, sizeof (RegData)); ASSERT_EFI_ERROR (Status); Data32 = CpuToFdt32 (1); - Status = FdtSetProp (Fdt, TempNode, "reg-io-width", &Data32, sizeof (Data32)); + Status = FdtSetProperty (Fdt, TempNode, "reg-io-width", &Data32, sizeof (Data32)); ASSERT_EFI_ERROR (Status); - Status = FdtSetProp (Fdt, TempNode, "compatible", "isa", (UINT32)(AsciiStrLen ("isa")+1)); + Status = FdtSetProperty (Fdt, TempNode, "compatible", "isa", (UINT32)(AsciiStrLen ("isa")+1)); ASSERT_EFI_ERROR (Status); return Status; @@ -360,19 +404,19 @@ BuildFdtForSerialLpss ( ASSERT (TempNode > 0); Data32 = CpuToFdt32 (SerialPortInfo->BaudRate); - Status = FdtSetProp (Fdt, TempNode, "current-speed", &Data32, sizeof (Data32)); + Status = FdtSetProperty (Fdt, TempNode, "current-speed", &Data32, sizeof (Data32)); ASSERT_EFI_ERROR (Status); RegData[0] = CpuToFdt32 ((UINT32)SerialPortInfo->RegisterBase); RegData[1] = CpuToFdt32 (0x80); - Status = FdtSetProp (Fdt, TempNode, "reg", &RegData, sizeof (RegData)); + Status = FdtSetProperty (Fdt, TempNode, "reg", &RegData, sizeof (RegData)); ASSERT_EFI_ERROR (Status); Data32 = CpuToFdt32 (4); - Status = FdtSetProp (Fdt, TempNode, "reg-io-width", &Data32, sizeof (Data32)); + Status = FdtSetProperty (Fdt, TempNode, "reg-io-width", &Data32, sizeof (Data32)); ASSERT_EFI_ERROR (Status); - Status = FdtSetProp (Fdt, TempNode, "compatible", "ns16550a", (UINT32)(AsciiStrLen ("ns16550a")+1)); + Status = FdtSetProperty (Fdt, TempNode, "compatible", "ns16550a", (UINT32)(AsciiStrLen ("ns16550a")+1)); ASSERT_EFI_ERROR (Status); GuidHob = GET_NEXT_HOB (GuidHob); @@ -404,6 +448,7 @@ BuildFdtForPciRootBridge ( UINT32 RegTmp[2]; UINT32 RegData[21]; UINT32 DMARegData[8]; + UINT64 Reg64Data[2]; UINT32 Data32; UINT64 Data64; UINT8 BusNumber; @@ -588,7 +633,7 @@ BuildFdtForPciRootBridge ( RegData[20] = CpuToFdt32 (Data32); DEBUG ((DEBUG_INFO, "PciRootBridge->Io.base size [20] %x, \n", Data32)); - Status = FdtSetProp (Fdt, TempNode, "ranges", &RegData, sizeof (RegData)); + Status = FdtSetProperty (Fdt, TempNode, "ranges", &RegData, sizeof (RegData)); ASSERT_EFI_ERROR (Status); // non-reloc/non-prefetch/memory, child-addr, parent-addr, length @@ -608,14 +653,17 @@ BuildFdtForPciRootBridge ( DMARegData[6] = CpuToFdt32 (1); DMARegData[7] = CpuToFdt32 (0); - Status = FdtSetProp (Fdt, TempNode, "dma-ranges", &DMARegData, sizeof (DMARegData)); + Status = FdtSetProperty (Fdt, TempNode, "dma-ranges", &DMARegData, sizeof (DMARegData)); ASSERT_EFI_ERROR (Status); - Data32 = CpuToFdt32 (2); - Status = FdtSetProp (Fdt, TempNode, "#size-cells", &Data32, sizeof (UINT32)); + ASSERT (PciRootBridgeInfo->RootBridge[Index].Bus.Base <= 0xFF); + ASSERT (PciRootBridgeInfo->RootBridge[Index].Bus.Limit <= 0xFF); - Data32 = CpuToFdt32 (3); - Status = FdtSetProp (Fdt, TempNode, "#address-cells", &Data32, sizeof (UINT32)); + Reg64Data[0] = CpuToFdt64 (PciExpressBaseAddress + LShiftU64 (PciRootBridgeInfo->RootBridge[Index].Bus.Base, 20)); + Reg64Data[1] = CpuToFdt64 (LShiftU64 (PciRootBridgeInfo->RootBridge[Index].Bus.Limit +1, 20)); + + Status = FdtSetProperty (Fdt, TempNode, "reg", &Reg64Data, sizeof (Reg64Data)); + ASSERT_EFI_ERROR (Status); BusNumber = PciRootBridgeInfo->RootBridge[Index].Bus.Base & 0xFF; RegTmp[0] = CpuToFdt32 (BusNumber); @@ -624,10 +672,16 @@ BuildFdtForPciRootBridge ( DEBUG ((DEBUG_INFO, "PciRootBridge->BusNumber %x, \n", BusNumber)); DEBUG ((DEBUG_INFO, "PciRootBridge->BusLimit %x, \n", BusLimit)); - Status = FdtSetProp (Fdt, TempNode, "bus-range", &RegTmp, sizeof (RegTmp)); + Status = FdtSetProperty (Fdt, TempNode, "bus-range", &RegTmp, sizeof (RegTmp)); ASSERT_EFI_ERROR (Status); - Status = FdtSetProp (Fdt, TempNode, "compatible", "pci-rb", (UINT32)(AsciiStrLen ("pci-rb")+1)); + Data32 = CpuToFdt32 (2); + Status = FdtSetProperty (Fdt, TempNode, "#size-cells", &Data32, sizeof (UINT32)); + + Data32 = CpuToFdt32 (3); + Status = FdtSetProperty (Fdt, TempNode, "#address-cells", &Data32, sizeof (UINT32)); + + Status = FdtSetProperty (Fdt, TempNode, "compatible", "pci-rb", (UINT32)(AsciiStrLen ("pci-rb")+1)); ASSERT_EFI_ERROR (Status); if (Index == 0) { @@ -678,19 +732,19 @@ BuildFdtForPciRootBridge ( } Data32 = CpuToFdt32 (PciData.Device.SubsystemID); - Status = FdtSetProp (Fdt, GmaNode, "subsystem-id", &Data32, sizeof (UINT32)); + Status = FdtSetProperty (Fdt, GmaNode, "subsystem-id", &Data32, sizeof (UINT32)); Data32 = CpuToFdt32 (PciData.Device.SubsystemVendorID); - Status = FdtSetProp (Fdt, GmaNode, "subsystem-vendor-id", &Data32, sizeof (UINT32)); + Status = FdtSetProperty (Fdt, GmaNode, "subsystem-vendor-id", &Data32, sizeof (UINT32)); Data32 = CpuToFdt32 (PciData.Hdr.RevisionID); - Status = FdtSetProp (Fdt, GmaNode, "revision-id", &Data32, sizeof (UINT32)); + Status = FdtSetProperty (Fdt, GmaNode, "revision-id", &Data32, sizeof (UINT32)); Data32 = CpuToFdt32 (PciData.Hdr.DeviceId); - Status = FdtSetProp (Fdt, GmaNode, "device-id", &Data32, sizeof (UINT32)); + Status = FdtSetProperty (Fdt, GmaNode, "device-id", &Data32, sizeof (UINT32)); Data32 = CpuToFdt32 (PciData.Hdr.VendorId); - Status = FdtSetProp (Fdt, GmaNode, "vendor-id", &Data32, sizeof (UINT32)); + Status = FdtSetProperty (Fdt, GmaNode, "vendor-id", &Data32, sizeof (UINT32)); } if (SerialParent != NULL) { @@ -705,12 +759,12 @@ BuildFdtForPciRootBridge ( if (SerialParent->IsIsaCompatible) { Status = AsciiSPrint (eSPIStr, sizeof (eSPIStr), "isa@%X,%X", DevBase, FunBase); eSPINode = FdtAddSubnode (Fdt, TempNode, eSPIStr); - Status = FdtSetProp (Fdt, eSPINode, "compatible", "isa", (UINT32)(AsciiStrLen ("isa")+1)); + Status = FdtSetProperty (Fdt, eSPINode, "compatible", "isa", (UINT32)(AsciiStrLen ("isa")+1)); ASSERT_EFI_ERROR (Status); Data32 = CpuToFdt32 (1); - Status = FdtSetProp (Fdt, eSPINode, "#size-cells", &Data32, sizeof (UINT32)); + Status = FdtSetProperty (Fdt, eSPINode, "#size-cells", &Data32, sizeof (UINT32)); Data32 = CpuToFdt32 (2); - Status = FdtSetProp (Fdt, eSPINode, "#address-cells", &Data32, sizeof (UINT32)); + Status = FdtSetProperty (Fdt, eSPINode, "#address-cells", &Data32, sizeof (UINT32)); Status = BuildFdtForSerial (eSPINode, FdtBase); ASSERT_EFI_ERROR (Status); } @@ -757,52 +811,52 @@ BuildFdtForFrameBuffer ( TempNode = FdtAddSubnode (Fdt, 0, TempStr); ASSERT (TempNode > 0); - Status = FdtSetProp (Fdt, TempNode, "display", "&gma", (UINT32)(AsciiStrLen ("&gma")+1)); + Status = FdtSetProperty (Fdt, TempNode, "display", "&gma", (UINT32)(AsciiStrLen ("&gma")+1)); ASSERT_EFI_ERROR (Status); - Status = FdtSetProp (Fdt, TempNode, "format", "a8r8g8b8", (UINT32)(AsciiStrLen ("a8r8g8b8")+1)); + Status = FdtSetProperty (Fdt, TempNode, "format", "a8r8g8b8", (UINT32)(AsciiStrLen ("a8r8g8b8")+1)); ASSERT_EFI_ERROR (Status); Data32 = CpuToFdt32 (GraphicsInfo->GraphicsMode.VerticalResolution); - Status = FdtSetProp (Fdt, TempNode, "height", &Data32, sizeof (UINT32)); + Status = FdtSetProperty (Fdt, TempNode, "height", &Data32, sizeof (UINT32)); ASSERT_EFI_ERROR (Status); Data32 = CpuToFdt32 (GraphicsInfo->GraphicsMode.HorizontalResolution); - Status = FdtSetProp (Fdt, TempNode, "width", &Data32, sizeof (UINT32)); + Status = FdtSetProperty (Fdt, TempNode, "width", &Data32, sizeof (UINT32)); ASSERT_EFI_ERROR (Status); RegData[0] = CpuToFdt64 (GraphicsInfo->FrameBufferBase); RegData[1] = CpuToFdt64 (GraphicsInfo->FrameBufferSize); - Status = FdtSetProp (Fdt, TempNode, "reg", &RegData, sizeof (RegData)); + Status = FdtSetProperty (Fdt, TempNode, "reg", &RegData, sizeof (RegData)); ASSERT_EFI_ERROR (Status); - Status = FdtSetProp (Fdt, TempNode, "compatible", "simple-framebuffer", (UINT32)(AsciiStrLen ("simple-framebuffer")+1)); + Status = FdtSetProperty (Fdt, TempNode, "compatible", "simple-framebuffer", (UINT32)(AsciiStrLen ("simple-framebuffer")+1)); ASSERT_EFI_ERROR (Status); } else { Status = AsciiSPrint (TempStr, sizeof (TempStr), "framebuffer@%lX", 0xB0000000); TempNode = FdtAddSubnode (Fdt, 0, TempStr); ASSERT (TempNode > 0); - Status = FdtSetProp (Fdt, TempNode, "display", "&gma", (UINT32)(AsciiStrLen ("&gma")+1)); + Status = FdtSetProperty (Fdt, TempNode, "display", "&gma", (UINT32)(AsciiStrLen ("&gma")+1)); ASSERT_EFI_ERROR (Status); - Status = FdtSetProp (Fdt, TempNode, "format", "a8r8g8b8", (UINT32)(AsciiStrLen ("a8r8g8b8")+1)); + Status = FdtSetProperty (Fdt, TempNode, "format", "a8r8g8b8", (UINT32)(AsciiStrLen ("a8r8g8b8")+1)); ASSERT_EFI_ERROR (Status); Data32 = CpuToFdt32 (1024); - Status = FdtSetProp (Fdt, TempNode, "height", &Data32, sizeof (UINT32)); + Status = FdtSetProperty (Fdt, TempNode, "height", &Data32, sizeof (UINT32)); ASSERT_EFI_ERROR (Status); Data32 = CpuToFdt32 (1280); - Status = FdtSetProp (Fdt, TempNode, "width", &Data32, sizeof (UINT32)); + Status = FdtSetProperty (Fdt, TempNode, "width", &Data32, sizeof (UINT32)); ASSERT_EFI_ERROR (Status); RegData[0] = CpuToFdt64 (0xB0000000); RegData[1] = CpuToFdt64 (0x500000); - Status = FdtSetProp (Fdt, TempNode, "reg", &RegData, sizeof (RegData)); + Status = FdtSetProperty (Fdt, TempNode, "reg", &RegData, sizeof (RegData)); ASSERT_EFI_ERROR (Status); - Status = FdtSetProp (Fdt, TempNode, "compatible", "simple-framebuffer", (UINT32)(AsciiStrLen ("simple-framebuffer")+1)); + Status = FdtSetProperty (Fdt, TempNode, "compatible", "simple-framebuffer", (UINT32)(AsciiStrLen ("simple-framebuffer")+1)); ASSERT_EFI_ERROR (Status); } @@ -855,35 +909,35 @@ BuildFdtForUplRequired ( ASSERT (CpuHob != NULL); if (mResourceAssigned) { - Status = FdtSetProp (Fdt, UPLParaNode, "pci-enum-done", NULL, 0); + Status = FdtSetProperty (Fdt, UPLParaNode, "pci-enum-done", NULL, 0); ASSERT_EFI_ERROR (Status); } BootMode = GetBootModeHob (); Data32 = CpuToFdt32 ((UINT32)CpuHob->SizeOfMemorySpace); - Status = FdtSetProp (Fdt, UPLParaNode, "addr-width", &Data32, sizeof (Data32)); + Status = FdtSetProperty (Fdt, UPLParaNode, "addr-width", &Data32, sizeof (Data32)); ASSERT_EFI_ERROR (Status); if (BootMode == BOOT_WITH_FULL_CONFIGURATION) { - Status = FdtSetProp (Fdt, UPLParaNode, "boot-mode", "normal", (UINT32)(AsciiStrLen ("normal")+1)); + Status = FdtSetProperty (Fdt, UPLParaNode, "boot-mode", "normal", (UINT32)(AsciiStrLen ("normal")+1)); } else if (BootMode == BOOT_WITH_MINIMAL_CONFIGURATION) { - Status = FdtSetProp (Fdt, UPLParaNode, "boot-mode", "fast", (UINT32)(AsciiStrLen ("fast")+1)); + Status = FdtSetProperty (Fdt, UPLParaNode, "boot-mode", "fast", (UINT32)(AsciiStrLen ("fast")+1)); } else if (BootMode == BOOT_WITH_FULL_CONFIGURATION_PLUS_DIAGNOSTICS) { - Status = FdtSetProp (Fdt, UPLParaNode, "boot-mode", "full", (UINT32)(AsciiStrLen ("full")+1)); + Status = FdtSetProperty (Fdt, UPLParaNode, "boot-mode", "full", (UINT32)(AsciiStrLen ("full")+1)); } else if (BootMode == BOOT_WITH_DEFAULT_SETTINGS) { - Status = FdtSetProp (Fdt, UPLParaNode, "boot-mode", "default", (UINT32)(AsciiStrLen ("default")+1)); + Status = FdtSetProperty (Fdt, UPLParaNode, "boot-mode", "default", (UINT32)(AsciiStrLen ("default")+1)); } else if (BootMode == BOOT_ON_S4_RESUME) { - Status = FdtSetProp (Fdt, UPLParaNode, "boot-mode", "s4", (UINT32)(AsciiStrLen ("s4")+1)); + Status = FdtSetProperty (Fdt, UPLParaNode, "boot-mode", "s4", (UINT32)(AsciiStrLen ("s4")+1)); } else if (BootMode == BOOT_ON_S3_RESUME) { - Status = FdtSetProp (Fdt, UPLParaNode, "boot-mode", "s3", (UINT32)(AsciiStrLen ("s3")+1)); + Status = FdtSetProperty (Fdt, UPLParaNode, "boot-mode", "s3", (UINT32)(AsciiStrLen ("s3")+1)); } else { - Status = FdtSetProp (Fdt, UPLParaNode, "boot-mode", "na", (UINT32)(AsciiStrLen ("na")+1)); + Status = FdtSetProperty (Fdt, UPLParaNode, "boot-mode", "na", (UINT32)(AsciiStrLen ("na")+1)); } ASSERT_EFI_ERROR (Status); - Status = FdtSetProp (Fdt, UPLParaNode, "compatible", "upl", (UINT32)(AsciiStrLen ("upl")+1)); + Status = FdtSetProperty (Fdt, UPLParaNode, "compatible", "upl", (UINT32)(AsciiStrLen ("upl")+1)); ASSERT_EFI_ERROR (Status); GuidHob = GetFirstGuidHob (&gUniversalPayloadBaseGuid); @@ -896,7 +950,7 @@ BuildFdtForUplRequired ( UPLImageNode = FdtAddSubnode (Fdt, ParentNode, TempStr); Data64 = CpuToFdt64 ((UINTN)Fit); - Status = FdtSetProp (FdtBase, UPLImageNode, "addr", &Data64, sizeof (Data64)); + Status = FdtSetProperty (FdtBase, UPLImageNode, "addr", &Data64, sizeof (Data64)); } CustomNode = FdtAddSubnode (Fdt, ParentNode, "upl-custom"); @@ -904,7 +958,7 @@ BuildFdtForUplRequired ( HobPtr = GetHobList (); Data64 = CpuToFdt64 ((UINT64)(EFI_PHYSICAL_ADDRESS)HobPtr); - Status = FdtSetProp (Fdt, CustomNode, "hoblistptr", &Data64, sizeof (Data64)); + Status = FdtSetProperty (Fdt, CustomNode, "hoblistptr", &Data64, sizeof (Data64)); ASSERT_EFI_ERROR (Status); return Status; diff --git a/UefiPayloadPkg/Library/CustomFdtNodeParserLib/CustomFdtNodeParserLib.c b/UefiPayloadPkg/Library/CustomFdtNodeParserLib/CustomFdtNodeParserLib.c index 0c454496dcca..5ce0aa315c9b 100644 --- a/UefiPayloadPkg/Library/CustomFdtNodeParserLib/CustomFdtNodeParserLib.c +++ b/UefiPayloadPkg/Library/CustomFdtNodeParserLib/CustomFdtNodeParserLib.c @@ -87,6 +87,10 @@ FitIsHobNeed ( } if (Hob.Header->HobType == EFI_HOB_TYPE_GUID_EXTENSION) { + if (CompareGuid (&Hob.Guid->Name, &gUniversalPayloadSmbios3TableGuid)) { + return FALSE; + } + if (CompareGuid (&Hob.Guid->Name, &gUniversalPayloadSerialPortInfoGuid)) { return FALSE; } diff --git a/UefiPayloadPkg/Library/CustomFdtNodeParserLib/CustomFdtNodeParserLib.inf b/UefiPayloadPkg/Library/CustomFdtNodeParserLib/CustomFdtNodeParserLib.inf index 036ed4315dd0..6f1e5fc8c9bd 100644 --- a/UefiPayloadPkg/Library/CustomFdtNodeParserLib/CustomFdtNodeParserLib.inf +++ b/UefiPayloadPkg/Library/CustomFdtNodeParserLib/CustomFdtNodeParserLib.inf @@ -40,6 +40,7 @@ gUniversalPayloadSerialPortInfoGuid gUniversalPayloadDeviceTreeGuid gUniversalPayloadAcpiTableGuid + gUniversalPayloadSmbios3TableGuid gEfiHobMemoryAllocModuleGuid [Pcd] diff --git a/UefiPayloadPkg/Library/FdtParserLib/FdtParserLib.c b/UefiPayloadPkg/Library/FdtParserLib/FdtParserLib.c index 09b7372b9ab4..740309930099 100644 --- a/UefiPayloadPkg/Library/FdtParserLib/FdtParserLib.c +++ b/UefiPayloadPkg/Library/FdtParserLib/FdtParserLib.c @@ -253,7 +253,7 @@ ParseReservedMemory ( StartAddress = Fdt64ToCpu (*Data64); NumberOfBytes = Fdt64ToCpu (*(Data64 + 1)); DEBUG ((DEBUG_INFO, "\n Property %a", TempStr)); - DEBUG ((DEBUG_INFO, " %016lX %016lX", StartAddress, NumberOfBytes)); + DEBUG ((DEBUG_INFO, " %016lX %016lX\n", StartAddress, NumberOfBytes)); } RecordMemoryNode (SubNode); @@ -264,34 +264,38 @@ ParseReservedMemory ( } else { PropertyPtr = FdtGetProperty (Fdt, SubNode, "compatible", &TempLen); TempStr = (CHAR8 *)(PropertyPtr->Data); + DEBUG ((DEBUG_INFO, "compatible: %a\n", TempStr)); if (AsciiStrnCmp (TempStr, "boot-code", AsciiStrLen ("boot-code")) == 0) { - DEBUG ((DEBUG_INFO, " boot-code")); + DEBUG ((DEBUG_INFO, " boot-code\n")); BuildMemoryAllocationHob (StartAddress, NumberOfBytes, EfiBootServicesCode); } else if (AsciiStrnCmp (TempStr, "boot-data", AsciiStrLen ("boot-data")) == 0) { - DEBUG ((DEBUG_INFO, " boot-data")); + DEBUG ((DEBUG_INFO, " boot-data\n")); BuildMemoryAllocationHob (StartAddress, NumberOfBytes, EfiBootServicesData); } else if (AsciiStrnCmp (TempStr, "runtime-code", AsciiStrLen ("runtime-code")) == 0) { - DEBUG ((DEBUG_INFO, " runtime-code")); + DEBUG ((DEBUG_INFO, " runtime-code\n")); BuildMemoryAllocationHob (StartAddress, NumberOfBytes, EfiRuntimeServicesCode); } else if (AsciiStrnCmp (TempStr, "runtime-data", AsciiStrLen ("runtime-data")) == 0) { - DEBUG ((DEBUG_INFO, " runtime-data")); + DEBUG ((DEBUG_INFO, " runtime-data\n")); BuildMemoryAllocationHob (StartAddress, NumberOfBytes, EfiRuntimeServicesData); } else if (AsciiStrnCmp (TempStr, "special-purpose", AsciiStrLen ("special-purpose")) == 0) { Attribute = MEMORY_ATTRIBUTE_DEFAULT | EFI_RESOURCE_ATTRIBUTE_SPECIAL_PURPOSE; - DEBUG ((DEBUG_INFO, " special-purpose memory")); + DEBUG ((DEBUG_INFO, " special-purpose memory\n")); BuildResourceDescriptorHob (EFI_RESOURCE_SYSTEM_MEMORY, Attribute, StartAddress, NumberOfBytes); + } else if (AsciiStrnCmp (TempStr, "acpi-nvs", AsciiStrLen ("acpi-nvs")) == 0) { + DEBUG ((DEBUG_INFO, "\n ********* acpi-nvs ********\n")); + BuildMemoryAllocationHob (StartAddress, NumberOfBytes, EfiACPIMemoryNVS); } else if (AsciiStrnCmp (TempStr, "acpi", AsciiStrLen ("acpi")) == 0) { - DEBUG ((DEBUG_INFO, " acpi, StartAddress:%x, NumberOfBytes:%x", StartAddress, NumberOfBytes)); + DEBUG ((DEBUG_INFO, " acpi, StartAddress:%x, NumberOfBytes:%x\n", StartAddress, NumberOfBytes)); BuildMemoryAllocationHob (StartAddress, NumberOfBytes, EfiBootServicesData); PlatformAcpiTable = BuildGuidHob (&gUniversalPayloadAcpiTableGuid, sizeof (UNIVERSAL_PAYLOAD_ACPI_TABLE)); if (PlatformAcpiTable != NULL) { - DEBUG ((DEBUG_INFO, " build gUniversalPayloadAcpiTableGuid , NumberOfBytes:%x", NumberOfBytes)); + DEBUG ((DEBUG_INFO, " build gUniversalPayloadAcpiTableGuid , NumberOfBytes:%x\n", NumberOfBytes)); PlatformAcpiTable->Rsdp = (EFI_PHYSICAL_ADDRESS)(UINTN)StartAddress; PlatformAcpiTable->Header.Revision = UNIVERSAL_PAYLOAD_ACPI_TABLE_REVISION; PlatformAcpiTable->Header.Length = sizeof (UNIVERSAL_PAYLOAD_ACPI_TABLE); } } else if (AsciiStrnCmp (TempStr, "smbios", AsciiStrLen ("smbios")) == 0) { - DEBUG ((DEBUG_INFO, " build smbios, NumberOfBytes:%x", NumberOfBytes)); + DEBUG ((DEBUG_INFO, " build smbios, NumberOfBytes:%x\n", NumberOfBytes)); BuildMemoryAllocationHob (StartAddress, NumberOfBytes, EfiBootServicesData); SmbiosTable = BuildGuidHob (&gUniversalPayloadSmbios3TableGuid, sizeof (UNIVERSAL_PAYLOAD_SMBIOS_TABLE)); if (SmbiosTable != NULL) { @@ -299,9 +303,6 @@ ParseReservedMemory ( SmbiosTable->Header.Length = sizeof (UNIVERSAL_PAYLOAD_SMBIOS_TABLE); SmbiosTable->SmBiosEntryPoint = (EFI_PHYSICAL_ADDRESS)(UINTN)(StartAddress); } - } else if (AsciiStrnCmp (TempStr, "acpi-nvs", AsciiStrLen ("acpi-nvs")) == 0) { - DEBUG ((DEBUG_INFO, " acpi-nvs")); - BuildMemoryAllocationHob (StartAddress, NumberOfBytes, EfiACPIMemoryNVS); } else { BuildMemoryAllocationHob (StartAddress, NumberOfBytes, EfiReservedMemoryType); } @@ -889,10 +890,10 @@ ParseDtb ( } } - NumRsv = FdtNumRsv (Fdt); + NumRsv = FdtGetNumberOfReserveMapEntries (Fdt); /* Look for an existing entry and add it to the efi mem map. */ for (index = 0; index < NumRsv; index++) { - if (FdtGetMemRsv (Fdt, index, &Addr, &Size) != 0) { + if (FdtGetReserveMapEntry (Fdt, index, &Addr, &Size) != 0) { continue; } diff --git a/UefiPayloadPkg/PayloadLoaderPeim/FitLib.h b/UefiPayloadPkg/PayloadLoaderPeim/FitLib.h index 6a93b4159011..05b790b42e2f 100644 --- a/UefiPayloadPkg/PayloadLoaderPeim/FitLib.h +++ b/UefiPayloadPkg/PayloadLoaderPeim/FitLib.h @@ -12,8 +12,8 @@ SPDX-License-Identifier: BSD-2-Clause-Patent #include typedef struct { - UINT64 RelocateType; UINT64 Offset; + UINT64 RelocateType; } FIT_RELOCATE_ITEM; typedef struct { diff --git a/UefiPayloadPkg/PayloadLoaderPeim/FitPayloadLoaderPeim.c b/UefiPayloadPkg/PayloadLoaderPeim/FitPayloadLoaderPeim.c index d659b7547433..7885a52fed9c 100644 --- a/UefiPayloadPkg/PayloadLoaderPeim/FitPayloadLoaderPeim.c +++ b/UefiPayloadPkg/PayloadLoaderPeim/FitPayloadLoaderPeim.c @@ -35,6 +35,43 @@ EFI_PEI_PPI_DESCRIPTOR mEndOfPeiSignalPpi = { NULL }; +#if (FixedPcdGetBool (PcdHandOffFdtEnable) == 0) + +/** + Notify ReadyToPayLoad signal. + @param[in] PeiServices An indirect pointer to the EFI_PEI_SERVICES table published by the PEI Foundation. + @param[in] NotifyDescriptor Address of the notification descriptor data structure. + @param[in] Ppi Address of the PPI that was installed. + @retval EFI_SUCCESS Hobs data is discovered. + @return Others No Hobs data is discovered. +**/ +EFI_STATUS +EFIAPI +EndOfPeiPpiNotifyCallback ( + IN EFI_PEI_SERVICES **PeiServices, + IN EFI_PEI_NOTIFY_DESCRIPTOR *NotifyDescriptor, + IN VOID *Ppi + ) +{ + EFI_STATUS Status; + + // + // Ready to Payload phase signal + // + Status = PeiServicesInstallPpi (&gReadyToPayloadSignalPpi); + + return Status; +} + +EFI_PEI_NOTIFY_DESCRIPTOR mEndOfPeiNotifyList[] = { + { + (EFI_PEI_PPI_DESCRIPTOR_NOTIFY_CALLBACK | EFI_PEI_PPI_DESCRIPTOR_TERMINATE_LIST), + &gEfiEndOfPeiSignalPpiGuid, + EndOfPeiPpiNotifyCallback + } +}; +#endif + /** The wrapper function of PeiLoadImageLoadImage(). @param This - Pointer to EFI_PEI_LOAD_FILE_PPI. @@ -144,13 +181,14 @@ PeiLoadFileLoadPayload ( *ImageSizeArg = Context.PayloadSize; *EntryPoint = Context.PayloadEntryPoint; + #if (FixedPcdGetBool (PcdHandOffFdtEnable)) + Status = PeiServicesInstallPpi (&mEndOfPeiSignalPpi); ASSERT_EFI_ERROR (Status); Status = PeiServicesInstallPpi (&gReadyToPayloadSignalPpi); ASSERT_EFI_ERROR (Status); - #if (FixedPcdGetBool (PcdHandOffFdtEnable)) Hob = GetFirstGuidHob (&gUniversalPayloadDeviceTreeGuid); if (Hob != NULL) { Fdt = (UNIVERSAL_PAYLOAD_DEVICE_TREE *)GET_GUID_HOB_DATA (Hob); @@ -178,6 +216,9 @@ PeiLoadFileLoadPayload ( NULL, TopOfStack ); + #else + Status = PeiServicesNotifyPpi (&mEndOfPeiNotifyList[0]); + ASSERT_EFI_ERROR (Status); #endif return EFI_SUCCESS; @@ -299,8 +340,8 @@ FdtPpiNotifyCallback ( // Set cell property of root node Data32 = CpuToFdt32 (2); - Status = FdtSetProp (FdtBase, 0, "#address-cells", &Data32, sizeof (UINT32)); - Status = FdtSetProp (FdtBase, 0, "#size-cells", &Data32, sizeof (UINT32)); + Status = FdtSetProperty (FdtBase, 0, "#address-cells", &Data32, sizeof (UINT32)); + Status = FdtSetProperty (FdtBase, 0, "#size-cells", &Data32, sizeof (UINT32)); Status = BuildFdtForUPL (FdtBase); ASSERT_EFI_ERROR (Status); diff --git a/UefiPayloadPkg/Readme.md b/UefiPayloadPkg/Readme.md index 4149eab90d08..0ddc159114a7 100644 --- a/UefiPayloadPkg/Readme.md +++ b/UefiPayloadPkg/Readme.md @@ -2,10 +2,10 @@ Provide UEFI Universal Payload for different bootloader to generate EFI environment # Spec -UniversalPayload URL: https://universalscalablefirmware.github.io/documentation/2_universal_payload.html -UniversalPayload URL: https://universalpayload.github.io/spec/ -ELF Format URL: https://refspecs.linuxfoundation.org/elf/elf.pdf -FIT Format URL: https://universalpayload.github.io/spec/chapter2-payload-image-format.html +- UniversalPayload URL: https://universalscalablefirmware.github.io/documentation/2_universal_payload.html +- UniversalPayload URL: https://universalpayload.github.io/spec/ +- ELF Format URL: https://refspecs.linuxfoundation.org/elf/elf.pdf +- FIT Format URL: https://universalpayload.github.io/spec/chapter2-payload-image-format.html # Uefi UniversalPayload Format | Binary Format | HandOffPayload - HOB | @@ -48,29 +48,19 @@ FIT Format URL: https://universalpayload.github.io/spec/chapter2-payload-image-f + +-----------------------+ ``` -# Environment +# Build Environment - ELF ``` - Download and install https://github.com/llvm/llvm-project/releases/tag/llvmorg-10.0.1 + Install GCC compiler on linux and MSVC compiler on windows + Install CLANG compiler https://github.com/llvm/llvm-project/releases/tag/llvmorg-10.0.1 on windows and linux ``` - FIT - - Windows - ``` - Download and install swig by https://swig.org/ and also set install path into environment variable - ``` - ```powershell - Set-ExecutionPolicy Bypass -Scope Process -Force; [System.Net.ServicePointManager]::SecurityProtocol = [System.Net.ServicePointManager]::SecurityProtocol -bor 3072; iex ((New-Object System.Net.WebClient).DownloadString('https://chocolatey.org/install.ps1')) - choco install dtc-msys2 - pip3 install pefile - pip3 install pylibfdt - ``` - - Ubuntu - ```bash - sudo apt install -y u-boot-tools - pip3 install pefile - pip3 install swig - pip3 install pylibfdt - ``` + ``` + Install GCC compiler on linux and MSVC compiler on windows + pip3 install pefile + pip3 install pylibfdt + ``` + # How to build UEFI UniversalPayload - Windows - edksetup Rebuild @@ -84,6 +74,24 @@ FIT Format URL: https://universalpayload.github.io/spec/chapter2-payload-image-f - UniversalPayload.fit - python UefiPayloadPkg/UniversalPayloadBuild.py -t --Fit + +# How to dump payload binary data + - UniversalPayload.elf + - Install elf dump tools https://github.com/llvm/llvm-project/releases/tag/llvmorg-10.0.1 + - llvm-objdump -h Build/UefiPayloadPkgX64/UniversalPayload.elf + + - UniversalPayload.fit + - Install fdtdump tool + - Windows + ```powershell + Set-ExecutionPolicy Bypass -Scope Process -Force; [System.Net.ServicePointManager]::SecurityProtocol = [System.Net.ServicePointManager]::SecurityProtocol -bor 3072; iex ((New-Object System.Net.WebClient).DownloadString('https://chocolatey.org/install.ps1')) + choco install dtc-msys2 + ``` + - Linux + ```bash + sudo apt install -y u-boot-tools + ``` + - fdtdump Build/UefiPayloadPkgX64/UniversalPayload.fit # Edk2boot + UefiUniversalPayload diff --git a/UefiPayloadPkg/UefiPayloadPkg.ci.yaml b/UefiPayloadPkg/UefiPayloadPkg.ci.yaml index ac43a7a8ee46..84e3f14b6864 100644 --- a/UefiPayloadPkg/UefiPayloadPkg.ci.yaml +++ b/UefiPayloadPkg/UefiPayloadPkg.ci.yaml @@ -96,5 +96,6 @@ "BLD_*_DISABLE_RESET_SYSTEM": "TRUE", "BLD_*_SERIAL_DRIVER_ENABLE": "FALSE", "BLD_*_BUILD_ARCH": "", + "BLD_*_SECURE_BOOT_ENABLE": "TRUE", } } diff --git a/UefiPayloadPkg/UefiPayloadPkg.dsc b/UefiPayloadPkg/UefiPayloadPkg.dsc index 3c0f2d699b0b..61b5f8f992f0 100644 --- a/UefiPayloadPkg/UefiPayloadPkg.dsc +++ b/UefiPayloadPkg/UefiPayloadPkg.dsc @@ -42,6 +42,7 @@ DEFINE BOOTSPLASH_IMAGE = FALSE DEFINE NVME_ENABLE = TRUE DEFINE CAPSULE_SUPPORT = FALSE + DEFINE LOCKBOX_SUPPORT = FALSE # # Crypto Support @@ -153,6 +154,11 @@ DEFINE MULTIPLE_DEBUG_PORT_SUPPORT = FALSE + # + # Security + # + DEFINE SECURE_BOOT_ENABLE = FALSE + [BuildOptions] *_*_*_CC_FLAGS = -D DISABLE_NEW_DEPRECATED_INTERFACES !if $(USE_CBMEM_FOR_CONSOLE) == FALSE @@ -298,9 +304,23 @@ !endif DebugLib|MdeModulePkg/Library/PeiDxeDebugLibReportStatusCode/PeiDxeDebugLibReportStatusCode.inf +!if $(LOCKBOX_SUPPORT) == TRUE + LockBoxLib|MdeModulePkg/Library/SmmLockBoxLib/SmmLockBoxDxeLib.inf +!else LockBoxLib|MdeModulePkg/Library/LockBoxNullLib/LockBoxNullLib.inf +!endif FileExplorerLib|MdeModulePkg/Library/FileExplorerLib/FileExplorerLib.inf + +!if $(SECURE_BOOT_ENABLE) == TRUE + PlatformSecureLib|SecurityPkg/Library/PlatformSecureLibNull/PlatformSecureLibNull.inf + AuthVariableLib|SecurityPkg/Library/AuthVariableLib/AuthVariableLib.inf + SecureBootVariableLib|SecurityPkg/Library/SecureBootVariableLib/SecureBootVariableLib.inf + PlatformPKProtectionLib|SecurityPkg/Library/PlatformPKProtectionLibVarPolicy/PlatformPKProtectionLibVarPolicy.inf + SecureBootVariableProvisionLib|SecurityPkg/Library/SecureBootVariableProvisionLib/SecureBootVariableProvisionLib.inf +!else AuthVariableLib|MdeModulePkg/Library/AuthVariableLibNull/AuthVariableLibNull.inf +!endif + !if $(VARIABLE_SUPPORT) == "EMU" TpmMeasurementLib|MdeModulePkg/Library/TpmMeasurementLibNull/TpmMeasurementLibNull.inf !elseif $(VARIABLE_SUPPORT) == "SPI" @@ -391,6 +411,9 @@ !endif [LibraryClasses.common.DXE_RUNTIME_DRIVER] +!if $(SECURE_BOOT_ENABLE) == TRUE + BaseCryptLib|CryptoPkg/Library/BaseCryptLib/RuntimeCryptLib.inf +!endif PcdLib|MdePkg/Library/DxePcdLib/DxePcdLib.inf MemoryAllocationLib|MdePkg/Library/UefiMemoryAllocationLib/UefiMemoryAllocationLib.inf ReportStatusCodeLib|MdeModulePkg/Library/RuntimeDxeReportStatusCodeLib/RuntimeDxeReportStatusCodeLib.inf @@ -522,6 +545,13 @@ !endif +!if $(SECURE_BOOT_ENABLE) == TRUE + # Override the default values from SecurityPkg to ensure images from all sources are verified in secure boot + gEfiSecurityPkgTokenSpaceGuid.PcdOptionRomImageVerificationPolicy|0x04 + gEfiSecurityPkgTokenSpaceGuid.PcdFixedMediaImageVerificationPolicy|0x04 + gEfiSecurityPkgTokenSpaceGuid.PcdRemovableMediaImageVerificationPolicy|0x04 +!endif + [PcdsPatchableInModule.X64] !if $(NETWORK_DRIVER_ENABLE) == TRUE gEfiNetworkPkgTokenSpaceGuid.PcdAllowHttpConnections|TRUE @@ -711,8 +741,18 @@ # Components that produce the architectural protocols # !if $(SECURITY_STUB_ENABLE) == TRUE - MdeModulePkg/Universal/SecurityStubDxe/SecurityStubDxe.inf + MdeModulePkg/Universal/SecurityStubDxe/SecurityStubDxe.inf { + +!if $(SECURE_BOOT_ENABLE) == TRUE + NULL|SecurityPkg/Library/DxeImageVerificationLib/DxeImageVerificationLib.inf !endif + } +!endif + +!if $(SECURE_BOOT_ENABLE) == TRUE + SecurityPkg/VariableAuthenticated/SecureBootConfigDxe/SecureBootConfigDxe.inf +!endif + UefiCpuPkg/CpuDxe/CpuDxe.inf MdeModulePkg/Universal/BdsDxe/BdsDxe.inf !if $(BOOTSPLASH_IMAGE) diff --git a/UefiPayloadPkg/UefiPayloadPkg.fdf b/UefiPayloadPkg/UefiPayloadPkg.fdf index c1b1e35f325c..e788f27cc122 100644 --- a/UefiPayloadPkg/UefiPayloadPkg.fdf +++ b/UefiPayloadPkg/UefiPayloadPkg.fdf @@ -17,8 +17,8 @@ DEFINE FD_SIZE = 0x00850000 DEFINE NUM_BLOCKS = 0x850 !else -DEFINE FD_SIZE = 0x00590000 -DEFINE NUM_BLOCKS = 0x590 +DEFINE FD_SIZE = 0x00700000 +DEFINE NUM_BLOCKS = 0x700 !endif ################################################################################ @@ -208,6 +208,12 @@ INF PcAtChipsetPkg/PcatRealTimeClockRuntimeDxe/PcatRealTimeClockRuntimeDxe.inf INF MdeModulePkg/Universal/Variable/RuntimeDxe/VariableSmmRuntimeDxe.inf !endif +!if $(UNIVERSAL_PAYLOAD) == FALSE + !if $(SECURE_BOOT_ENABLE) == TRUE + INF SecurityPkg/VariableAuthenticated/SecureBootConfigDxe/SecureBootConfigDxe.inf + !endif +!endif + INF UefiCpuPkg/CpuIo2Dxe/CpuIo2Dxe.inf INF MdeModulePkg/Universal/DevicePathDxe/DevicePathDxe.inf !if $(MEMORY_TEST) == "GENERIC" @@ -333,6 +339,35 @@ INF ShellPkg/DynamicCommand/DpDynamicCommand/DpDynamicCommand.inf INF ShellPkg/Application/Shell/Shell.inf !endif +!if $(UNIVERSAL_PAYLOAD) == TRUE +!if $(SECURE_BOOT_ENABLE) == TRUE + +[FV.SECFV] +FvNameGuid = 2700E2F3-19D2-4E2D-9F13-BC891B9FC62C +BlockSize = $(FD_BLOCK_SIZE) +FvForceRebase = FALSE +FvAlignment = 16 +ERASE_POLARITY = 1 +MEMORY_MAPPED = TRUE +STICKY_WRITE = TRUE +LOCK_CAP = TRUE +LOCK_STATUS = TRUE +WRITE_DISABLED_CAP = TRUE +WRITE_ENABLED_CAP = TRUE +WRITE_STATUS = TRUE +WRITE_LOCK_CAP = TRUE +WRITE_LOCK_STATUS = TRUE +READ_DISABLED_CAP = TRUE +READ_ENABLED_CAP = TRUE +READ_STATUS = TRUE +READ_LOCK_CAP = TRUE +READ_LOCK_STATUS = TRUE + +INF SecurityPkg/VariableAuthenticated/SecureBootConfigDxe/SecureBootConfigDxe.inf + +!endif +!endif + ################################################################################ # diff --git a/UefiPayloadPkg/UniversalPayloadBuild.py b/UefiPayloadPkg/UniversalPayloadBuild.py index 59c78a21b405..404edfb57b25 100644 --- a/UefiPayloadPkg/UniversalPayloadBuild.py +++ b/UefiPayloadPkg/UniversalPayloadBuild.py @@ -144,6 +144,7 @@ def BuildUniversalPayload(Args): EntryModuleInf = os.path.normpath("UefiPayloadPkg/UefiPayloadEntry/{}.inf".format (UpldEntryFile)) DxeFvOutputDir = os.path.join(BuildDir, "{}_{}".format (BuildTarget, ToolChain), os.path.normpath("FV/DXEFV.Fv")) BdsFvOutputDir = os.path.join(BuildDir, "{}_{}".format (BuildTarget, ToolChain), os.path.normpath("FV/BDSFV.Fv")) + SecFvOutputDir = os.path.join(BuildDir, "{}_{}".format (BuildTarget, ToolChain), os.path.normpath("FV/SECFV.Fv")) NetworkFvOutputDir = os.path.join(BuildDir, "{}_{}".format (BuildTarget, ToolChain), os.path.normpath("FV/NETWORKFV.Fv")) PayloadReportPath = os.path.join(BuildDir, "UefiUniversalPayload.txt") ModuleReportPath = os.path.join(BuildDir, "UefiUniversalPayloadEntry.txt") @@ -212,6 +213,7 @@ def BuildUniversalPayload(Args): MultiFvList = [ ['uefi_fv', os.path.join(BuildDir, "{}_{}".format (BuildTarget, ToolChain), os.path.normpath("FV/DXEFV.Fv")) ], ['bds_fv', os.path.join(BuildDir, "{}_{}".format (BuildTarget, ToolChain), os.path.normpath("FV/BDSFV.Fv")) ], + ['sec_fv', os.path.join(BuildDir, "{}_{}".format (BuildTarget, ToolChain), os.path.normpath("FV/SECFV.Fv")) ], ['network_fv', os.path.join(BuildDir, "{}_{}".format (BuildTarget, ToolChain), os.path.normpath("FV/NETWORKFV.Fv"))], ] @@ -234,6 +236,7 @@ def BuildUniversalPayload(Args): fit_image_info_header.TargetPath = os.path.join(BuildDir, 'UniversalPayload.fit') fit_image_info_header.UefifvPath = DxeFvOutputDir fit_image_info_header.BdsfvPath = BdsFvOutputDir + fit_image_info_header.SecfvPath = SecFvOutputDir fit_image_info_header.NetworkfvPath = NetworkFvOutputDir fit_image_info_header.DataOffset = 0x1000 fit_image_info_header.LoadAddr = Args.LoadAddress @@ -269,7 +272,7 @@ def BuildUniversalPayload(Args): continue Type = entry.type Offset = entry.rva + fit_image_info_header.DataOffset - RelocBinary += Type.to_bytes (8, 'little') + Offset.to_bytes (8, 'little') + RelocBinary += Offset.to_bytes (8, 'little') + Type.to_bytes (8, 'little') RelocBinary += b'\x00' * (0x1000 - (len(RelocBinary) % 0x1000)) # diff --git a/UnitTestFrameworkPkg/Library/UnitTestLib/Assert.c b/UnitTestFrameworkPkg/Library/UnitTestLib/Assert.c index 53cb71f61065..52752e0adc62 100644 --- a/UnitTestFrameworkPkg/Library/UnitTestLib/Assert.c +++ b/UnitTestFrameworkPkg/Library/UnitTestLib/Assert.c @@ -33,7 +33,7 @@ AddUnitTestFailure ( UnitTest->FailureType = FailureType; AsciiStrCpyS ( &UnitTest->FailureMessage[0], - UNIT_TEST_TESTFAILUREMSG_LENGTH, + UNIT_TEST_MAX_STRING_LENGTH, FailureMessage ); @@ -50,7 +50,7 @@ UnitTestLogFailure ( ) { UNIT_TEST_FRAMEWORK_HANDLE FrameworkHandle; - CHAR8 LogString[UNIT_TEST_TESTFAILUREMSG_LENGTH]; + CHAR8 LogString[UNIT_TEST_MAX_STRING_LENGTH]; VA_LIST Marker; // diff --git a/UnitTestFrameworkPkg/Library/UnitTestLib/Log.c b/UnitTestFrameworkPkg/Library/UnitTestLib/Log.c index f61b9d57b10a..88cf826b8863 100644 --- a/UnitTestFrameworkPkg/Library/UnitTestLib/Log.c +++ b/UnitTestFrameworkPkg/Library/UnitTestLib/Log.c @@ -15,8 +15,7 @@ #include #include -#define UNIT_TEST_MAX_SINGLE_LOG_STRING_LENGTH (512) -#define UNIT_TEST_MAX_LOG_BUFFER SIZE_16KB +#define UNIT_TEST_MAX_LOG_BUFFER SIZE_16KB struct _UNIT_TEST_LOG_PREFIX_STRING { UNIT_TEST_STATUS LogLevel; @@ -85,7 +84,7 @@ AddStringToUnitTestLog ( UnitTest->Log, UNIT_TEST_MAX_LOG_BUFFER / sizeof (CHAR8), String, - UNIT_TEST_MAX_SINGLE_LOG_STRING_LENGTH + UNIT_TEST_MAX_STRING_LENGTH ); if (EFI_ERROR (Status)) { DEBUG ((DEBUG_ERROR, "Failed to add unit test log string. Status = %r\n", Status)); @@ -160,8 +159,8 @@ UnitTestLog ( ) { UNIT_TEST_FRAMEWORK_HANDLE FrameworkHandle; - CHAR8 NewFormatString[UNIT_TEST_MAX_SINGLE_LOG_STRING_LENGTH]; - CHAR8 LogString[UNIT_TEST_MAX_SINGLE_LOG_STRING_LENGTH]; + CHAR8 NewFormatString[UNIT_TEST_MAX_STRING_LENGTH]; + CHAR8 LogString[UNIT_TEST_MAX_STRING_LENGTH]; CONST CHAR8 *LogTypePrefix; VA_LIST Marker; diff --git a/UnitTestFrameworkPkg/Library/UnitTestLib/UnitTestLib.c b/UnitTestFrameworkPkg/Library/UnitTestLib/UnitTestLib.c index 3e3a850af125..953f1959bc11 100644 --- a/UnitTestFrameworkPkg/Library/UnitTestLib/UnitTestLib.c +++ b/UnitTestFrameworkPkg/Library/UnitTestLib/UnitTestLib.c @@ -571,9 +571,9 @@ UpdateTestFromSave ( Test->FailureType = MatchingTest->FailureType; AsciiStrnCpyS ( &Test->FailureMessage[0], - UNIT_TEST_TESTFAILUREMSG_LENGTH, + UNIT_TEST_MAX_STRING_LENGTH, &MatchingTest->FailureMessage[0], - UNIT_TEST_TESTFAILUREMSG_LENGTH + UNIT_TEST_MAX_STRING_LENGTH ); // @@ -748,7 +748,7 @@ SerializeState ( // TestSaveData->Result = UnitTest->Result; TestSaveData->FailureType = UnitTest->FailureType; - AsciiStrnCpyS (&TestSaveData->FailureMessage[0], UNIT_TEST_TESTFAILUREMSG_LENGTH, &UnitTest->FailureMessage[0], UNIT_TEST_TESTFAILUREMSG_LENGTH); + AsciiStrnCpyS (&TestSaveData->FailureMessage[0], UNIT_TEST_MAX_STRING_LENGTH, &UnitTest->FailureMessage[0], UNIT_TEST_MAX_STRING_LENGTH); // // If there is a log, save the log. diff --git a/UnitTestFrameworkPkg/PrivateInclude/UnitTestFrameworkTypes.h b/UnitTestFrameworkPkg/PrivateInclude/UnitTestFrameworkTypes.h index adce413818a2..3d91b7810872 100644 --- a/UnitTestFrameworkPkg/PrivateInclude/UnitTestFrameworkTypes.h +++ b/UnitTestFrameworkPkg/PrivateInclude/UnitTestFrameworkTypes.h @@ -15,7 +15,7 @@ /// /// The maximum length of a string stored in the unit test framework /// -#define UNIT_TEST_MAX_STRING_LENGTH (120) +#define UNIT_TEST_MAX_STRING_LENGTH (512) /// /// The size of a firngerprint used to save/resume execution of a unit test @@ -24,12 +24,6 @@ /// #define UNIT_TEST_FINGERPRINT_SIZE (sizeof (UINT32)) -/// -/// The maximum length of a test failure message stored in the unit test -/// framework -/// -#define UNIT_TEST_TESTFAILUREMSG_LENGTH (120) - /// /// FAILURE_TYPE used to record the type of assert that was triggered by a unit /// test. @@ -54,7 +48,7 @@ typedef struct { CHAR8 *Name; // can't have spaces and should be short CHAR8 *Log; FAILURE_TYPE FailureType; - CHAR8 FailureMessage[UNIT_TEST_TESTFAILUREMSG_LENGTH]; + CHAR8 FailureMessage[UNIT_TEST_MAX_STRING_LENGTH]; UINT8 Fingerprint[UNIT_TEST_FINGERPRINT_SIZE]; UNIT_TEST_STATUS Result; UNIT_TEST_FUNCTION RunTest; @@ -117,7 +111,7 @@ typedef struct { typedef struct { UINT32 Size; // Size of the UNIT_TEST_SAVE_TEST including Log[] UINT8 Fingerprint[UNIT_TEST_FINGERPRINT_SIZE]; // Fingerprint of the test itself. - CHAR8 FailureMessage[UNIT_TEST_TESTFAILUREMSG_LENGTH]; + CHAR8 FailureMessage[UNIT_TEST_MAX_STRING_LENGTH]; FAILURE_TYPE FailureType; UNIT_TEST_STATUS Result; CHAR8 Log[]; diff --git a/UnitTestFrameworkPkg/ReadMe.md b/UnitTestFrameworkPkg/ReadMe.md index d28cb5cb0a5d..6a67ca23a149 100644 --- a/UnitTestFrameworkPkg/ReadMe.md +++ b/UnitTestFrameworkPkg/ReadMe.md @@ -485,8 +485,8 @@ function to be compiled into the test application and then hooked to during a test. This library is mainly a wrapper around the -[subhook](https://github.com/Zeex/subhook) header and source files. It is -important to note that the use of the mock function macros and the creation +[subhook](https://github.com/tianocore/edk2-subhook) header and source files. It +is important to note that the use of the mock function macros and the creation of mock functions requires no knowledge about the SubhookLib. The SubhookLib library is entirely hidden and encapsulated within FunctionMockLib, and it is only mentioned here to provide a complete explanation on all the libraries diff --git a/UnitTestFrameworkPkg/UnitTestFrameworkPkgHost.dsc.inc b/UnitTestFrameworkPkg/UnitTestFrameworkPkgHost.dsc.inc index c56db1819c40..2012c3ae9a32 100644 --- a/UnitTestFrameworkPkg/UnitTestFrameworkPkgHost.dsc.inc +++ b/UnitTestFrameworkPkg/UnitTestFrameworkPkgHost.dsc.inc @@ -49,11 +49,13 @@ MSFT:*_VS2015x86_IA32_DLINK_FLAGS = /LIBPATH:"%VS2015_PREFIX%Lib" /LIBPATH:"%VS2015_PREFIX%VC\Lib" /LIBPATH:"%UniversalCRTSdkDir%lib\%UCRTVersion%\ucrt\x86" /LIBPATH:"%WindowsSdkDir%lib\%WindowsSDKLibVersion%\um\x86" MSFT:*_VS2017_IA32_DLINK_FLAGS = /LIBPATH:"%VCToolsInstallDir%lib\x86" /LIBPATH:"%UniversalCRTSdkDir%lib\%UCRTVersion%\ucrt\x86" /LIBPATH:"%WindowsSdkDir%lib\%WindowsSDKLibVersion%\um\x86" MSFT:*_VS2019_IA32_DLINK_FLAGS = /LIBPATH:"%VCToolsInstallDir%lib\x86" /LIBPATH:"%UniversalCRTSdkDir%lib\%UCRTVersion%\ucrt\x86" /LIBPATH:"%WindowsSdkDir%lib\%WindowsSDKLibVersion%\um\x86" + MSFT:*_VS2022_IA32_DLINK_FLAGS = /LIBPATH:"%VCToolsInstallDir%lib\x86" /LIBPATH:"%UniversalCRTSdkDir%lib\%UCRTVersion%\ucrt\x86" /LIBPATH:"%WindowsSdkDir%lib\%WindowsSDKLibVersion%\um\x86" MSFT:*_VS2015_X64_DLINK_FLAGS = /LIBPATH:"%VS2015_PREFIX%VC\Lib\AMD64" /LIBPATH:"%UniversalCRTSdkDir%lib\%UCRTVersion%\ucrt\x64" /LIBPATH:"%WindowsSdkDir%lib\%WindowsSDKLibVersion%\um\x64" MSFT:*_VS2015x86_X64_DLINK_FLAGS = /LIBPATH:"%VS2015_PREFIX%VC\Lib\AMD64" /LIBPATH:"%UniversalCRTSdkDir%lib\%UCRTVersion%\ucrt\x64" /LIBPATH:"%WindowsSdkDir%lib\%WindowsSDKLibVersion%\um\x64" MSFT:*_VS2017_X64_DLINK_FLAGS = /LIBPATH:"%VCToolsInstallDir%lib\x64" /LIBPATH:"%UniversalCRTSdkDir%lib\%UCRTVersion%\ucrt\x64" /LIBPATH:"%WindowsSdkDir%lib\%WindowsSDKLibVersion%\um\x64" MSFT:*_VS2019_X64_DLINK_FLAGS = /LIBPATH:"%VCToolsInstallDir%lib\x64" /LIBPATH:"%UniversalCRTSdkDir%lib\%UCRTVersion%\ucrt\x64" /LIBPATH:"%WindowsSdkDir%lib\%WindowsSDKLibVersion%\um\x64" + MSFT:*_VS2022_X64_DLINK_FLAGS = /LIBPATH:"%VCToolsInstallDir%lib\x64" /LIBPATH:"%UniversalCRTSdkDir%lib\%UCRTVersion%\ucrt\x64" /LIBPATH:"%WindowsSdkDir%lib\%WindowsSDKLibVersion%\um\x64" # # GCC diff --git a/edksetup.sh b/edksetup.sh index cab3a8c113e0..0ae32ea8cc91 100755 --- a/edksetup.sh +++ b/edksetup.sh @@ -103,14 +103,22 @@ SetupEnv() fi } -SetupPython3() +SetupPythonCommand() { + # + # If PYTHON_COMMAND is already set, then we can return right now + # + if [ -n "$PYTHON_COMMAND" ] + then + return 0 + fi + export PYTHON_COMMAND=python3 } SourceEnv() { - SetupPython3 + SetupPythonCommand SetWorkspace SetupEnv }