From 3a996f479eb395dfb0981dce30cf46d35f19d689 Mon Sep 17 00:00:00 2001 From: Michael Kubacki Date: Thu, 12 Jan 2023 20:02:48 -0500 Subject: [PATCH] Convert relevant files to CRLF Mu aligns with TianoCore's requirement for CRLF line endings. Signed-off-by: Michael Kubacki --- .../BuildPlugin/DebugMacroCheck_plug_in.yaml | 22 +- .../Plugin/DebugMacroCheck/DebugMacroCheck.py | 1764 +++--- .../tests/test_DebugMacroCheck.py | 402 +- .../Plugin/ImageValidation/ImageValidation.py | 550 +- .../ImageValidation_plug_in.yaml | 20 +- BaseTools/Bin/basetoolsbin_ext_dep.yaml | 36 +- .../NugetPublishing/Mu-Basetools.config.json | 16 +- BaseTools/NugetPublishing/Mu-Nasm.config.json | 16 +- BaseTools/Plugin/BmpCheck/BmpCheckPlugin.py | 340 +- .../ClangPdbToolChain/ClangPdbToolChain.py | 186 +- .../ClangPdbToolChain_plug_in.yaml | 22 +- .../Plugin/Edk2ToolHelper/Edk2ToolHelper.py | 332 +- .../FdSizeReport/FdSizeReportGenerator.py | 1050 ++-- BaseTools/Plugin/FlattenPdbs/FlattenPdbs.py | 126 +- .../OverrideValidation/OverrideValidation.py | 1418 ++--- BaseTools/Plugin/Sample/HelloWorld.py | 86 +- .../WindowsCapsuleSupportHelper.py | 124 +- BaseTools/Scripts/GenFmpImageAuth.py | 462 +- BaseTools/Scripts/WindowsCapsuleFileGen.py | 258 +- CryptoPkg/Driver/CryptoDxe.inf | 352 +- CryptoPkg/Driver/CryptoPei.inf | 356 +- CryptoPkg/Driver/CryptoSmm.inf | 352 +- CryptoPkg/Driver/Packaging/License.txt | 24 +- .../edk2-BaseCryptoDriver.config.json | 16 +- CryptoPkg/Driver/readme.md | 308 +- .../Library/BaseCryptLib/BaseCryptLib.inf | 2 +- .../Library/BaseCryptLib/PeiCryptLib.inf | 2 +- .../Library/BaseCryptLib/RuntimeCryptLib.inf | 4 +- .../Library/BaseCryptLib/SmmCryptLib.inf | 2 +- .../BaseCryptLibOnProtocolPpi/DxeCryptLib.inf | 356 +- .../BaseCryptLibOnProtocolPpi/PeiCryptLib.inf | 354 +- .../BaseCryptLibOnProtocolPpi/SmmCryptLib.inf | 352 +- .../BaseCryptLibOnProtocolPpi/readme.md | 14 +- CryptoPkg/Library/HmacSha1Lib/HmacSha1Lib.inf | 144 +- CryptoPkg/Library/HmacSha1Lib/HmacSha1Lib.uni | 38 +- .../Library/HmacSha1Lib/HmacSha1LibNull.inf | 124 +- .../Library/IntrinsicLib/IntrinsicLib.inf | 8 +- CryptoPkg/Test/CryptoPkgHostTest.dsc | 70 +- .../BaseCryptLib/BaseCryptLibUnitTestApp.inf | 110 +- .../Application/HelloWorld/HelloWorld.ver | 8 +- .../SmiHandlerProfileAuditTestApp.inf | 118 +- .../BaseExceptionPersistenceLibNull.inf | 52 +- .../CapsulePersistLibNull.inf | 72 +- .../Library/DeviceStateLib/DeviceStateLib.inf | 66 +- MdeModulePkg/Library/DeviceStateLib/Readme.md | 64 +- .../MemoryBinOverrideLibNull.inf | 62 +- .../DxeMemoryProtectionHobLib.inf | 66 +- .../SmmMemoryProtectionHobLib.inf | 68 +- .../StandaloneMmMemoryProtectionHobLib.inf | 70 +- .../DxeMemoryProtectionHobLibNull.inf | 50 +- .../MmMemoryProtectionHobLibNull.inf | 52 +- .../MemoryTypeInfoSecVarCheckLib.inf | 90 +- .../MemoryTypeInformationChangeLibNull.inf | 58 +- .../ParallelLzmaCustomDecompressLib.inf | 80 +- .../SecurityLockAuditDebugMessageLib.inf | 56 +- .../SecurityLockAuditLibNull.inf | 50 +- .../VarCheckPolicyLibVariableDxe.inf | 62 +- .../VariablePolicyUnitTest.inf | 90 +- MdeModulePkg/Test/MdeModulePkgHostTest.dsc | 20 +- .../VariablePolicyFuncTestApp/Readme.md | 134 +- .../VariablePolicyFuncTestApp.inf | 96 +- .../VariableRuntimeDxeUnitTest.inf | 314 +- .../BaseBinSecurityLibNull.inf | 48 +- .../BaseBinSecurityLibRng.inf | 76 +- .../X64/GSHandlerCheck.asm | 34 +- .../X64/report_rangecheckfailure.asm | 36 +- .../X64/security_check_cookie.asm | 48 +- .../Library/BaseLib/AArch64/CpuBreakAssert.S | 56 +- .../Library/BaseMmuLibNull/BaseMmuLibNull.inf | 58 +- .../ArmCompilerIntrinsicsLib.inf | 156 +- MdePkg/Library/FltUsedLib/FltUsedLib.inf | 82 +- MdePkg/Library/FltUsedLib/Readme.md | 30 +- MdePkg/Library/VsIntrinsicLib/IA32/llmul.asm | 196 +- .../Library/VsIntrinsicLib/VsIntrinsicLib.inf | 74 +- .../Library/VsIntrinsicLib/VsIntrinsicLib.uni | 34 +- .../RngLibHostTestLfsr/RngLibHostTestLfsr.inf | 50 +- .../Test/Library/StubUefiLib/StubUefiLib.inf | 74 +- .../MemoryAttributeProtocolFuncTestApp.inf | 80 +- .../Readme.md | 38 +- .../Library/BaseLib/BaseLibUnitTestApp.inf | 66 +- .../TestBaseSafeIntLibTestApp.inf | 84 +- .../SharedNetworking/Dhcp6Dxe.DEBUG.inf | 130 +- .../SharedNetworking/Dhcp6Dxe.RELEASE.inf | 130 +- NetworkPkg/SharedNetworking/DnsDxe.DEBUG.inf | 130 +- .../SharedNetworking/DnsDxe.RELEASE.inf | 126 +- NetworkPkg/SharedNetworking/DriverBuilder.py | 318 +- .../SharedNetworking/HttpBootDxe.DEBUG.inf | 162 +- .../SharedNetworking/HttpBootDxe.RELEASE.inf | 168 +- .../HttpUtilitiesDxe.DEBUG.inf | 104 +- .../HttpUtilitiesDxe.RELEASE.inf | 104 +- NetworkPkg/SharedNetworking/Ip6Dxe.DEBUG.inf | 148 +- .../SharedNetworking/Ip6Dxe.RELEASE.inf | 146 +- NetworkPkg/SharedNetworking/README.md | 64 +- .../SharedNetworking/SharedNetworkPkg.dsc | 352 +- .../SharedNetworking/SharedNetworkPkg.fdf | 94 +- .../SharedNetworking/SharedNetworkSettings.py | 1134 ++-- .../SharedNetworking.config.json | 16 +- .../SharedNetworking/SharedNetworking.md | 190 +- .../SharedNetworking_ext_dep.json | 14 +- NetworkPkg/SharedNetworking/TcpDxe.DEBUG.inf | 128 +- .../SharedNetworking/TcpDxe.RELEASE.inf | 128 +- NetworkPkg/SharedNetworking/TlsDxe.DEBUG.inf | 116 +- .../SharedNetworking/TlsDxe.RELEASE.inf | 116 +- NetworkPkg/SharedNetworking/TlsDxe.uni | 48 +- NetworkPkg/SharedNetworking/TlsDxeExtra.uni | 36 +- NetworkPkg/SharedNetworking/Udp6Dxe.DEBUG.inf | 112 +- .../SharedNetworking/Udp6Dxe.RELEASE.inf | 112 +- ...ipelines-sharednetworking-release-gate.yml | 184 +- NetworkPkg/SharedNetworking/release_notes.md | 8 +- .../Application/FbptDump/FbptDump.inf | 74 +- .../CommonPolicy/Template_PolicyHeader.yaml | 54 +- .../UpdatePolicyHdr/UpdatePolicyHdr.py | 524 +- .../PolicyDefinitions/GFX_policy_def.yaml | 86 +- PolicyServicePkg/Tools/GenCfgData.py | 5128 ++++++++--------- RepoDetails.md | 220 +- .../StandaloneMmCoreEntryPointNull.inf | 64 +- edk2_core_path_env.json | 8 +- 117 files changed, 12006 insertions(+), 12006 deletions(-) diff --git a/.pytool/Plugin/DebugMacroCheck/BuildPlugin/DebugMacroCheck_plug_in.yaml b/.pytool/Plugin/DebugMacroCheck/BuildPlugin/DebugMacroCheck_plug_in.yaml index 97320f0251..50f97cbd39 100644 --- a/.pytool/Plugin/DebugMacroCheck/BuildPlugin/DebugMacroCheck_plug_in.yaml +++ b/.pytool/Plugin/DebugMacroCheck/BuildPlugin/DebugMacroCheck_plug_in.yaml @@ -1,11 +1,11 @@ -## @file -# Build plugin used to check that debug macros are formatted properly. -# -# Copyright (c) Microsoft Corporation. All rights reserved. -# SPDX-License-Identifier: BSD-2-Clause-Patent -## -{ - "scope": "global", - "name": "Debug Macro Check Plugin", - "module": "DebugMacroCheckBuildPlugin" -} +## @file +# Build plugin used to check that debug macros are formatted properly. +# +# Copyright (c) Microsoft Corporation. All rights reserved. +# SPDX-License-Identifier: BSD-2-Clause-Patent +## +{ + "scope": "global", + "name": "Debug Macro Check Plugin", + "module": "DebugMacroCheckBuildPlugin" +} diff --git a/.pytool/Plugin/DebugMacroCheck/DebugMacroCheck.py b/.pytool/Plugin/DebugMacroCheck/DebugMacroCheck.py index 3df3c0aff8..c51655bdf3 100644 --- a/.pytool/Plugin/DebugMacroCheck/DebugMacroCheck.py +++ b/.pytool/Plugin/DebugMacroCheck/DebugMacroCheck.py @@ -1,882 +1,882 @@ -# @file DebugMacroCheck.py -# -# A script that checks if DEBUG macros are formatted properly. -# -# In particular, that print format specifiers are defined -# with the expected number of arguments in the variable -# argument list. -# -# Copyright (c) Microsoft Corporation. All rights reserved. -# SPDX-License-Identifier: BSD-2-Clause-Patent -## - -from argparse import RawTextHelpFormatter -import logging -import os -import re -import regex -import sys -import shutil -import timeit -import yaml - -from edk2toollib.utility_functions import RunCmd -from io import StringIO -from pathlib import Path, PurePath -from typing import Dict, Iterable, List, Optional, Tuple - - -PROGRAM_NAME = "Debug Macro Checker" - - -def log_old_python_version_warning(): - """Warn users on old Python versions for future usage of 3.10 features.""" - - # Help move the world toward being more ideal... - if sys.version_info.major < 3 or \ - (sys.version_info.major == 3 and sys.version_info.minor < 10): - from datetime import date - import platform - - py_3_10_release_date = date(2021, 10, 4) - days_since_release = (date.today() - py_3_10_release_date).days - - logging.warning(f"You are using Python {platform.python_version()}." - f" Python 3.10 has been available for " - f"{days_since_release} days.\nUpgrade so Python " - f"scripts can use 3.10 language features!\n\n" - f"https://www.python.org/downloads/\n") - - -class GitHelpers: - """ - Collection of Git helpers. - - Will be moved to a more generic module and imported in the future. - """ - - @staticmethod - def get_git_ignored_paths(directory_path: PurePath) -> List[Path]: - """Returns ignored files in this git repository. - - Args: - directory_path (PurePath): Path to the git directory. - - Returns: - List[Path]: List of file absolute paths to all files ignored - in this git repository. If git is not found, an empty - list will be returned. - """ - if not shutil.which("git"): - logging.warn( - "Git is not found on this system. Git submodule paths will " - "not be considered.") - return [] - - out_stream_buffer = StringIO() - exit_code = RunCmd("git", "ls-files --other", - workingdir=str(directory_path), - outstream=out_stream_buffer, - logging_level=logging.NOTSET) - if exit_code != 0: - return [] - - rel_paths = out_stream_buffer.getvalue().strip().splitlines() - abs_paths = [] - for path in rel_paths: - abs_paths.append(Path(directory_path, path)) - return abs_paths - - @staticmethod - def get_git_submodule_paths(directory_path: PurePath) -> List[Path]: - """Returns submodules in the given workspace directory. - - Args: - directory_path (PurePath): Path to the git directory. - - Returns: - List[Path]: List of directory absolute paths to the root of - each submodule found from this folder. If submodules are not - found, an empty list will be returned. - """ - if not shutil.which("git"): - return [] - - if os.path.isfile(directory_path.joinpath(".gitmodules")): - out_stream_buffer = StringIO() - exit_code = RunCmd( - "git", "config --file .gitmodules --get-regexp path", - workingdir=str(directory_path), - outstream=out_stream_buffer, - logging_level=logging.NOTSET) - if exit_code != 0: - return [] - - submodule_paths = [] - for line in out_stream_buffer.getvalue().strip().splitlines(): - submodule_paths.append( - Path(directory_path, line.split()[1])) - - return submodule_paths - else: - return [] - - -class QuietFilter(logging.Filter): - """A logging filter that temporarily suppresses message output.""" - - def __init__(self, quiet: bool = False): - """Class constructor method. - - Args: - quiet (bool, optional): Indicates if messages are currently being - printed (False) or not (True). Defaults to False. - """ - - self._quiet = quiet - - def filter(self, record: logging.LogRecord) -> bool: - """Quiet filter method. - - Args: - record (logging.LogRecord): A log record object that the filter is - applied to. - - Returns: - bool: True if messages are being suppressed. Otherwise, False. - """ - return not self._quiet - - -class ProgressFilter(logging.Filter): - """A logging filter that suppresses 'Progress' messages.""" - - def filter(self, record: logging.LogRecord) -> bool: - """Progress filter method. - - Args: - record (logging.LogRecord): A log record object that the filter is - applied to. - - Returns: - bool: True if the message is not a 'Progress' message. Otherwise, - False. - """ - return not record.getMessage().startswith("\rProgress") - - -class CacheDuringProgressFilter(logging.Filter): - """A logging filter that suppresses messages during progress operations.""" - - _message_cache = [] - - @property - def message_cache(self) -> List[logging.LogRecord]: - """Contains a cache of messages accumulated during time of operation. - - Returns: - List[logging.LogRecord]: List of log records stored while the - filter was active. - """ - return self._message_cache - - def filter(self, record: logging.LogRecord): - """Cache progress filter that suppresses messages during progress - display output. - - Args: - record (logging.LogRecord): A log record to cache. - """ - self._message_cache.append(record) - - -def check_debug_macros(macros: Iterable[Dict[str, str]], - file_dbg_path: str, - **macro_subs: str - ) -> Tuple[int, int, int]: - """Checks if debug macros contain formatting errors. - - Args: - macros (Iterable[Dict[str, str]]): : A groupdict of macro matches. - This is an iterable of dictionaries with group names from the regex - match as the key and the matched string as the value for the key. - - file_dbg_path (str): The file path (or other custom string) to display - in debug messages. - - macro_subs (Dict[str,str]): Variable-length keyword and replacement - value string pairs to substitute during debug macro checks. - - Returns: - Tuple[int, int, int]: A tuple of the number of formatting errors, - number of print specifiers, and number of arguments for the macros - given. - """ - - macro_subs = {k.lower(): v for k, v in macro_subs.items()} - - arg_cnt, failure_cnt, print_spec_cnt = 0, 0, 0 - for macro in macros: - # Special Specifier Handling - processed_dbg_str = macro['dbg_str'].strip().lower() - - logging.debug(f"Inspecting macro: {macro}") - - # Make any macro substitutions so further processing is applied - # to the substituted value. - for k in macro_subs.keys(): - processed_dbg_str = processed_dbg_str.replace(k, macro_subs[k]) - - logging.debug("Debug macro string after replacements: " - f"{processed_dbg_str}") - - # These are very rarely used in debug strings. They are somewhat - # more common in HII code to control text displayed on the - # console. Due to the rarity and likelihood usage is a mistake, - # a warning is shown if found. - specifier_display_replacements = ['%n', '%h', '%e', '%b', '%v'] - for s in specifier_display_replacements: - if s in processed_dbg_str: - logging.warning(f"File: {file_dbg_path}") - logging.warning(f" {s} found in string and ignored:") - logging.warning(f" \"{processed_dbg_str}\"") - processed_dbg_str = processed_dbg_str.replace(s, '') - - # These are miscellaneous print specifiers that do not require - # special parsing and simply need to be replaced since they do - # have a corresponding argument associated with them. - specifier_other_replacements = ['%%', '\r', '\n'] - for s in specifier_other_replacements: - if s in processed_dbg_str: - processed_dbg_str = processed_dbg_str.replace(s, '') - - processed_dbg_str = re.sub( - r'%[.\-+ ,Ll0-9]*\*[.\-+ ,Ll0-9]*[a-zA-Z]', '%_%_', - processed_dbg_str) - logging.debug(f"Final macro before print specifier scan: " - f"{processed_dbg_str}") - - print_spec_cnt = processed_dbg_str.count('%') - - # Need to take into account parentheses between args in function - # calls that might be in the args list. Use regex module for - # this one since the recursive pattern match helps simplify - # only matching commas outside nested call groups. - if macro['dbg_args'] is None: - processed_arg_str = "" - else: - processed_arg_str = macro['dbg_args'].strip() - - argument_other_replacements = ['\r', '\n'] - for r in argument_other_replacements: - if s in processed_arg_str: - processed_arg_str = processed_arg_str.replace(s, '') - processed_arg_str = re.sub(r' +', ' ', processed_arg_str) - - # Handle special case of commas in arg strings - remove them for - # final count to pick up correct number of argument separating - # commas. - processed_arg_str = re.sub( - r'([\"\'])(?:|\\.|[^\\])*?(\1)', - '', - processed_arg_str) - - arg_matches = regex.findall( - r'(?:\((?:[^)(]+|(?R))*+\))|(,)', - processed_arg_str, - regex.MULTILINE) - - arg_cnt = 0 - if processed_arg_str != '': - arg_cnt = arg_matches.count(',') - - if print_spec_cnt != arg_cnt: - logging.error(f"File: {file_dbg_path}") - logging.error(f" Message = {macro['dbg_str']}") - logging.error(f" Arguments = \"{processed_arg_str}\"") - logging.error(f" Specifier Count = {print_spec_cnt}") - logging.error(f" Argument Count = {arg_cnt}") - - failure_cnt += 1 - - return failure_cnt, print_spec_cnt, arg_cnt - - -def get_debug_macros(file_contents: str) -> List[Dict[str, str]]: - """Extract debug macros from the given file contents. - - Args: - file_contents (str): A string of source file contents that may - contain debug macros. - - Returns: - List[Dict[str, str]]: A groupdict of debug macro regex matches - within the file contents provided. - """ - - # This is the main regular expression that is responsible for identifying - # DEBUG macros within source files and grouping the macro message string - # and macro arguments strings so they can be further processed. - r = regex.compile( - r'(?>(?PDEBUG\s*\(\s*\((?:.*?,))(?:\s*))(?P.*?(?:\"' - r'(?:[^\"\\]|\\.)*\".*?)*)(?:(?(?=,)(?.*?(?=(?:\s*\)){2}\s*;' - r'))))(?:\s*\)){2,};?', - regex.MULTILINE | regex.DOTALL) - return [m.groupdict() for m in r.finditer(file_contents)] - - -def check_macros_in_string(src_str: str, - file_dbg_path: str, - **macro_subs: str) -> Tuple[int, int, int]: - """Checks for debug macro formatting errors in a string. - - Args: - src_str (str): Contents of the string with debug macros. - - file_dbg_path (str): The file path (or other custom string) to display - in debug messages. - - macro_subs (Dict[str,str]): Variable-length keyword and replacement - value string pairs to substitute during debug macro checks. - - Returns: - Tuple[int, int, int]: A tuple of the number of formatting errors, - number of print specifiers, and number of arguments for the macros - in the string given. - """ - return check_debug_macros( - get_debug_macros(src_str), file_dbg_path, **macro_subs) - - -def check_macros_in_file(file: PurePath, - file_dbg_path: str, - show_utf8_decode_warning: bool = False, - **macro_subs: str) -> Tuple[int, int, int]: - """Checks for debug macro formatting errors in a file. - - Args: - file (PurePath): The file path to check. - - file_dbg_path (str): The file path (or other custom string) to display - in debug messages. - - show_utf8_decode_warning (bool, optional): Indicates whether to show - warnings if UTF-8 files fail to decode. Defaults to False. - - macro_subs (Dict[str,str]): Variable-length keyword and replacement - value string pairs to substitute during debug macro checks. - - Returns: - Tuple[int, int, int]: A tuple of the number of formatting errors, - number of print specifiers, and number of arguments for the macros - in the file given. - """ - try: - return check_macros_in_string( - file.read_text(encoding='utf-8'), file_dbg_path, - **macro_subs) - except UnicodeDecodeError as e: - if show_utf8_decode_warning: - logging.warning( - f"{file_dbg_path} UTF-8 decode error.\n" - " Debug macro code check skipped!\n" - f" -> {str(e)}") - return 0, 0, 0 - - -def check_macros_in_directory(directory: PurePath, - file_extensions: Iterable[str] = ('.c',), - ignore_git_ignore_files: Optional[bool] = True, - ignore_git_submodules: Optional[bool] = True, - show_progress_bar: Optional[bool] = True, - show_utf8_decode_warning: bool = False, - **macro_subs: str - ) -> int: - """Checks files with the given extension in the given directory for debug - macro formatting errors. - - Args: - directory (PurePath): The path to the directory to check. - file_extensions (Iterable[str], optional): An iterable of strings - representing file extensions to check. Defaults to ('.c',). - - ignore_git_ignore_files (Optional[bool], optional): Indicates whether - files ignored by git should be ignored for the debug macro check. - Defaults to True. - - ignore_git_submodules (Optional[bool], optional): Indicates whether - files located in git submodules should not be checked. Defaults to - True. - - show_progress_bar (Optional[bool], optional): Indicates whether to - show a progress bar to show progress status while checking macros. - This is more useful on a very large directories. Defaults to True. - - show_utf8_decode_warning (bool, optional): Indicates whether to show - warnings if UTF-8 files fail to decode. Defaults to False. - - macro_subs (Dict[str,str]): Variable-length keyword and replacement - value string pairs to substitute during debug macro checks. - - Returns: - int: Count of debug macro errors in the directory. - """ - def _get_file_list(root_directory: PurePath, - extensions: Iterable[str]) -> List[Path]: - """Returns a list of files recursively located within the path. - - Args: - root_directory (PurePath): A directory Path object to the root - folder. - - extensions (Iterable[str]): An iterable of strings that - represent file extensions to recursively search for within - root_directory. - - Returns: - List[Path]: List of file Path objects to files found in the - given directory with the given extensions. - """ - def _show_file_discovered_message(file_count: int, - elapsed_time: float) -> None: - print(f"\rDiscovered {file_count:,} files in", - f"{current_start_delta:-.0f}s" - f"{'.' * min(int(current_start_delta), 40)}", end="\r") - - start_time = timeit.default_timer() - previous_indicator_time = start_time - - files = [] - for file in root_directory.rglob('*'): - if file.suffix in extensions: - files.append(Path(file)) - - # Give an indicator progress is being made - # This has a negligible impact on overall performance - # with print emission limited to half second intervals. - current_time = timeit.default_timer() - current_start_delta = current_time - start_time - - if current_time - previous_indicator_time >= 0.5: - # Since this rewrites the line, it can be considered a form - # of progress bar - if show_progress_bar: - _show_file_discovered_message(len(files), - current_start_delta) - previous_indicator_time = current_time - - if show_progress_bar: - _show_file_discovered_message(len(files), current_start_delta) - print() - - return files - - logging.info(f"Checking Debug Macros in directory: " - f"{directory.resolve()}\n") - - logging.info("Gathering the overall file list. This might take a" - "while.\n") - - start_time = timeit.default_timer() - file_list = set(_get_file_list(directory, file_extensions)) - end_time = timeit.default_timer() - start_time - - logging.debug(f"[PERF] File search found {len(file_list):,} files in " - f"{end_time:.2f} seconds.") - - if ignore_git_ignore_files: - logging.info("Getting git ignore files...") - start_time = timeit.default_timer() - ignored_file_paths = GitHelpers.get_git_ignored_paths(directory) - end_time = timeit.default_timer() - start_time - - logging.debug(f"[PERF] File ignore gathering took {end_time:.2f} " - f"seconds.") - - logging.info("Ignoring git ignore files...") - logging.debug(f"File list count before git ignore {len(file_list):,}") - start_time = timeit.default_timer() - file_list = file_list.difference(ignored_file_paths) - end_time = timeit.default_timer() - start_time - logging.info(f" {len(ignored_file_paths):,} files are ignored by git") - logging.info(f" {len(file_list):,} files after removing " - f"ignored files") - - logging.debug(f"[PERF] File ignore calculation took {end_time:.2f} " - f"seconds.") - - if ignore_git_submodules: - logging.info("Ignoring git submodules...") - submodule_paths = GitHelpers.get_git_submodule_paths(directory) - if submodule_paths: - logging.debug(f"File list count before git submodule exclusion " - f"{len(file_list):,}") - start_time = timeit.default_timer() - file_list = [f for f in file_list - if not f.is_relative_to(*submodule_paths)] - end_time = timeit.default_timer() - start_time - - for path in enumerate(submodule_paths): - logging.debug(" {0}. {1}".format(*path)) - - logging.info(f" {len(submodule_paths):,} submodules found") - logging.info(f" {len(file_list):,} files will be examined after " - f"excluding files in submodules") - - logging.debug(f"[PERF] Submodule exclusion calculation took " - f"{end_time:.2f} seconds.") - else: - logging.warning("No submodules found") - - logging.info(f"\nStarting macro check on {len(file_list):,} files.") - - cache_progress_filter = CacheDuringProgressFilter() - handler = next((h for h in logging.getLogger().handlers if h.get_name() == - 'stdout_logger_handler'), None) - - if handler is not None: - handler.addFilter(cache_progress_filter) - - start_time = timeit.default_timer() - - failure_cnt, file_cnt = 0, 0 - for file_cnt, file in enumerate(file_list): - file_rel_path = str(file.relative_to(directory)) - failure_cnt += check_macros_in_file( - file, file_rel_path, show_utf8_decode_warning, - **macro_subs)[0] - if show_progress_bar: - _show_progress(file_cnt, len(file_list), - f" {failure_cnt} errors" if failure_cnt > 0 else "") - - if show_progress_bar: - _show_progress(len(file_list), len(file_list), - f" {failure_cnt} errors" if failure_cnt > 0 else "") - print("\n", flush=True) - - end_time = timeit.default_timer() - start_time - - if handler is not None: - handler.removeFilter(cache_progress_filter) - - for record in cache_progress_filter.message_cache: - handler.emit(record) - - logging.debug(f"[PERF] The macro check operation took {end_time:.2f} " - f"seconds.") - - _log_failure_count(failure_cnt, file_cnt) - - return failure_cnt - - -def _log_failure_count(failure_count: int, file_count: int) -> None: - """Logs the failure count. - - Args: - failure_count (int): Count of failures to log. - - file_count (int): Count of files with failures. - """ - if failure_count > 0: - logging.error("\n") - logging.error(f"{failure_count:,} debug macro errors in " - f"{file_count:,} files") - - -def _show_progress(step: int, total: int, suffix: str = '') -> None: - """Print progress of tick to total. - - Args: - step (int): The current step count. - - total (int): The total step count. - - suffix (str): String to print at the end of the progress bar. - """ - global _progress_start_time - - if step == 0: - _progress_start_time = timeit.default_timer() - - terminal_col = shutil.get_terminal_size().columns - var_consume_len = (len("Progress|\u2588| 000.0% Complete 000s") + - len(suffix)) - avail_len = terminal_col - var_consume_len - - percent = f"{100 * (step / float(total)):3.1f}" - filled = int(avail_len * step // total) - bar = '\u2588' * filled + '-' * (avail_len - filled) - step_time = timeit.default_timer() - _progress_start_time - - print(f'\rProgress|{bar}| {percent}% Complete {step_time:-3.0f}s' - f'{suffix}', end='\r') - - -def _module_invocation_check_macros_in_directory_wrapper() -> int: - """Provides an command-line argument wrapper for checking debug macros. - - Returns: - int: The system exit code value. - """ - import argparse - import builtins - - def _check_dir_path(dir_path: str) -> bool: - """Returns the absolute path if the path is a directory." - - Args: - dir_path (str): A directory file system path. - - Raises: - NotADirectoryError: The directory path given is not a directory. - - Returns: - bool: True if the path is a directory else False. - """ - abs_dir_path = os.path.abspath(dir_path) - if os.path.isdir(dir_path): - return abs_dir_path - else: - raise NotADirectoryError(abs_dir_path) - - def _check_file_path(file_path: str) -> bool: - """Returns the absolute path if the path is a file." - - Args: - file_path (str): A file path. - - Raises: - FileExistsError: The path is not a valid file. - - Returns: - bool: True if the path is a valid file else False. - """ - abs_file_path = os.path.abspath(file_path) - if os.path.isfile(file_path): - return abs_file_path - else: - raise FileExistsError(file_path) - - def _quiet_print(*args, **kwargs): - """Replaces print when quiet is requested to prevent printing messages. - """ - pass - - root_logger = logging.getLogger() - root_logger.setLevel(logging.DEBUG) - - stdout_logger_handler = logging.StreamHandler(sys.stdout) - stdout_logger_handler.set_name('stdout_logger_handler') - stdout_logger_handler.setLevel(logging.INFO) - stdout_logger_handler.setFormatter(logging.Formatter('%(message)s')) - root_logger.addHandler(stdout_logger_handler) - - parser = argparse.ArgumentParser( - prog=PROGRAM_NAME, - description=( - "Checks for debug macro formatting " - "errors within files recursively located within " - "a given directory."), - formatter_class=RawTextHelpFormatter) - - io_req_group = parser.add_mutually_exclusive_group(required=True) - io_opt_group = parser.add_argument_group( - "Optional input and output") - git_group = parser.add_argument_group("Optional git control") - - io_req_group.add_argument('-w', '--workspace-directory', - type=_check_dir_path, - help="Directory of source files to check.\n\n") - - io_req_group.add_argument('-i', '--input-file', nargs='?', - type=_check_file_path, - help="File path for an input file to check.\n\n" - "Note that some other options do not apply " - "if a single file is specified such as " - "the\ngit options and file extensions.\n\n") - - io_opt_group.add_argument('-l', '--log-file', - nargs='?', - default=None, - const='debug_macro_check.log', - help="File path for log output.\n" - "(default: if the flag is given with no " - "file path then a file called\n" - "debug_macro_check.log is created and used " - "in the current directory)\n\n") - - io_opt_group.add_argument('-s', '--substitution-file', - type=_check_file_path, - help="A substitution YAML file specifies string " - "substitutions to perform within the debug " - "macro.\n\nThis is intended to be a simple " - "mechanism to expand the rare cases of pre-" - "processor\nmacros without directly " - "involving the pre-processor. The file " - "consists of one or more\nstring value " - "pairs where the key is the identifier to " - "replace and the value is the value\nto " - "replace it with.\n\nThis can also be used " - "as a method to ignore results by " - "replacing the problematic string\nwith a " - "different string.\n\n") - - io_opt_group.add_argument('-v', '--verbose-log-file', - action='count', - default=0, - help="Set file logging verbosity level.\n" - " - None: Info & > level messages\n" - " - '-v': + Debug level messages\n" - " - '-vv': + File name and function\n" - " - '-vvv': + Line number\n" - " - '-vvvv': + Timestamp\n" - "(default: verbose logging is not enabled)" - "\n\n") - - io_opt_group.add_argument('-n', '--no-progress-bar', action='store_true', - help="Disables progress bars.\n" - "(default: progress bars are used in some" - "places to show progress)\n\n") - - io_opt_group.add_argument('-q', '--quiet', action='store_true', - help="Disables console output.\n" - "(default: console output is enabled)\n\n") - - io_opt_group.add_argument('-u', '--utf8w', action='store_true', - help="Shows warnings for file UTF-8 decode " - "errors.\n" - "(default: UTF-8 decode errors are not " - "shown)\n\n") - - git_group.add_argument('-df', '--do-not-ignore-git-ignore-files', - action='store_true', - help="Do not ignore git ignored files.\n" - "(default: files in git ignore files are " - "ignored)\n\n") - - git_group.add_argument('-ds', '--do-not-ignore-git_submodules', - action='store_true', - help="Do not ignore files in git submodules.\n" - "(default: files in git submodules are " - "ignored)\n\n") - - parser.add_argument('-e', '--extensions', nargs='*', default=['.c'], - help="List of file extensions to include.\n" - "(default: %(default)s)") - - args = parser.parse_args() - - if args.quiet: - # Don't print in the few places that directly print - builtins.print = _quiet_print - stdout_logger_handler.addFilter(QuietFilter(args.quiet)) - - if args.log_file: - file_logger_handler = logging.FileHandler(filename=args.log_file, - mode='w', encoding='utf-8') - - # In an ideal world, everyone would update to the latest Python - # minor version (3.10) after a few weeks/months. Since that's not the - # case, resist from using structural pattern matching in Python 3.10. - # https://peps.python.org/pep-0636/ - - if args.verbose_log_file == 0: - file_logger_handler.setLevel(logging.INFO) - file_logger_formatter = logging.Formatter( - '%(levelname)-8s %(message)s') - elif args.verbose_log_file == 1: - file_logger_handler.setLevel(logging.DEBUG) - file_logger_formatter = logging.Formatter( - '%(levelname)-8s %(message)s') - elif args.verbose_log_file == 2: - file_logger_handler.setLevel(logging.DEBUG) - file_logger_formatter = logging.Formatter( - '[%(filename)s - %(funcName)20s() ] %(levelname)-8s ' - '%(message)s') - elif args.verbose_log_file == 3: - file_logger_handler.setLevel(logging.DEBUG) - file_logger_formatter = logging.Formatter( - '[%(filename)s:%(lineno)s - %(funcName)20s() ] ' - '%(levelname)-8s %(message)s') - elif args.verbose_log_file == 4: - file_logger_handler.setLevel(logging.DEBUG) - file_logger_formatter = logging.Formatter( - '%(asctime)s [%(filename)s:%(lineno)s - %(funcName)20s() ]' - ' %(levelname)-8s %(message)s') - else: - file_logger_handler.setLevel(logging.DEBUG) - file_logger_formatter = logging.Formatter( - '%(asctime)s [%(filename)s:%(lineno)s - %(funcName)20s() ]' - ' %(levelname)-8s %(message)s') - - file_logger_handler.addFilter(ProgressFilter()) - file_logger_handler.setFormatter(file_logger_formatter) - root_logger.addHandler(file_logger_handler) - - logging.info(PROGRAM_NAME + "\n") - - log_old_python_version_warning() - - substitution_data = {} - if args.substitution_file: - logging.info(f"Loading substitution file {args.substitution_file}") - with open(args.substitution_file, 'r') as sf: - substitution_data = yaml.safe_load(sf) - - if args.workspace_directory: - return check_macros_in_directory( - Path(args.workspace_directory), - args.extensions, - not args.do_not_ignore_git_ignore_files, - not args.do_not_ignore_git_submodules, - not args.no_progress_bar, - args.utf8w, - **substitution_data) - else: - curr_dir = Path(__file__).parent - input_file = Path(args.input_file) - - rel_path = str(input_file) - if input_file.is_relative_to(curr_dir): - rel_path = str(input_file.relative_to(curr_dir)) - - logging.info(f"Checking Debug Macros in File: " - f"{input_file.resolve()}\n") - - start_time = timeit.default_timer() - failure_cnt = check_macros_in_file( - input_file, - rel_path, - args.utf8w, - **substitution_data)[0] - end_time = timeit.default_timer() - start_time - - logging.debug(f"[PERF] The file macro check operation took " - f"{end_time:.2f} seconds.") - - _log_failure_count(failure_cnt, 1) - - return failure_cnt - - -if __name__ == '__main__': - # The exit status value is the number of macro formatting errors found. - # Therefore, if no macro formatting errors are found, 0 is returned. - # Some systems require the return value to be in the range 0-127, so - # a lower maximum of 100 is enforced to allow a wide range of potential - # values with a reasonably large maximum. - try: - sys.exit(max(_module_invocation_check_macros_in_directory_wrapper(), - 100)) - except KeyboardInterrupt: - logging.warning("Exiting due to keyboard interrupt.") - # Actual formatting errors are only allowed to reach 100. - # 101 signals a keyboard interrupt. - sys.exit(101) - except FileExistsError as e: - # 102 signals a file not found error. - logging.critical(f"Input file {e.args[0]} does not exist.") - sys.exit(102) -else: - log_old_python_version_warning() +# @file DebugMacroCheck.py +# +# A script that checks if DEBUG macros are formatted properly. +# +# In particular, that print format specifiers are defined +# with the expected number of arguments in the variable +# argument list. +# +# Copyright (c) Microsoft Corporation. All rights reserved. +# SPDX-License-Identifier: BSD-2-Clause-Patent +## + +from argparse import RawTextHelpFormatter +import logging +import os +import re +import regex +import sys +import shutil +import timeit +import yaml + +from edk2toollib.utility_functions import RunCmd +from io import StringIO +from pathlib import Path, PurePath +from typing import Dict, Iterable, List, Optional, Tuple + + +PROGRAM_NAME = "Debug Macro Checker" + + +def log_old_python_version_warning(): + """Warn users on old Python versions for future usage of 3.10 features.""" + + # Help move the world toward being more ideal... + if sys.version_info.major < 3 or \ + (sys.version_info.major == 3 and sys.version_info.minor < 10): + from datetime import date + import platform + + py_3_10_release_date = date(2021, 10, 4) + days_since_release = (date.today() - py_3_10_release_date).days + + logging.warning(f"You are using Python {platform.python_version()}." + f" Python 3.10 has been available for " + f"{days_since_release} days.\nUpgrade so Python " + f"scripts can use 3.10 language features!\n\n" + f"https://www.python.org/downloads/\n") + + +class GitHelpers: + """ + Collection of Git helpers. + + Will be moved to a more generic module and imported in the future. + """ + + @staticmethod + def get_git_ignored_paths(directory_path: PurePath) -> List[Path]: + """Returns ignored files in this git repository. + + Args: + directory_path (PurePath): Path to the git directory. + + Returns: + List[Path]: List of file absolute paths to all files ignored + in this git repository. If git is not found, an empty + list will be returned. + """ + if not shutil.which("git"): + logging.warn( + "Git is not found on this system. Git submodule paths will " + "not be considered.") + return [] + + out_stream_buffer = StringIO() + exit_code = RunCmd("git", "ls-files --other", + workingdir=str(directory_path), + outstream=out_stream_buffer, + logging_level=logging.NOTSET) + if exit_code != 0: + return [] + + rel_paths = out_stream_buffer.getvalue().strip().splitlines() + abs_paths = [] + for path in rel_paths: + abs_paths.append(Path(directory_path, path)) + return abs_paths + + @staticmethod + def get_git_submodule_paths(directory_path: PurePath) -> List[Path]: + """Returns submodules in the given workspace directory. + + Args: + directory_path (PurePath): Path to the git directory. + + Returns: + List[Path]: List of directory absolute paths to the root of + each submodule found from this folder. If submodules are not + found, an empty list will be returned. + """ + if not shutil.which("git"): + return [] + + if os.path.isfile(directory_path.joinpath(".gitmodules")): + out_stream_buffer = StringIO() + exit_code = RunCmd( + "git", "config --file .gitmodules --get-regexp path", + workingdir=str(directory_path), + outstream=out_stream_buffer, + logging_level=logging.NOTSET) + if exit_code != 0: + return [] + + submodule_paths = [] + for line in out_stream_buffer.getvalue().strip().splitlines(): + submodule_paths.append( + Path(directory_path, line.split()[1])) + + return submodule_paths + else: + return [] + + +class QuietFilter(logging.Filter): + """A logging filter that temporarily suppresses message output.""" + + def __init__(self, quiet: bool = False): + """Class constructor method. + + Args: + quiet (bool, optional): Indicates if messages are currently being + printed (False) or not (True). Defaults to False. + """ + + self._quiet = quiet + + def filter(self, record: logging.LogRecord) -> bool: + """Quiet filter method. + + Args: + record (logging.LogRecord): A log record object that the filter is + applied to. + + Returns: + bool: True if messages are being suppressed. Otherwise, False. + """ + return not self._quiet + + +class ProgressFilter(logging.Filter): + """A logging filter that suppresses 'Progress' messages.""" + + def filter(self, record: logging.LogRecord) -> bool: + """Progress filter method. + + Args: + record (logging.LogRecord): A log record object that the filter is + applied to. + + Returns: + bool: True if the message is not a 'Progress' message. Otherwise, + False. + """ + return not record.getMessage().startswith("\rProgress") + + +class CacheDuringProgressFilter(logging.Filter): + """A logging filter that suppresses messages during progress operations.""" + + _message_cache = [] + + @property + def message_cache(self) -> List[logging.LogRecord]: + """Contains a cache of messages accumulated during time of operation. + + Returns: + List[logging.LogRecord]: List of log records stored while the + filter was active. + """ + return self._message_cache + + def filter(self, record: logging.LogRecord): + """Cache progress filter that suppresses messages during progress + display output. + + Args: + record (logging.LogRecord): A log record to cache. + """ + self._message_cache.append(record) + + +def check_debug_macros(macros: Iterable[Dict[str, str]], + file_dbg_path: str, + **macro_subs: str + ) -> Tuple[int, int, int]: + """Checks if debug macros contain formatting errors. + + Args: + macros (Iterable[Dict[str, str]]): : A groupdict of macro matches. + This is an iterable of dictionaries with group names from the regex + match as the key and the matched string as the value for the key. + + file_dbg_path (str): The file path (or other custom string) to display + in debug messages. + + macro_subs (Dict[str,str]): Variable-length keyword and replacement + value string pairs to substitute during debug macro checks. + + Returns: + Tuple[int, int, int]: A tuple of the number of formatting errors, + number of print specifiers, and number of arguments for the macros + given. + """ + + macro_subs = {k.lower(): v for k, v in macro_subs.items()} + + arg_cnt, failure_cnt, print_spec_cnt = 0, 0, 0 + for macro in macros: + # Special Specifier Handling + processed_dbg_str = macro['dbg_str'].strip().lower() + + logging.debug(f"Inspecting macro: {macro}") + + # Make any macro substitutions so further processing is applied + # to the substituted value. + for k in macro_subs.keys(): + processed_dbg_str = processed_dbg_str.replace(k, macro_subs[k]) + + logging.debug("Debug macro string after replacements: " + f"{processed_dbg_str}") + + # These are very rarely used in debug strings. They are somewhat + # more common in HII code to control text displayed on the + # console. Due to the rarity and likelihood usage is a mistake, + # a warning is shown if found. + specifier_display_replacements = ['%n', '%h', '%e', '%b', '%v'] + for s in specifier_display_replacements: + if s in processed_dbg_str: + logging.warning(f"File: {file_dbg_path}") + logging.warning(f" {s} found in string and ignored:") + logging.warning(f" \"{processed_dbg_str}\"") + processed_dbg_str = processed_dbg_str.replace(s, '') + + # These are miscellaneous print specifiers that do not require + # special parsing and simply need to be replaced since they do + # have a corresponding argument associated with them. + specifier_other_replacements = ['%%', '\r', '\n'] + for s in specifier_other_replacements: + if s in processed_dbg_str: + processed_dbg_str = processed_dbg_str.replace(s, '') + + processed_dbg_str = re.sub( + r'%[.\-+ ,Ll0-9]*\*[.\-+ ,Ll0-9]*[a-zA-Z]', '%_%_', + processed_dbg_str) + logging.debug(f"Final macro before print specifier scan: " + f"{processed_dbg_str}") + + print_spec_cnt = processed_dbg_str.count('%') + + # Need to take into account parentheses between args in function + # calls that might be in the args list. Use regex module for + # this one since the recursive pattern match helps simplify + # only matching commas outside nested call groups. + if macro['dbg_args'] is None: + processed_arg_str = "" + else: + processed_arg_str = macro['dbg_args'].strip() + + argument_other_replacements = ['\r', '\n'] + for r in argument_other_replacements: + if s in processed_arg_str: + processed_arg_str = processed_arg_str.replace(s, '') + processed_arg_str = re.sub(r' +', ' ', processed_arg_str) + + # Handle special case of commas in arg strings - remove them for + # final count to pick up correct number of argument separating + # commas. + processed_arg_str = re.sub( + r'([\"\'])(?:|\\.|[^\\])*?(\1)', + '', + processed_arg_str) + + arg_matches = regex.findall( + r'(?:\((?:[^)(]+|(?R))*+\))|(,)', + processed_arg_str, + regex.MULTILINE) + + arg_cnt = 0 + if processed_arg_str != '': + arg_cnt = arg_matches.count(',') + + if print_spec_cnt != arg_cnt: + logging.error(f"File: {file_dbg_path}") + logging.error(f" Message = {macro['dbg_str']}") + logging.error(f" Arguments = \"{processed_arg_str}\"") + logging.error(f" Specifier Count = {print_spec_cnt}") + logging.error(f" Argument Count = {arg_cnt}") + + failure_cnt += 1 + + return failure_cnt, print_spec_cnt, arg_cnt + + +def get_debug_macros(file_contents: str) -> List[Dict[str, str]]: + """Extract debug macros from the given file contents. + + Args: + file_contents (str): A string of source file contents that may + contain debug macros. + + Returns: + List[Dict[str, str]]: A groupdict of debug macro regex matches + within the file contents provided. + """ + + # This is the main regular expression that is responsible for identifying + # DEBUG macros within source files and grouping the macro message string + # and macro arguments strings so they can be further processed. + r = regex.compile( + r'(?>(?PDEBUG\s*\(\s*\((?:.*?,))(?:\s*))(?P.*?(?:\"' + r'(?:[^\"\\]|\\.)*\".*?)*)(?:(?(?=,)(?.*?(?=(?:\s*\)){2}\s*;' + r'))))(?:\s*\)){2,};?', + regex.MULTILINE | regex.DOTALL) + return [m.groupdict() for m in r.finditer(file_contents)] + + +def check_macros_in_string(src_str: str, + file_dbg_path: str, + **macro_subs: str) -> Tuple[int, int, int]: + """Checks for debug macro formatting errors in a string. + + Args: + src_str (str): Contents of the string with debug macros. + + file_dbg_path (str): The file path (or other custom string) to display + in debug messages. + + macro_subs (Dict[str,str]): Variable-length keyword and replacement + value string pairs to substitute during debug macro checks. + + Returns: + Tuple[int, int, int]: A tuple of the number of formatting errors, + number of print specifiers, and number of arguments for the macros + in the string given. + """ + return check_debug_macros( + get_debug_macros(src_str), file_dbg_path, **macro_subs) + + +def check_macros_in_file(file: PurePath, + file_dbg_path: str, + show_utf8_decode_warning: bool = False, + **macro_subs: str) -> Tuple[int, int, int]: + """Checks for debug macro formatting errors in a file. + + Args: + file (PurePath): The file path to check. + + file_dbg_path (str): The file path (or other custom string) to display + in debug messages. + + show_utf8_decode_warning (bool, optional): Indicates whether to show + warnings if UTF-8 files fail to decode. Defaults to False. + + macro_subs (Dict[str,str]): Variable-length keyword and replacement + value string pairs to substitute during debug macro checks. + + Returns: + Tuple[int, int, int]: A tuple of the number of formatting errors, + number of print specifiers, and number of arguments for the macros + in the file given. + """ + try: + return check_macros_in_string( + file.read_text(encoding='utf-8'), file_dbg_path, + **macro_subs) + except UnicodeDecodeError as e: + if show_utf8_decode_warning: + logging.warning( + f"{file_dbg_path} UTF-8 decode error.\n" + " Debug macro code check skipped!\n" + f" -> {str(e)}") + return 0, 0, 0 + + +def check_macros_in_directory(directory: PurePath, + file_extensions: Iterable[str] = ('.c',), + ignore_git_ignore_files: Optional[bool] = True, + ignore_git_submodules: Optional[bool] = True, + show_progress_bar: Optional[bool] = True, + show_utf8_decode_warning: bool = False, + **macro_subs: str + ) -> int: + """Checks files with the given extension in the given directory for debug + macro formatting errors. + + Args: + directory (PurePath): The path to the directory to check. + file_extensions (Iterable[str], optional): An iterable of strings + representing file extensions to check. Defaults to ('.c',). + + ignore_git_ignore_files (Optional[bool], optional): Indicates whether + files ignored by git should be ignored for the debug macro check. + Defaults to True. + + ignore_git_submodules (Optional[bool], optional): Indicates whether + files located in git submodules should not be checked. Defaults to + True. + + show_progress_bar (Optional[bool], optional): Indicates whether to + show a progress bar to show progress status while checking macros. + This is more useful on a very large directories. Defaults to True. + + show_utf8_decode_warning (bool, optional): Indicates whether to show + warnings if UTF-8 files fail to decode. Defaults to False. + + macro_subs (Dict[str,str]): Variable-length keyword and replacement + value string pairs to substitute during debug macro checks. + + Returns: + int: Count of debug macro errors in the directory. + """ + def _get_file_list(root_directory: PurePath, + extensions: Iterable[str]) -> List[Path]: + """Returns a list of files recursively located within the path. + + Args: + root_directory (PurePath): A directory Path object to the root + folder. + + extensions (Iterable[str]): An iterable of strings that + represent file extensions to recursively search for within + root_directory. + + Returns: + List[Path]: List of file Path objects to files found in the + given directory with the given extensions. + """ + def _show_file_discovered_message(file_count: int, + elapsed_time: float) -> None: + print(f"\rDiscovered {file_count:,} files in", + f"{current_start_delta:-.0f}s" + f"{'.' * min(int(current_start_delta), 40)}", end="\r") + + start_time = timeit.default_timer() + previous_indicator_time = start_time + + files = [] + for file in root_directory.rglob('*'): + if file.suffix in extensions: + files.append(Path(file)) + + # Give an indicator progress is being made + # This has a negligible impact on overall performance + # with print emission limited to half second intervals. + current_time = timeit.default_timer() + current_start_delta = current_time - start_time + + if current_time - previous_indicator_time >= 0.5: + # Since this rewrites the line, it can be considered a form + # of progress bar + if show_progress_bar: + _show_file_discovered_message(len(files), + current_start_delta) + previous_indicator_time = current_time + + if show_progress_bar: + _show_file_discovered_message(len(files), current_start_delta) + print() + + return files + + logging.info(f"Checking Debug Macros in directory: " + f"{directory.resolve()}\n") + + logging.info("Gathering the overall file list. This might take a" + "while.\n") + + start_time = timeit.default_timer() + file_list = set(_get_file_list(directory, file_extensions)) + end_time = timeit.default_timer() - start_time + + logging.debug(f"[PERF] File search found {len(file_list):,} files in " + f"{end_time:.2f} seconds.") + + if ignore_git_ignore_files: + logging.info("Getting git ignore files...") + start_time = timeit.default_timer() + ignored_file_paths = GitHelpers.get_git_ignored_paths(directory) + end_time = timeit.default_timer() - start_time + + logging.debug(f"[PERF] File ignore gathering took {end_time:.2f} " + f"seconds.") + + logging.info("Ignoring git ignore files...") + logging.debug(f"File list count before git ignore {len(file_list):,}") + start_time = timeit.default_timer() + file_list = file_list.difference(ignored_file_paths) + end_time = timeit.default_timer() - start_time + logging.info(f" {len(ignored_file_paths):,} files are ignored by git") + logging.info(f" {len(file_list):,} files after removing " + f"ignored files") + + logging.debug(f"[PERF] File ignore calculation took {end_time:.2f} " + f"seconds.") + + if ignore_git_submodules: + logging.info("Ignoring git submodules...") + submodule_paths = GitHelpers.get_git_submodule_paths(directory) + if submodule_paths: + logging.debug(f"File list count before git submodule exclusion " + f"{len(file_list):,}") + start_time = timeit.default_timer() + file_list = [f for f in file_list + if not f.is_relative_to(*submodule_paths)] + end_time = timeit.default_timer() - start_time + + for path in enumerate(submodule_paths): + logging.debug(" {0}. {1}".format(*path)) + + logging.info(f" {len(submodule_paths):,} submodules found") + logging.info(f" {len(file_list):,} files will be examined after " + f"excluding files in submodules") + + logging.debug(f"[PERF] Submodule exclusion calculation took " + f"{end_time:.2f} seconds.") + else: + logging.warning("No submodules found") + + logging.info(f"\nStarting macro check on {len(file_list):,} files.") + + cache_progress_filter = CacheDuringProgressFilter() + handler = next((h for h in logging.getLogger().handlers if h.get_name() == + 'stdout_logger_handler'), None) + + if handler is not None: + handler.addFilter(cache_progress_filter) + + start_time = timeit.default_timer() + + failure_cnt, file_cnt = 0, 0 + for file_cnt, file in enumerate(file_list): + file_rel_path = str(file.relative_to(directory)) + failure_cnt += check_macros_in_file( + file, file_rel_path, show_utf8_decode_warning, + **macro_subs)[0] + if show_progress_bar: + _show_progress(file_cnt, len(file_list), + f" {failure_cnt} errors" if failure_cnt > 0 else "") + + if show_progress_bar: + _show_progress(len(file_list), len(file_list), + f" {failure_cnt} errors" if failure_cnt > 0 else "") + print("\n", flush=True) + + end_time = timeit.default_timer() - start_time + + if handler is not None: + handler.removeFilter(cache_progress_filter) + + for record in cache_progress_filter.message_cache: + handler.emit(record) + + logging.debug(f"[PERF] The macro check operation took {end_time:.2f} " + f"seconds.") + + _log_failure_count(failure_cnt, file_cnt) + + return failure_cnt + + +def _log_failure_count(failure_count: int, file_count: int) -> None: + """Logs the failure count. + + Args: + failure_count (int): Count of failures to log. + + file_count (int): Count of files with failures. + """ + if failure_count > 0: + logging.error("\n") + logging.error(f"{failure_count:,} debug macro errors in " + f"{file_count:,} files") + + +def _show_progress(step: int, total: int, suffix: str = '') -> None: + """Print progress of tick to total. + + Args: + step (int): The current step count. + + total (int): The total step count. + + suffix (str): String to print at the end of the progress bar. + """ + global _progress_start_time + + if step == 0: + _progress_start_time = timeit.default_timer() + + terminal_col = shutil.get_terminal_size().columns + var_consume_len = (len("Progress|\u2588| 000.0% Complete 000s") + + len(suffix)) + avail_len = terminal_col - var_consume_len + + percent = f"{100 * (step / float(total)):3.1f}" + filled = int(avail_len * step // total) + bar = '\u2588' * filled + '-' * (avail_len - filled) + step_time = timeit.default_timer() - _progress_start_time + + print(f'\rProgress|{bar}| {percent}% Complete {step_time:-3.0f}s' + f'{suffix}', end='\r') + + +def _module_invocation_check_macros_in_directory_wrapper() -> int: + """Provides an command-line argument wrapper for checking debug macros. + + Returns: + int: The system exit code value. + """ + import argparse + import builtins + + def _check_dir_path(dir_path: str) -> bool: + """Returns the absolute path if the path is a directory." + + Args: + dir_path (str): A directory file system path. + + Raises: + NotADirectoryError: The directory path given is not a directory. + + Returns: + bool: True if the path is a directory else False. + """ + abs_dir_path = os.path.abspath(dir_path) + if os.path.isdir(dir_path): + return abs_dir_path + else: + raise NotADirectoryError(abs_dir_path) + + def _check_file_path(file_path: str) -> bool: + """Returns the absolute path if the path is a file." + + Args: + file_path (str): A file path. + + Raises: + FileExistsError: The path is not a valid file. + + Returns: + bool: True if the path is a valid file else False. + """ + abs_file_path = os.path.abspath(file_path) + if os.path.isfile(file_path): + return abs_file_path + else: + raise FileExistsError(file_path) + + def _quiet_print(*args, **kwargs): + """Replaces print when quiet is requested to prevent printing messages. + """ + pass + + root_logger = logging.getLogger() + root_logger.setLevel(logging.DEBUG) + + stdout_logger_handler = logging.StreamHandler(sys.stdout) + stdout_logger_handler.set_name('stdout_logger_handler') + stdout_logger_handler.setLevel(logging.INFO) + stdout_logger_handler.setFormatter(logging.Formatter('%(message)s')) + root_logger.addHandler(stdout_logger_handler) + + parser = argparse.ArgumentParser( + prog=PROGRAM_NAME, + description=( + "Checks for debug macro formatting " + "errors within files recursively located within " + "a given directory."), + formatter_class=RawTextHelpFormatter) + + io_req_group = parser.add_mutually_exclusive_group(required=True) + io_opt_group = parser.add_argument_group( + "Optional input and output") + git_group = parser.add_argument_group("Optional git control") + + io_req_group.add_argument('-w', '--workspace-directory', + type=_check_dir_path, + help="Directory of source files to check.\n\n") + + io_req_group.add_argument('-i', '--input-file', nargs='?', + type=_check_file_path, + help="File path for an input file to check.\n\n" + "Note that some other options do not apply " + "if a single file is specified such as " + "the\ngit options and file extensions.\n\n") + + io_opt_group.add_argument('-l', '--log-file', + nargs='?', + default=None, + const='debug_macro_check.log', + help="File path for log output.\n" + "(default: if the flag is given with no " + "file path then a file called\n" + "debug_macro_check.log is created and used " + "in the current directory)\n\n") + + io_opt_group.add_argument('-s', '--substitution-file', + type=_check_file_path, + help="A substitution YAML file specifies string " + "substitutions to perform within the debug " + "macro.\n\nThis is intended to be a simple " + "mechanism to expand the rare cases of pre-" + "processor\nmacros without directly " + "involving the pre-processor. The file " + "consists of one or more\nstring value " + "pairs where the key is the identifier to " + "replace and the value is the value\nto " + "replace it with.\n\nThis can also be used " + "as a method to ignore results by " + "replacing the problematic string\nwith a " + "different string.\n\n") + + io_opt_group.add_argument('-v', '--verbose-log-file', + action='count', + default=0, + help="Set file logging verbosity level.\n" + " - None: Info & > level messages\n" + " - '-v': + Debug level messages\n" + " - '-vv': + File name and function\n" + " - '-vvv': + Line number\n" + " - '-vvvv': + Timestamp\n" + "(default: verbose logging is not enabled)" + "\n\n") + + io_opt_group.add_argument('-n', '--no-progress-bar', action='store_true', + help="Disables progress bars.\n" + "(default: progress bars are used in some" + "places to show progress)\n\n") + + io_opt_group.add_argument('-q', '--quiet', action='store_true', + help="Disables console output.\n" + "(default: console output is enabled)\n\n") + + io_opt_group.add_argument('-u', '--utf8w', action='store_true', + help="Shows warnings for file UTF-8 decode " + "errors.\n" + "(default: UTF-8 decode errors are not " + "shown)\n\n") + + git_group.add_argument('-df', '--do-not-ignore-git-ignore-files', + action='store_true', + help="Do not ignore git ignored files.\n" + "(default: files in git ignore files are " + "ignored)\n\n") + + git_group.add_argument('-ds', '--do-not-ignore-git_submodules', + action='store_true', + help="Do not ignore files in git submodules.\n" + "(default: files in git submodules are " + "ignored)\n\n") + + parser.add_argument('-e', '--extensions', nargs='*', default=['.c'], + help="List of file extensions to include.\n" + "(default: %(default)s)") + + args = parser.parse_args() + + if args.quiet: + # Don't print in the few places that directly print + builtins.print = _quiet_print + stdout_logger_handler.addFilter(QuietFilter(args.quiet)) + + if args.log_file: + file_logger_handler = logging.FileHandler(filename=args.log_file, + mode='w', encoding='utf-8') + + # In an ideal world, everyone would update to the latest Python + # minor version (3.10) after a few weeks/months. Since that's not the + # case, resist from using structural pattern matching in Python 3.10. + # https://peps.python.org/pep-0636/ + + if args.verbose_log_file == 0: + file_logger_handler.setLevel(logging.INFO) + file_logger_formatter = logging.Formatter( + '%(levelname)-8s %(message)s') + elif args.verbose_log_file == 1: + file_logger_handler.setLevel(logging.DEBUG) + file_logger_formatter = logging.Formatter( + '%(levelname)-8s %(message)s') + elif args.verbose_log_file == 2: + file_logger_handler.setLevel(logging.DEBUG) + file_logger_formatter = logging.Formatter( + '[%(filename)s - %(funcName)20s() ] %(levelname)-8s ' + '%(message)s') + elif args.verbose_log_file == 3: + file_logger_handler.setLevel(logging.DEBUG) + file_logger_formatter = logging.Formatter( + '[%(filename)s:%(lineno)s - %(funcName)20s() ] ' + '%(levelname)-8s %(message)s') + elif args.verbose_log_file == 4: + file_logger_handler.setLevel(logging.DEBUG) + file_logger_formatter = logging.Formatter( + '%(asctime)s [%(filename)s:%(lineno)s - %(funcName)20s() ]' + ' %(levelname)-8s %(message)s') + else: + file_logger_handler.setLevel(logging.DEBUG) + file_logger_formatter = logging.Formatter( + '%(asctime)s [%(filename)s:%(lineno)s - %(funcName)20s() ]' + ' %(levelname)-8s %(message)s') + + file_logger_handler.addFilter(ProgressFilter()) + file_logger_handler.setFormatter(file_logger_formatter) + root_logger.addHandler(file_logger_handler) + + logging.info(PROGRAM_NAME + "\n") + + log_old_python_version_warning() + + substitution_data = {} + if args.substitution_file: + logging.info(f"Loading substitution file {args.substitution_file}") + with open(args.substitution_file, 'r') as sf: + substitution_data = yaml.safe_load(sf) + + if args.workspace_directory: + return check_macros_in_directory( + Path(args.workspace_directory), + args.extensions, + not args.do_not_ignore_git_ignore_files, + not args.do_not_ignore_git_submodules, + not args.no_progress_bar, + args.utf8w, + **substitution_data) + else: + curr_dir = Path(__file__).parent + input_file = Path(args.input_file) + + rel_path = str(input_file) + if input_file.is_relative_to(curr_dir): + rel_path = str(input_file.relative_to(curr_dir)) + + logging.info(f"Checking Debug Macros in File: " + f"{input_file.resolve()}\n") + + start_time = timeit.default_timer() + failure_cnt = check_macros_in_file( + input_file, + rel_path, + args.utf8w, + **substitution_data)[0] + end_time = timeit.default_timer() - start_time + + logging.debug(f"[PERF] The file macro check operation took " + f"{end_time:.2f} seconds.") + + _log_failure_count(failure_cnt, 1) + + return failure_cnt + + +if __name__ == '__main__': + # The exit status value is the number of macro formatting errors found. + # Therefore, if no macro formatting errors are found, 0 is returned. + # Some systems require the return value to be in the range 0-127, so + # a lower maximum of 100 is enforced to allow a wide range of potential + # values with a reasonably large maximum. + try: + sys.exit(max(_module_invocation_check_macros_in_directory_wrapper(), + 100)) + except KeyboardInterrupt: + logging.warning("Exiting due to keyboard interrupt.") + # Actual formatting errors are only allowed to reach 100. + # 101 signals a keyboard interrupt. + sys.exit(101) + except FileExistsError as e: + # 102 signals a file not found error. + logging.critical(f"Input file {e.args[0]} does not exist.") + sys.exit(102) +else: + log_old_python_version_warning() diff --git a/.pytool/Plugin/DebugMacroCheck/tests/test_DebugMacroCheck.py b/.pytool/Plugin/DebugMacroCheck/tests/test_DebugMacroCheck.py index dddc760416..db51d23e03 100644 --- a/.pytool/Plugin/DebugMacroCheck/tests/test_DebugMacroCheck.py +++ b/.pytool/Plugin/DebugMacroCheck/tests/test_DebugMacroCheck.py @@ -1,201 +1,201 @@ -# @file test_DebugMacroCheck.py -# -# Contains unit tests for the DebugMacroCheck build plugin. -# -# An example of running these tests from the root of the workspace: -# python -m unittest discover -s ./.pytool/Plugin/DebugMacroCheck/tests -v -# -# Copyright (c) Microsoft Corporation. All rights reserved. -# SPDX-License-Identifier: BSD-2-Clause-Patent -## - -import inspect -import pathlib -import sys -import unittest - -# Import the build plugin -test_file = pathlib.Path(__file__) -sys.path.append(str(test_file.parent.parent)) - -# flake8 (E402): Ignore flake8 module level import not at top of file -import DebugMacroCheck # noqa: E402 - -from os import linesep # noqa: E402 -from tests import DebugMacroDataSet # noqa: E402 -from tests import MacroTest # noqa: E402 -from typing import Callable, Tuple # noqa: E402 - - -# -# This metaclass is provided to dynamically produce test case container -# classes. The main purpose of this approach is to: -# 1. Allow categories of test cases to be defined (test container classes) -# 2. Allow test cases to automatically (dynamically) be assigned to their -# corresponding test container class when new test data is defined. -# -# The idea being that infrastructure and test data are separated. Adding -# / removing / modifying test data does not require an infrastructure -# change (unless new categories are defined). -# 3. To work with the unittest discovery algorithm and VS Code Test Explorer. -# -# Notes: -# - (1) can roughly be achieved with unittest test suites. In another -# implementation approach, this solution was tested with relatively minor -# modifications to use test suites. However, this became a bit overly -# complicated with the dynamic test case method generation and did not -# work as well with VS Code Test Explorer. -# - For (2) and (3), particularly for VS Code Test Explorer to work, the -# dynamic population of the container class namespace needed to happen prior -# to class object creation. That is why the metaclass assigns test methods -# to the new classes based upon the test category specified in the -# corresponding data class. -# - This could have been simplified a bit by either using one test case -# container class and/or testing data in a single, monolithic test function -# that iterates over the data set. However, the dynamic hierarchy greatly -# helps organize test results and reporting. The infrastructure though -# inheriting some complexity to support it, should not need to change (much) -# as the data set expands. -# - Test case categories (container classes) are derived from the overall -# type of macro conditions under test. -# -# - This implementation assumes unittest will discover test cases -# (classes derived from unittest.TestCase) with the name pattern "Test_*" -# and test functions with the name pattern "test_x". Individual tests are -# dynamically numbered monotonically within a category. -# - The final test case description is also able to return fairly clean -# context information. -# -class Meta_TestDebugMacroCheck(type): - """ - Metaclass for debug macro test case class factory. - """ - @classmethod - def __prepare__(mcls, name, bases, **kwargs): - """Returns the test case namespace for this class.""" - candidate_macros, cls_ns, cnt = [], {}, 0 - - if "category" in kwargs.keys(): - candidate_macros = [m for m in DebugMacroDataSet.DEBUG_MACROS if - m.category == kwargs["category"]] - else: - candidate_macros = DebugMacroDataSet.DEBUG_MACROS - - for cnt, macro_test in enumerate(candidate_macros): - f_name = f'test_{macro_test.category}_{cnt}' - t_desc = f'{macro_test!s}' - cls_ns[f_name] = mcls.build_macro_test(macro_test, t_desc) - return cls_ns - - def __new__(mcls, name, bases, ns, **kwargs): - """Defined to prevent variable args from bubbling to the base class.""" - return super().__new__(mcls, name, bases, ns) - - def __init__(mcls, name, bases, ns, **kwargs): - """Defined to prevent variable args from bubbling to the base class.""" - return super().__init__(name, bases, ns) - - @classmethod - def build_macro_test(cls, macro_test: MacroTest.MacroTest, - test_desc: str) -> Callable[[None], None]: - """Returns a test function for this macro test data." - - Args: - macro_test (MacroTest.MacroTest): The macro test class. - - test_desc (str): A test description string. - - Returns: - Callable[[None], None]: A test case function. - """ - def test_func(self): - act_result = cls.check_regex(macro_test.macro) - self.assertCountEqual( - act_result, - macro_test.result, - test_desc + f'{linesep}'.join( - ["", f"Actual Result: {act_result}", "=" * 80, ""])) - - return test_func - - @classmethod - def check_regex(cls, source_str: str) -> Tuple[int, int, int]: - """Returns the plugin result for the given macro string. - - Args: - source_str (str): A string containing debug macros. - - Returns: - Tuple[int, int, int]: A tuple of the number of formatting errors, - number of print specifiers, and number of arguments for the macros - given. - """ - return DebugMacroCheck.check_debug_macros( - DebugMacroCheck.get_debug_macros(source_str), - cls._get_function_name()) - - @classmethod - def _get_function_name(cls) -> str: - """Returns the function name from one level of call depth. - - Returns: - str: The caller function name. - """ - return "function: " + inspect.currentframe().f_back.f_code.co_name - - -# Test container classes for dynamically generated macro test cases. -# A class can be removed below to skip / remove it from testing. -# Test case functions will be added to the appropriate class as they are -# created. -class Test_NoSpecifierNoArgument( - unittest.TestCase, - metaclass=Meta_TestDebugMacroCheck, - category="no_specifier_no_argument_macro_test"): - pass - - -class Test_EqualSpecifierEqualArgument( - unittest.TestCase, - metaclass=Meta_TestDebugMacroCheck, - category="equal_specifier_equal_argument_macro_test"): - pass - - -class Test_MoreSpecifiersThanArguments( - unittest.TestCase, - metaclass=Meta_TestDebugMacroCheck, - category="more_specifiers_than_arguments_macro_test"): - pass - - -class Test_LessSpecifiersThanArguments( - unittest.TestCase, - metaclass=Meta_TestDebugMacroCheck, - category="less_specifiers_than_arguments_macro_test"): - pass - - -class Test_IgnoredSpecifiers( - unittest.TestCase, - metaclass=Meta_TestDebugMacroCheck, - category="ignored_specifiers_macro_test"): - pass - - -class Test_SpecialParsingMacroTest( - unittest.TestCase, - metaclass=Meta_TestDebugMacroCheck, - category="special_parsing_macro_test"): - pass - - -class Test_CodeSnippetMacroTest( - unittest.TestCase, - metaclass=Meta_TestDebugMacroCheck, - category="code_snippet_macro_test"): - pass - - -if __name__ == '__main__': - unittest.main() +# @file test_DebugMacroCheck.py +# +# Contains unit tests for the DebugMacroCheck build plugin. +# +# An example of running these tests from the root of the workspace: +# python -m unittest discover -s ./.pytool/Plugin/DebugMacroCheck/tests -v +# +# Copyright (c) Microsoft Corporation. All rights reserved. +# SPDX-License-Identifier: BSD-2-Clause-Patent +## + +import inspect +import pathlib +import sys +import unittest + +# Import the build plugin +test_file = pathlib.Path(__file__) +sys.path.append(str(test_file.parent.parent)) + +# flake8 (E402): Ignore flake8 module level import not at top of file +import DebugMacroCheck # noqa: E402 + +from os import linesep # noqa: E402 +from tests import DebugMacroDataSet # noqa: E402 +from tests import MacroTest # noqa: E402 +from typing import Callable, Tuple # noqa: E402 + + +# +# This metaclass is provided to dynamically produce test case container +# classes. The main purpose of this approach is to: +# 1. Allow categories of test cases to be defined (test container classes) +# 2. Allow test cases to automatically (dynamically) be assigned to their +# corresponding test container class when new test data is defined. +# +# The idea being that infrastructure and test data are separated. Adding +# / removing / modifying test data does not require an infrastructure +# change (unless new categories are defined). +# 3. To work with the unittest discovery algorithm and VS Code Test Explorer. +# +# Notes: +# - (1) can roughly be achieved with unittest test suites. In another +# implementation approach, this solution was tested with relatively minor +# modifications to use test suites. However, this became a bit overly +# complicated with the dynamic test case method generation and did not +# work as well with VS Code Test Explorer. +# - For (2) and (3), particularly for VS Code Test Explorer to work, the +# dynamic population of the container class namespace needed to happen prior +# to class object creation. That is why the metaclass assigns test methods +# to the new classes based upon the test category specified in the +# corresponding data class. +# - This could have been simplified a bit by either using one test case +# container class and/or testing data in a single, monolithic test function +# that iterates over the data set. However, the dynamic hierarchy greatly +# helps organize test results and reporting. The infrastructure though +# inheriting some complexity to support it, should not need to change (much) +# as the data set expands. +# - Test case categories (container classes) are derived from the overall +# type of macro conditions under test. +# +# - This implementation assumes unittest will discover test cases +# (classes derived from unittest.TestCase) with the name pattern "Test_*" +# and test functions with the name pattern "test_x". Individual tests are +# dynamically numbered monotonically within a category. +# - The final test case description is also able to return fairly clean +# context information. +# +class Meta_TestDebugMacroCheck(type): + """ + Metaclass for debug macro test case class factory. + """ + @classmethod + def __prepare__(mcls, name, bases, **kwargs): + """Returns the test case namespace for this class.""" + candidate_macros, cls_ns, cnt = [], {}, 0 + + if "category" in kwargs.keys(): + candidate_macros = [m for m in DebugMacroDataSet.DEBUG_MACROS if + m.category == kwargs["category"]] + else: + candidate_macros = DebugMacroDataSet.DEBUG_MACROS + + for cnt, macro_test in enumerate(candidate_macros): + f_name = f'test_{macro_test.category}_{cnt}' + t_desc = f'{macro_test!s}' + cls_ns[f_name] = mcls.build_macro_test(macro_test, t_desc) + return cls_ns + + def __new__(mcls, name, bases, ns, **kwargs): + """Defined to prevent variable args from bubbling to the base class.""" + return super().__new__(mcls, name, bases, ns) + + def __init__(mcls, name, bases, ns, **kwargs): + """Defined to prevent variable args from bubbling to the base class.""" + return super().__init__(name, bases, ns) + + @classmethod + def build_macro_test(cls, macro_test: MacroTest.MacroTest, + test_desc: str) -> Callable[[None], None]: + """Returns a test function for this macro test data." + + Args: + macro_test (MacroTest.MacroTest): The macro test class. + + test_desc (str): A test description string. + + Returns: + Callable[[None], None]: A test case function. + """ + def test_func(self): + act_result = cls.check_regex(macro_test.macro) + self.assertCountEqual( + act_result, + macro_test.result, + test_desc + f'{linesep}'.join( + ["", f"Actual Result: {act_result}", "=" * 80, ""])) + + return test_func + + @classmethod + def check_regex(cls, source_str: str) -> Tuple[int, int, int]: + """Returns the plugin result for the given macro string. + + Args: + source_str (str): A string containing debug macros. + + Returns: + Tuple[int, int, int]: A tuple of the number of formatting errors, + number of print specifiers, and number of arguments for the macros + given. + """ + return DebugMacroCheck.check_debug_macros( + DebugMacroCheck.get_debug_macros(source_str), + cls._get_function_name()) + + @classmethod + def _get_function_name(cls) -> str: + """Returns the function name from one level of call depth. + + Returns: + str: The caller function name. + """ + return "function: " + inspect.currentframe().f_back.f_code.co_name + + +# Test container classes for dynamically generated macro test cases. +# A class can be removed below to skip / remove it from testing. +# Test case functions will be added to the appropriate class as they are +# created. +class Test_NoSpecifierNoArgument( + unittest.TestCase, + metaclass=Meta_TestDebugMacroCheck, + category="no_specifier_no_argument_macro_test"): + pass + + +class Test_EqualSpecifierEqualArgument( + unittest.TestCase, + metaclass=Meta_TestDebugMacroCheck, + category="equal_specifier_equal_argument_macro_test"): + pass + + +class Test_MoreSpecifiersThanArguments( + unittest.TestCase, + metaclass=Meta_TestDebugMacroCheck, + category="more_specifiers_than_arguments_macro_test"): + pass + + +class Test_LessSpecifiersThanArguments( + unittest.TestCase, + metaclass=Meta_TestDebugMacroCheck, + category="less_specifiers_than_arguments_macro_test"): + pass + + +class Test_IgnoredSpecifiers( + unittest.TestCase, + metaclass=Meta_TestDebugMacroCheck, + category="ignored_specifiers_macro_test"): + pass + + +class Test_SpecialParsingMacroTest( + unittest.TestCase, + metaclass=Meta_TestDebugMacroCheck, + category="special_parsing_macro_test"): + pass + + +class Test_CodeSnippetMacroTest( + unittest.TestCase, + metaclass=Meta_TestDebugMacroCheck, + category="code_snippet_macro_test"): + pass + + +if __name__ == '__main__': + unittest.main() diff --git a/.pytool/Plugin/ImageValidation/ImageValidation.py b/.pytool/Plugin/ImageValidation/ImageValidation.py index 532c6fa6f7..789412ec79 100644 --- a/.pytool/Plugin/ImageValidation/ImageValidation.py +++ b/.pytool/Plugin/ImageValidation/ImageValidation.py @@ -1,275 +1,275 @@ -# @file ImageValidation.py -# Plugin to validate any PE images against a set of requirements -## -# Copyright (c) Microsoft Corporation. -# SPDX-License-Identifier: BSD-2-Clause-Patent -## - -import os -import re -from pathlib import Path -from pefile import PE -from edk2toolext.environment.plugintypes.uefi_build_plugin import IUefiBuildPlugin -from edk2toolext.image_validation import * -from edk2toollib.uefi.edk2.path_utilities import Edk2Path -from edk2toollib.uefi.edk2.parsers.inf_parser import InfParser -from edk2toollib.uefi.edk2.parsers.fdf_parser import FdfParser -from edk2toollib.uefi.edk2.parsers.dsc_parser import DscParser -from edk2toollib.uefi.edk2.parsers.dsc_parser import * -import json -from typing import List -import logging -from datetime import datetime - - -class ImageValidation(IUefiBuildPlugin): - def __init__(self): - self.test_manager = TestManager() - - # Default tests provided by edk2toolext.image_validation - self.test_manager.add_test(TestWriteExecuteFlags()) - self.test_manager.add_test(TestSectionAlignment()) - self.test_manager.add_test(TestSubsystemValue()) - # Add additional Tests here - - def do_post_build(self, thebuilder): - - starttime = datetime.now() - logging.info( - "---------------------------------------------------------") - logging.info( - "-----------Postbuild Image Validation Starting-----------") - logging.info( - "---------------------------------------------------------") - - # Load Configuration Data - config_path = thebuilder.env.GetValue("PE_VALIDATION_PATH", None) - tool_chain_tag = thebuilder.env.GetValue("TOOL_CHAIN_TAG") - if config_path is None: - logging.info( - "PE_VALIDATION_PATH not set, PE Image Validation Skipped") - return 0 # Path not set, Plugin skipped - - if not os.path.isfile(config_path): - logging.error("Invalid PE_VALIDATION_PATH. File not Found") - return 1 - - with open(config_path) as jsonfile: - config_data = json.load(jsonfile) - - self.test_manager.config_data = config_data - self.config_data = config_data - self.ignore_list = config_data["IGNORE_LIST"] - self.arch_dict = config_data["TARGET_ARCH"] - - count = 0 - - # Start Pre-Compiled Image Verification - fdf_parser = FdfParser() - dsc_parser = DscParser() - - ws = thebuilder.ws - pp = thebuilder.pp.split(os.pathsep) - edk2 = Edk2Path(ws, pp) - - ActiveDsc = edk2.GetAbsolutePathOnThisSystemFromEdk2RelativePath( - thebuilder.env.GetValue("ACTIVE_PLATFORM")) - ActiveFdf = edk2.GetAbsolutePathOnThisSystemFromEdk2RelativePath( - thebuilder.env.GetValue("FLASH_DEFINITION")) - - if ActiveFdf is None: - logging.info("No FDF found - PE Image Validation skipped") - return 0 - - # parse the DSC and the FDF - dsc_parser.SetBaseAbsPath(ws).SetPackagePaths(pp) - dsc_parser.SetInputVars(thebuilder.env.GetAllBuildKeyValues()).ParseFile( - ActiveDsc) # parse the DSC for build vars - fdf_parser.SetBaseAbsPath(ws).SetPackagePaths(pp) - fdf_parser.SetInputVars(dsc_parser.LocalVars).ParseFile( - ActiveFdf) # give FDF parser the vars from DSC - - # Test all pre-compiled efis described in the fdf - result = Result.PASS - for FV_name in fdf_parser.FVs: # Get all Firmware volumes - FV_files = fdf_parser.FVs[FV_name]["Files"] - for fv_file_name in FV_files: # Iterate over each file in the firmware volume - fv_file = FV_files[fv_file_name] - if "PE32" in fv_file: # Any PE32 section in the FV contains a path to the efi - # could have multiple PE32 sections - for efi_path in fv_file["PE32"]: - efi_path = self._resolve_vars(thebuilder, efi_path) - efi_path = edk2.GetAbsolutePathOnThisSystemFromEdk2RelativePath( - efi_path) - if efi_path == None: - logging.warn( - "Unable to parse the path to the pre-compiled efi") - continue - if os.path.basename(efi_path) in self.ignore_list: - continue - logging.info( - f'Performing Image Verification ... {os.path.basename(efi_path)}') - if self._validate_image(efi_path, fv_file["type"]) == Result.FAIL: - result = Result.FAIL - count += 1 - # End Pre-Compiled Image Verification - - # Start Build Time Compiled Image Verification - result = Result.PASS - for arch in thebuilder.env.GetValue("TARGET_ARCH").split(): - efi_path_list = self._walk_directory_for_extension( - ['.efi'], f'{thebuilder.env.GetValue("BUILD_OUTPUT_BASE")}/{arch}') - - for efi_path in efi_path_list: - if os.path.basename(efi_path) in self.ignore_list: - continue - - # Perform Image Verification on any output efi's - # Grab profile from makefile - if efi_path.__contains__("OUTPUT"): - try: - if tool_chain_tag.__contains__("VS"): - profile = self._get_profile_from_makefile( - f'{Path(efi_path).parent.parent}/Makefile') - - elif tool_chain_tag.__contains__("GCC"): - profile = self._get_profile_from_makefile( - f'{Path(efi_path).parent.parent}/GNUmakefile') - - elif tool_chain_tag.__contains__("CLANG"): - profile = self._get_profile_from_makefile( - f'{Path(efi_path).parent.parent}/GNUmakefile') - else: - logging.warn("Unexpected TOOL_CHAIN_TAG... Cannot parse makefile. Using DEFAULT profile.") - profile = "DEFAULT" - except: - logging.warn(f'Failed to parse makefile at [{Path(efi_path).parent.parent}/GNUmakefile]') - logging.warn(f'Using DEFAULT profile') - profile = "DEFAULT" - - logging.info( - f'Performing Image Verification ... {os.path.basename(efi_path)}') - if self._validate_image(efi_path, profile) == Result.FAIL: - result = Result.FAIL - count += 1 - # End Built Time Compiled Image Verification - - endtime = datetime.now() - delta = endtime - starttime - logging.info( - "---------------------------------------------------------") - logging.info( - "-----------Postbuild Image Validation Finished-----------") - logging.info( - "------------------{:04d} Images Verified-------------------".format(count)) - logging.info( - "-------------- Running Time (mm:ss): {0[0]:02}:{0[1]:02} --------------".format(divmod(delta.seconds, 60))) - logging.info( - "---------------------------------------------------------") - - if result == Result.FAIL: - return 1 - else: - return 0 - - # Executes run_tests() on the efi - def _validate_image(self, efi_path, profile="DEFAULT"): - pe = PE(efi_path) - - target_config = self.config_data[MACHINE_TYPE[pe.FILE_HEADER.Machine]].get( - profile) - if target_config == {}: # The target_config is present, but empty, therefore, override to default - profile = "DEFAULT" - - return self.test_manager.run_tests(pe, profile) - - # Reads the Makefile of an efi, if present, to determine profile - def _get_profile_from_makefile(self, makefile): - with open(makefile) as file: - for line in file.readlines(): - if line.__contains__('MODULE_TYPE'): - line = line.split('=') - module_type = line[1] - module_type = module_type.strip() - return module_type - return "DEFAULT" - - # Attempts to convert shorthand arch such as X64 to the - # Fully describe architecture. Additional support for - # Fallback architectures can be added here - def _try_convert_full_arch(self, arch): - full_arch = self.arch_dict.get(arch) - if full_arch == None: - if arch.__contains__("ARM"): - full_arch = "IMAGE_FILE_MACHINE_ARM" - # Add other Arches - return full_arch - - # Resolves variable names matching the $(...) pattern. - def _resolve_vars(self, thebuilder, s): - var_pattern = re.compile(r'\$\([^)]*\)') # Detect $(...) pattern - env = thebuilder.env - rs = s - for match in var_pattern.findall(s): - var_name = match[2:-1] - env_var = env.GetValue(var_name) if env.GetValue( - var_name) != None else env.GetBuildValue(var_name) - if env_var == None: - pass - rs = rs.replace(match, env_var) - return rs - - def _walk_directory_for_extension(self, extensionlist: List[str], directory: os.PathLike, - ignorelist: List[str] = None) -> List[os.PathLike]: - ''' Walks a file directory recursively for all items ending in certain extension - @extensionlist: List[str] list of file extensions - @directory: Path - absolute path to directory to start looking - @ignorelist: List[str] or None. optional - default is None: a list of case insensitive filenames to ignore - @returns a List of file paths to matching files - ''' - if not isinstance(extensionlist, list): - logging.critical("Expected list but got " + - str(type(extensionlist))) - raise TypeError("extensionlist must be a list") - - if directory is None: - logging.critical("No directory given") - raise TypeError("directory is None") - - if not os.path.isabs(directory): - logging.critical("Directory not abs path") - raise ValueError("directory is not an absolute path") - - if not os.path.isdir(directory): - logging.critical("Invalid find directory to walk") - raise ValueError("directory is not a valid directory path") - - if ignorelist is not None: - if not isinstance(ignorelist, list): - logging.critical("Expected list but got " + - str(type(ignorelist))) - raise TypeError("ignorelist must be a list") - - ignorelist_lower = list() - for item in ignorelist: - ignorelist_lower.append(item.lower()) - - extensionlist_lower = list() - for item in extensionlist: - extensionlist_lower.append(item.lower()) - - returnlist = list() - for Root, Dirs, Files in os.walk(directory): - for File in Files: - for Extension in extensionlist_lower: - if File.lower().endswith(Extension): - ignoreIt = False - if(ignorelist is not None): - for c in ignorelist_lower: - if(File.lower().startswith(c)): - ignoreIt = True - break - if not ignoreIt: - returnlist.append(os.path.join(Root, File)) - - return returnlist +# @file ImageValidation.py +# Plugin to validate any PE images against a set of requirements +## +# Copyright (c) Microsoft Corporation. +# SPDX-License-Identifier: BSD-2-Clause-Patent +## + +import os +import re +from pathlib import Path +from pefile import PE +from edk2toolext.environment.plugintypes.uefi_build_plugin import IUefiBuildPlugin +from edk2toolext.image_validation import * +from edk2toollib.uefi.edk2.path_utilities import Edk2Path +from edk2toollib.uefi.edk2.parsers.inf_parser import InfParser +from edk2toollib.uefi.edk2.parsers.fdf_parser import FdfParser +from edk2toollib.uefi.edk2.parsers.dsc_parser import DscParser +from edk2toollib.uefi.edk2.parsers.dsc_parser import * +import json +from typing import List +import logging +from datetime import datetime + + +class ImageValidation(IUefiBuildPlugin): + def __init__(self): + self.test_manager = TestManager() + + # Default tests provided by edk2toolext.image_validation + self.test_manager.add_test(TestWriteExecuteFlags()) + self.test_manager.add_test(TestSectionAlignment()) + self.test_manager.add_test(TestSubsystemValue()) + # Add additional Tests here + + def do_post_build(self, thebuilder): + + starttime = datetime.now() + logging.info( + "---------------------------------------------------------") + logging.info( + "-----------Postbuild Image Validation Starting-----------") + logging.info( + "---------------------------------------------------------") + + # Load Configuration Data + config_path = thebuilder.env.GetValue("PE_VALIDATION_PATH", None) + tool_chain_tag = thebuilder.env.GetValue("TOOL_CHAIN_TAG") + if config_path is None: + logging.info( + "PE_VALIDATION_PATH not set, PE Image Validation Skipped") + return 0 # Path not set, Plugin skipped + + if not os.path.isfile(config_path): + logging.error("Invalid PE_VALIDATION_PATH. File not Found") + return 1 + + with open(config_path) as jsonfile: + config_data = json.load(jsonfile) + + self.test_manager.config_data = config_data + self.config_data = config_data + self.ignore_list = config_data["IGNORE_LIST"] + self.arch_dict = config_data["TARGET_ARCH"] + + count = 0 + + # Start Pre-Compiled Image Verification + fdf_parser = FdfParser() + dsc_parser = DscParser() + + ws = thebuilder.ws + pp = thebuilder.pp.split(os.pathsep) + edk2 = Edk2Path(ws, pp) + + ActiveDsc = edk2.GetAbsolutePathOnThisSystemFromEdk2RelativePath( + thebuilder.env.GetValue("ACTIVE_PLATFORM")) + ActiveFdf = edk2.GetAbsolutePathOnThisSystemFromEdk2RelativePath( + thebuilder.env.GetValue("FLASH_DEFINITION")) + + if ActiveFdf is None: + logging.info("No FDF found - PE Image Validation skipped") + return 0 + + # parse the DSC and the FDF + dsc_parser.SetBaseAbsPath(ws).SetPackagePaths(pp) + dsc_parser.SetInputVars(thebuilder.env.GetAllBuildKeyValues()).ParseFile( + ActiveDsc) # parse the DSC for build vars + fdf_parser.SetBaseAbsPath(ws).SetPackagePaths(pp) + fdf_parser.SetInputVars(dsc_parser.LocalVars).ParseFile( + ActiveFdf) # give FDF parser the vars from DSC + + # Test all pre-compiled efis described in the fdf + result = Result.PASS + for FV_name in fdf_parser.FVs: # Get all Firmware volumes + FV_files = fdf_parser.FVs[FV_name]["Files"] + for fv_file_name in FV_files: # Iterate over each file in the firmware volume + fv_file = FV_files[fv_file_name] + if "PE32" in fv_file: # Any PE32 section in the FV contains a path to the efi + # could have multiple PE32 sections + for efi_path in fv_file["PE32"]: + efi_path = self._resolve_vars(thebuilder, efi_path) + efi_path = edk2.GetAbsolutePathOnThisSystemFromEdk2RelativePath( + efi_path) + if efi_path == None: + logging.warn( + "Unable to parse the path to the pre-compiled efi") + continue + if os.path.basename(efi_path) in self.ignore_list: + continue + logging.info( + f'Performing Image Verification ... {os.path.basename(efi_path)}') + if self._validate_image(efi_path, fv_file["type"]) == Result.FAIL: + result = Result.FAIL + count += 1 + # End Pre-Compiled Image Verification + + # Start Build Time Compiled Image Verification + result = Result.PASS + for arch in thebuilder.env.GetValue("TARGET_ARCH").split(): + efi_path_list = self._walk_directory_for_extension( + ['.efi'], f'{thebuilder.env.GetValue("BUILD_OUTPUT_BASE")}/{arch}') + + for efi_path in efi_path_list: + if os.path.basename(efi_path) in self.ignore_list: + continue + + # Perform Image Verification on any output efi's + # Grab profile from makefile + if efi_path.__contains__("OUTPUT"): + try: + if tool_chain_tag.__contains__("VS"): + profile = self._get_profile_from_makefile( + f'{Path(efi_path).parent.parent}/Makefile') + + elif tool_chain_tag.__contains__("GCC"): + profile = self._get_profile_from_makefile( + f'{Path(efi_path).parent.parent}/GNUmakefile') + + elif tool_chain_tag.__contains__("CLANG"): + profile = self._get_profile_from_makefile( + f'{Path(efi_path).parent.parent}/GNUmakefile') + else: + logging.warn("Unexpected TOOL_CHAIN_TAG... Cannot parse makefile. Using DEFAULT profile.") + profile = "DEFAULT" + except: + logging.warn(f'Failed to parse makefile at [{Path(efi_path).parent.parent}/GNUmakefile]') + logging.warn(f'Using DEFAULT profile') + profile = "DEFAULT" + + logging.info( + f'Performing Image Verification ... {os.path.basename(efi_path)}') + if self._validate_image(efi_path, profile) == Result.FAIL: + result = Result.FAIL + count += 1 + # End Built Time Compiled Image Verification + + endtime = datetime.now() + delta = endtime - starttime + logging.info( + "---------------------------------------------------------") + logging.info( + "-----------Postbuild Image Validation Finished-----------") + logging.info( + "------------------{:04d} Images Verified-------------------".format(count)) + logging.info( + "-------------- Running Time (mm:ss): {0[0]:02}:{0[1]:02} --------------".format(divmod(delta.seconds, 60))) + logging.info( + "---------------------------------------------------------") + + if result == Result.FAIL: + return 1 + else: + return 0 + + # Executes run_tests() on the efi + def _validate_image(self, efi_path, profile="DEFAULT"): + pe = PE(efi_path) + + target_config = self.config_data[MACHINE_TYPE[pe.FILE_HEADER.Machine]].get( + profile) + if target_config == {}: # The target_config is present, but empty, therefore, override to default + profile = "DEFAULT" + + return self.test_manager.run_tests(pe, profile) + + # Reads the Makefile of an efi, if present, to determine profile + def _get_profile_from_makefile(self, makefile): + with open(makefile) as file: + for line in file.readlines(): + if line.__contains__('MODULE_TYPE'): + line = line.split('=') + module_type = line[1] + module_type = module_type.strip() + return module_type + return "DEFAULT" + + # Attempts to convert shorthand arch such as X64 to the + # Fully describe architecture. Additional support for + # Fallback architectures can be added here + def _try_convert_full_arch(self, arch): + full_arch = self.arch_dict.get(arch) + if full_arch == None: + if arch.__contains__("ARM"): + full_arch = "IMAGE_FILE_MACHINE_ARM" + # Add other Arches + return full_arch + + # Resolves variable names matching the $(...) pattern. + def _resolve_vars(self, thebuilder, s): + var_pattern = re.compile(r'\$\([^)]*\)') # Detect $(...) pattern + env = thebuilder.env + rs = s + for match in var_pattern.findall(s): + var_name = match[2:-1] + env_var = env.GetValue(var_name) if env.GetValue( + var_name) != None else env.GetBuildValue(var_name) + if env_var == None: + pass + rs = rs.replace(match, env_var) + return rs + + def _walk_directory_for_extension(self, extensionlist: List[str], directory: os.PathLike, + ignorelist: List[str] = None) -> List[os.PathLike]: + ''' Walks a file directory recursively for all items ending in certain extension + @extensionlist: List[str] list of file extensions + @directory: Path - absolute path to directory to start looking + @ignorelist: List[str] or None. optional - default is None: a list of case insensitive filenames to ignore + @returns a List of file paths to matching files + ''' + if not isinstance(extensionlist, list): + logging.critical("Expected list but got " + + str(type(extensionlist))) + raise TypeError("extensionlist must be a list") + + if directory is None: + logging.critical("No directory given") + raise TypeError("directory is None") + + if not os.path.isabs(directory): + logging.critical("Directory not abs path") + raise ValueError("directory is not an absolute path") + + if not os.path.isdir(directory): + logging.critical("Invalid find directory to walk") + raise ValueError("directory is not a valid directory path") + + if ignorelist is not None: + if not isinstance(ignorelist, list): + logging.critical("Expected list but got " + + str(type(ignorelist))) + raise TypeError("ignorelist must be a list") + + ignorelist_lower = list() + for item in ignorelist: + ignorelist_lower.append(item.lower()) + + extensionlist_lower = list() + for item in extensionlist: + extensionlist_lower.append(item.lower()) + + returnlist = list() + for Root, Dirs, Files in os.walk(directory): + for File in Files: + for Extension in extensionlist_lower: + if File.lower().endswith(Extension): + ignoreIt = False + if(ignorelist is not None): + for c in ignorelist_lower: + if(File.lower().startswith(c)): + ignoreIt = True + break + if not ignoreIt: + returnlist.append(os.path.join(Root, File)) + + return returnlist diff --git a/.pytool/Plugin/ImageValidation/ImageValidation_plug_in.yaml b/.pytool/Plugin/ImageValidation/ImageValidation_plug_in.yaml index 57af6446ec..ebda955072 100644 --- a/.pytool/Plugin/ImageValidation/ImageValidation_plug_in.yaml +++ b/.pytool/Plugin/ImageValidation/ImageValidation_plug_in.yaml @@ -1,11 +1,11 @@ -## @file -# Performs PE/COFF Image Validation Post Build -# -# Copyright (c) Microsoft Corporation. -# SPDX-License-Identifier: BSD-2-Clause-Patent -## -{ - "scope": "global", - "name": "PECOFF Image Validation Plugin", - "module": "ImageValidation" +## @file +# Performs PE/COFF Image Validation Post Build +# +# Copyright (c) Microsoft Corporation. +# SPDX-License-Identifier: BSD-2-Clause-Patent +## +{ + "scope": "global", + "name": "PECOFF Image Validation Plugin", + "module": "ImageValidation" } \ No newline at end of file diff --git a/BaseTools/Bin/basetoolsbin_ext_dep.yaml b/BaseTools/Bin/basetoolsbin_ext_dep.yaml index 80c6f78c7f..291479ecf2 100644 --- a/BaseTools/Bin/basetoolsbin_ext_dep.yaml +++ b/BaseTools/Bin/basetoolsbin_ext_dep.yaml @@ -1,18 +1,18 @@ -## -# Download the compiled basetools from nuget.org -# - Nuget package contains different binaries based on the host os -# Set this downloaded folder on path -# Set a Shell variable to this path -# -# Copyright (c) 2019, Microsoft Corporation -# SPDX-License-Identifier: BSD-2-Clause-Patent -## -{ - "scope": "global", - "type": "nuget", - "name": "Mu-Basetools", - "source": "https://pkgs.dev.azure.com/projectmu/mu/_packaging/Basetools-Binary/nuget/v3/index.json", - "version": "2022.08.1", - "flags": ["set_shell_var", "set_path", "host_specific"], - "var_name": "EDK_TOOLS_BIN" -} +## +# Download the compiled basetools from nuget.org +# - Nuget package contains different binaries based on the host os +# Set this downloaded folder on path +# Set a Shell variable to this path +# +# Copyright (c) 2019, Microsoft Corporation +# SPDX-License-Identifier: BSD-2-Clause-Patent +## +{ + "scope": "global", + "type": "nuget", + "name": "Mu-Basetools", + "source": "https://pkgs.dev.azure.com/projectmu/mu/_packaging/Basetools-Binary/nuget/v3/index.json", + "version": "2022.08.1", + "flags": ["set_shell_var", "set_path", "host_specific"], + "var_name": "EDK_TOOLS_BIN" +} diff --git a/BaseTools/NugetPublishing/Mu-Basetools.config.json b/BaseTools/NugetPublishing/Mu-Basetools.config.json index 22490342bb..0054993742 100644 --- a/BaseTools/NugetPublishing/Mu-Basetools.config.json +++ b/BaseTools/NugetPublishing/Mu-Basetools.config.json @@ -1,9 +1,9 @@ -{ - "name": "Mu-Basetools", - "author_string": "ProjectMu, TianoCore", - "server_url": "https://api.nuget.org/v3/index.json", - "project_url": "https://aka.ms/projectmu", - "license_url": "https://github.com/tianocore/edk2/blob/master/License.txt", - "description_string": "Edk2 Basetools compiled for Windows and Linux; packaged for Project Mu", - "copyright_string": "Copyright 2018 - 2019" +{ + "name": "Mu-Basetools", + "author_string": "ProjectMu, TianoCore", + "server_url": "https://api.nuget.org/v3/index.json", + "project_url": "https://aka.ms/projectmu", + "license_url": "https://github.com/tianocore/edk2/blob/master/License.txt", + "description_string": "Edk2 Basetools compiled for Windows and Linux; packaged for Project Mu", + "copyright_string": "Copyright 2018 - 2019" } \ No newline at end of file diff --git a/BaseTools/NugetPublishing/Mu-Nasm.config.json b/BaseTools/NugetPublishing/Mu-Nasm.config.json index 0a346263ef..3e2bcc847c 100644 --- a/BaseTools/NugetPublishing/Mu-Nasm.config.json +++ b/BaseTools/NugetPublishing/Mu-Nasm.config.json @@ -1,9 +1,9 @@ -{ - "name": "mu_nasm", - "author_string": "The NASM development team", - "server_url": "https://api.nuget.org/v3/index.json", - "project_url": "http://nasm.us/", - "license_url": "https://opensource.org/licenses/BSD-2-Clause", - "description_string": "NASM the netwide assembler packaged for Project Mu", - "copyright_string": "Copyright 2018" +{ + "name": "mu_nasm", + "author_string": "The NASM development team", + "server_url": "https://api.nuget.org/v3/index.json", + "project_url": "http://nasm.us/", + "license_url": "https://opensource.org/licenses/BSD-2-Clause", + "description_string": "NASM the netwide assembler packaged for Project Mu", + "copyright_string": "Copyright 2018" } \ No newline at end of file diff --git a/BaseTools/Plugin/BmpCheck/BmpCheckPlugin.py b/BaseTools/Plugin/BmpCheck/BmpCheckPlugin.py index 22413ffa00..d8aebc9679 100644 --- a/BaseTools/Plugin/BmpCheck/BmpCheckPlugin.py +++ b/BaseTools/Plugin/BmpCheck/BmpCheckPlugin.py @@ -1,170 +1,170 @@ -# @file BmpCheck.py -# Plugin to support checking BMP's included in the FDF for proper usage -# This makes symbol publishing easier and with the usage of -# ALT PDB PATH can shrink the size of each module. -# -## -# Copyright (c) Microsoft Corporation. All rights reserved. -# SPDX-License-Identifier: BSD-2-Clause-Patent -# -### - -import logging -import os -import time -try: - from edk2toollib.uefi.edk2.path_utilities import Edk2Path - from edk2toolext.environment.plugintypes.uefi_build_plugin import IUefiBuildPlugin - from edk2toollib.uefi.edk2.parsers.fdf_parser import FdfParser - from edk2toollib.uefi.edk2.parsers.dsc_parser import DscParser - from edk2toollib.uefi import bmp_object -except Exception: - pass - - -def timing(f): - def wrap(*args): - time1 = time.time() - ret = f(*args) - time2 = time.time() - logging.debug('{:s} function took {:.3f} ms'.format(f.__name__, (time2-time1)*1000.0)) - - return ret - return wrap - - -# the tests that we run on the BMP object -class UefiBmpSupportTests(object): - - def __init__(self, BmpObject, max_width=0, max_height=0): - self.Bmp = BmpObject - self.logger = logging.getLogger(__name__) - self.max_width = max_width - self.max_height = max_height - - def Test1(self): - self.logger.info("Test1: Pixel Data Size in file matches computed Size of Pixel data") - #test1 - DataSizePerLine = ((self.Bmp.PixelWidth * self.Bmp.BitPerPixel + 31) >> 3) & (~0x3) - DataSize2 = ((self.Bmp.PixelWidth * self.Bmp.BitPerPixel +31) / 32) * 4 - self.logger.debug("DataSize2 = {}".format(DataSize2)) - self.logger.debug(" DataSizePerLine: {}".format(DataSizePerLine)) - RawDataSize = self.Bmp.PixelHeight * DataSizePerLine - self.logger.debug(" RawDataSize: 0x%X" % RawDataSize) - ComputeSize = (self.Bmp.Size - self.Bmp.ImageOffset) - self.logger.debug(" File Calculated Data Size: 0x%X" % ComputeSize) - - if(ComputeSize != RawDataSize): - self.logger.error(" BMP Test1 - Fail") - return 1 - else: - self.logger.info(" BMP Test1 - Pass") - return 0 - - def Test2(self): - self.logger.info(" BMP Test2: File Header and Img Header as expected") - #test2 - if self.Bmp.CharB != b'B' and self.Bmp.CharB != b'B': - self.logger.error("Logo check - B header failed {}".format(self.Bmp.CharB)) - return 1 - if self.Bmp.CharM != b'M' and self.Bmp.CharM != 'M': - self.logger.error("Logo check - M header failed {}".format(self.Bmp.CharM)) - return 1 - - self.logger.info(" Test2 - Pass") - return 0 - - def Test3(self): - if self.max_width > 0 and BmpObj.PixelWidth > self.max_width: - self.logger.critical("Image {} is too wide".format(BmpFilePath)) - return 1 - if self.max_height > 0 and BmpObj.PixelHeight > self.max_height: - self.logger.critical("Image {} is too height".format(BmpFilePath)) - return 1 - return 0 - - - -class BmpCheckPlugin(IUefiBuildPlugin): - - def __init__(self): - self.logger = logging.getLogger(__name__) - - @staticmethod - def CheckBmp(BmpFilePath, max_width=0, max_height=0): - if not os.path.isfile(BmpFilePath): - return 1 - bmp = open(BmpFilePath, "rb") - BmpObj = bmp_object.BmpObject(bmp) - bmp.close() - #run tests - Tests = UefiBmpSupportTests(BmpObj) - ret = Tests.Test1() - ret += Tests.Test2() - ret += Tests.Test3() - return ret - - @timing - def do_pre_build(self, thebuilder): - try: - error_count = 0 - ''' - # this scans the whole build directory for bmp's - bmp_search_path = os.path.join(thebuilder.ws,"**","*.bmp"); - for found_item in glob.iglob(bmp_search_path, recursive=True): - if CheckBmp(found_item): - logging.error("{} failed image check".format(found_item)) - error_count += 1 - return error_count - ''' - - fp = FdfParser() - dp = DscParser() - - ws = thebuilder.ws - pp = thebuilder.pp.split(";") - edk2 = Edk2Path(ws, pp) - - ActiveDsc = edk2.GetAbsolutePathOnThisSystemFromEdk2RelativePath( - thebuilder.env.GetValue("ACTIVE_PLATFORM")) - ActiveFdf = edk2.GetAbsolutePathOnThisSystemFromEdk2RelativePath( - thebuilder.env.GetValue("FLASH_DEFINITION")) - - if ActiveFdf is None: - self.logger.info("No FDF found- BMP check skipped") - return 0 - # parse the DSC and the FDF - dp.SetBaseAbsPath(ws).SetPackagePaths(pp) - dp.SetInputVars(thebuilder.env.GetAllBuildKeyValues()).ParseFile(ActiveDsc) # parse the DSC for build vars - fp.SetBaseAbsPath(ws).SetPackagePaths(pp) - fp.SetInputVars(dp.LocalVars).ParseFile(ActiveFdf) # give FDF parser the vars from DSC - - # for each FV section in the DSC - for FV_name in fp.FVs: - FV_files = fp.FVs[FV_name]["Files"] - # now look for images in each file of this FV - for fv_file_name in FV_files: - fv_file = FV_files[fv_file_name] - if fv_file["type"].upper() != 'FREEFORM': - continue - fv_file_raw = fv_file['RAW'] - fv_file_raw_list = [] - if isinstance(fv_file_raw, list): - fv_file_raw_list = fv_file_raw - else: - fv_file_raw_list.append(fv_file_raw) - # for each file that is RAW type - for fv_file_raw_item in fv_file_raw_list: - # check if it ends with a bmp - if fv_file_raw_item.lower().endswith(".bmp"): - logging.debug(fv_file_raw_item) - BmpFilePath = edk2.GetAbsolutePathOnThisSystemFromEdk2RelativePath(fv_file_raw_item) - logging.debug(BmpFilePath) - if BmpCheckPlugin.CheckBmp(BmpFilePath): # do the check - self.logger.error("{} failed image check".format(fv_file_raw_item)) - error_count += 1 - return error_count - except: - self.logger.warning( - "Unable to read the FDF. Please update your Edk2-Pytools-* Packages") - return 0 +# @file BmpCheck.py +# Plugin to support checking BMP's included in the FDF for proper usage +# This makes symbol publishing easier and with the usage of +# ALT PDB PATH can shrink the size of each module. +# +## +# Copyright (c) Microsoft Corporation. All rights reserved. +# SPDX-License-Identifier: BSD-2-Clause-Patent +# +### + +import logging +import os +import time +try: + from edk2toollib.uefi.edk2.path_utilities import Edk2Path + from edk2toolext.environment.plugintypes.uefi_build_plugin import IUefiBuildPlugin + from edk2toollib.uefi.edk2.parsers.fdf_parser import FdfParser + from edk2toollib.uefi.edk2.parsers.dsc_parser import DscParser + from edk2toollib.uefi import bmp_object +except Exception: + pass + + +def timing(f): + def wrap(*args): + time1 = time.time() + ret = f(*args) + time2 = time.time() + logging.debug('{:s} function took {:.3f} ms'.format(f.__name__, (time2-time1)*1000.0)) + + return ret + return wrap + + +# the tests that we run on the BMP object +class UefiBmpSupportTests(object): + + def __init__(self, BmpObject, max_width=0, max_height=0): + self.Bmp = BmpObject + self.logger = logging.getLogger(__name__) + self.max_width = max_width + self.max_height = max_height + + def Test1(self): + self.logger.info("Test1: Pixel Data Size in file matches computed Size of Pixel data") + #test1 + DataSizePerLine = ((self.Bmp.PixelWidth * self.Bmp.BitPerPixel + 31) >> 3) & (~0x3) + DataSize2 = ((self.Bmp.PixelWidth * self.Bmp.BitPerPixel +31) / 32) * 4 + self.logger.debug("DataSize2 = {}".format(DataSize2)) + self.logger.debug(" DataSizePerLine: {}".format(DataSizePerLine)) + RawDataSize = self.Bmp.PixelHeight * DataSizePerLine + self.logger.debug(" RawDataSize: 0x%X" % RawDataSize) + ComputeSize = (self.Bmp.Size - self.Bmp.ImageOffset) + self.logger.debug(" File Calculated Data Size: 0x%X" % ComputeSize) + + if(ComputeSize != RawDataSize): + self.logger.error(" BMP Test1 - Fail") + return 1 + else: + self.logger.info(" BMP Test1 - Pass") + return 0 + + def Test2(self): + self.logger.info(" BMP Test2: File Header and Img Header as expected") + #test2 + if self.Bmp.CharB != b'B' and self.Bmp.CharB != b'B': + self.logger.error("Logo check - B header failed {}".format(self.Bmp.CharB)) + return 1 + if self.Bmp.CharM != b'M' and self.Bmp.CharM != 'M': + self.logger.error("Logo check - M header failed {}".format(self.Bmp.CharM)) + return 1 + + self.logger.info(" Test2 - Pass") + return 0 + + def Test3(self): + if self.max_width > 0 and BmpObj.PixelWidth > self.max_width: + self.logger.critical("Image {} is too wide".format(BmpFilePath)) + return 1 + if self.max_height > 0 and BmpObj.PixelHeight > self.max_height: + self.logger.critical("Image {} is too height".format(BmpFilePath)) + return 1 + return 0 + + + +class BmpCheckPlugin(IUefiBuildPlugin): + + def __init__(self): + self.logger = logging.getLogger(__name__) + + @staticmethod + def CheckBmp(BmpFilePath, max_width=0, max_height=0): + if not os.path.isfile(BmpFilePath): + return 1 + bmp = open(BmpFilePath, "rb") + BmpObj = bmp_object.BmpObject(bmp) + bmp.close() + #run tests + Tests = UefiBmpSupportTests(BmpObj) + ret = Tests.Test1() + ret += Tests.Test2() + ret += Tests.Test3() + return ret + + @timing + def do_pre_build(self, thebuilder): + try: + error_count = 0 + ''' + # this scans the whole build directory for bmp's + bmp_search_path = os.path.join(thebuilder.ws,"**","*.bmp"); + for found_item in glob.iglob(bmp_search_path, recursive=True): + if CheckBmp(found_item): + logging.error("{} failed image check".format(found_item)) + error_count += 1 + return error_count + ''' + + fp = FdfParser() + dp = DscParser() + + ws = thebuilder.ws + pp = thebuilder.pp.split(";") + edk2 = Edk2Path(ws, pp) + + ActiveDsc = edk2.GetAbsolutePathOnThisSystemFromEdk2RelativePath( + thebuilder.env.GetValue("ACTIVE_PLATFORM")) + ActiveFdf = edk2.GetAbsolutePathOnThisSystemFromEdk2RelativePath( + thebuilder.env.GetValue("FLASH_DEFINITION")) + + if ActiveFdf is None: + self.logger.info("No FDF found- BMP check skipped") + return 0 + # parse the DSC and the FDF + dp.SetBaseAbsPath(ws).SetPackagePaths(pp) + dp.SetInputVars(thebuilder.env.GetAllBuildKeyValues()).ParseFile(ActiveDsc) # parse the DSC for build vars + fp.SetBaseAbsPath(ws).SetPackagePaths(pp) + fp.SetInputVars(dp.LocalVars).ParseFile(ActiveFdf) # give FDF parser the vars from DSC + + # for each FV section in the DSC + for FV_name in fp.FVs: + FV_files = fp.FVs[FV_name]["Files"] + # now look for images in each file of this FV + for fv_file_name in FV_files: + fv_file = FV_files[fv_file_name] + if fv_file["type"].upper() != 'FREEFORM': + continue + fv_file_raw = fv_file['RAW'] + fv_file_raw_list = [] + if isinstance(fv_file_raw, list): + fv_file_raw_list = fv_file_raw + else: + fv_file_raw_list.append(fv_file_raw) + # for each file that is RAW type + for fv_file_raw_item in fv_file_raw_list: + # check if it ends with a bmp + if fv_file_raw_item.lower().endswith(".bmp"): + logging.debug(fv_file_raw_item) + BmpFilePath = edk2.GetAbsolutePathOnThisSystemFromEdk2RelativePath(fv_file_raw_item) + logging.debug(BmpFilePath) + if BmpCheckPlugin.CheckBmp(BmpFilePath): # do the check + self.logger.error("{} failed image check".format(fv_file_raw_item)) + error_count += 1 + return error_count + except: + self.logger.warning( + "Unable to read the FDF. Please update your Edk2-Pytools-* Packages") + return 0 diff --git a/BaseTools/Plugin/ClangPdbToolChain/ClangPdbToolChain.py b/BaseTools/Plugin/ClangPdbToolChain/ClangPdbToolChain.py index 36571c45a7..fcc901c8f9 100644 --- a/BaseTools/Plugin/ClangPdbToolChain/ClangPdbToolChain.py +++ b/BaseTools/Plugin/ClangPdbToolChain/ClangPdbToolChain.py @@ -1,94 +1,94 @@ -# @file ClangPdbToolChain.py -# Plugin to configures paths for the ClangPdb tool chain -## -# This plugin works in conjuncture with the tools_def -# -# Copyright (c) Microsoft Corporation -# SPDX-License-Identifier: BSD-2-Clause-Patent -## -import os -import logging -from io import StringIO -from edk2toolext.environment.plugintypes.uefi_build_plugin import IUefiBuildPlugin -from edk2toolext.environment import shell_environment -from edk2toolext.environment import version_aggregator -from edk2toollib.utility_functions import GetHostInfo -from edk2toollib.utility_functions import RunCmd - - -class ClangPdbToolChain(IUefiBuildPlugin): - - def do_post_build(self, thebuilder): - return 0 - - def do_pre_build(self, thebuilder): - self.Logger = logging.getLogger("ClangPdbToolChain") - - ## - # CLANGPBD - # - Need to find the clang path. - # - Report path and version for logging - # - # if CLANG_BIN already set the plugin will confirm it exists and get the version of clang - # If not set it will look for clang on the path. If found it will configure for that. - # if still not found it will try the default install directory. - # finally an error will be reported if not found - ## - if thebuilder.env.GetValue("TOOL_CHAIN_TAG") == "CLANGPDB": - - HostInfo = GetHostInfo() - ClangBin_Default = "UNDEFINED" - clang_exe = "clang" - - if HostInfo.os == "Windows": - ClangBin_Default = "C:\\Program Files\\LLVM\\bin\\\\" #need to escape the last slash as it seems to be removed - clang_exe += ".exe" - elif HostInfo.os == "Linux": - ClangBin_Default = "/LLVM/bin/" #this isn't right - else: - pass - # no defaults set - - ClangBin = shell_environment.GetEnvironment().get_shell_var("CLANG_BIN") - if ClangBin is not None: - self.Logger.info("CLANG_BIN is already set.") - else: - # see if clang is on path. - for path_entry in os.getenv("PATH").split(os.pathsep): - path_entry = os.path.normpath(path_entry) - if os.path.isfile(os.path.join(path_entry, clang_exe)): - ClangBin = os.path.abspath(path_entry) + os.sep - break - if ClangBin is None: - # Didn't find it on path - try the install default. - ClangBin = ClangBin_Default - - shell_environment.GetEnvironment().set_shell_var("CLANG_BIN", ClangBin) - - version_aggregator.GetVersionAggregator().ReportVersion( - "CLANG BIN", ClangBin, version_aggregator.VersionTypes.INFO) - - # now confirm it exists - if not os.path.exists(shell_environment.GetEnvironment().get_shell_var("CLANG_BIN")): - self.Logger.error(f"Path for CLANGPDB toolchain is invalid. {ClangBin}") - return -2 - - version_aggregator.GetVersionAggregator().ReportVersion( - "CLANG Version", self._get_clang_version(ClangBin), version_aggregator.VersionTypes.TOOL) - - return 0 - - ## - ## Get the clang version to report - ## - ## clang --version - ## clang version 12.0.0 - ## - def _get_clang_version(self, clang_bin_path): - return_buffer = StringIO() - ret = RunCmd(os.path.join(clang_bin_path, "clang"), "--version", outstream=return_buffer) - if (ret != 0): - logging.warning("Failed to find version of clang") - return -1 - line = return_buffer.getvalue().splitlines()[0].strip() +# @file ClangPdbToolChain.py +# Plugin to configures paths for the ClangPdb tool chain +## +# This plugin works in conjuncture with the tools_def +# +# Copyright (c) Microsoft Corporation +# SPDX-License-Identifier: BSD-2-Clause-Patent +## +import os +import logging +from io import StringIO +from edk2toolext.environment.plugintypes.uefi_build_plugin import IUefiBuildPlugin +from edk2toolext.environment import shell_environment +from edk2toolext.environment import version_aggregator +from edk2toollib.utility_functions import GetHostInfo +from edk2toollib.utility_functions import RunCmd + + +class ClangPdbToolChain(IUefiBuildPlugin): + + def do_post_build(self, thebuilder): + return 0 + + def do_pre_build(self, thebuilder): + self.Logger = logging.getLogger("ClangPdbToolChain") + + ## + # CLANGPBD + # - Need to find the clang path. + # - Report path and version for logging + # + # if CLANG_BIN already set the plugin will confirm it exists and get the version of clang + # If not set it will look for clang on the path. If found it will configure for that. + # if still not found it will try the default install directory. + # finally an error will be reported if not found + ## + if thebuilder.env.GetValue("TOOL_CHAIN_TAG") == "CLANGPDB": + + HostInfo = GetHostInfo() + ClangBin_Default = "UNDEFINED" + clang_exe = "clang" + + if HostInfo.os == "Windows": + ClangBin_Default = "C:\\Program Files\\LLVM\\bin\\\\" #need to escape the last slash as it seems to be removed + clang_exe += ".exe" + elif HostInfo.os == "Linux": + ClangBin_Default = "/LLVM/bin/" #this isn't right + else: + pass + # no defaults set + + ClangBin = shell_environment.GetEnvironment().get_shell_var("CLANG_BIN") + if ClangBin is not None: + self.Logger.info("CLANG_BIN is already set.") + else: + # see if clang is on path. + for path_entry in os.getenv("PATH").split(os.pathsep): + path_entry = os.path.normpath(path_entry) + if os.path.isfile(os.path.join(path_entry, clang_exe)): + ClangBin = os.path.abspath(path_entry) + os.sep + break + if ClangBin is None: + # Didn't find it on path - try the install default. + ClangBin = ClangBin_Default + + shell_environment.GetEnvironment().set_shell_var("CLANG_BIN", ClangBin) + + version_aggregator.GetVersionAggregator().ReportVersion( + "CLANG BIN", ClangBin, version_aggregator.VersionTypes.INFO) + + # now confirm it exists + if not os.path.exists(shell_environment.GetEnvironment().get_shell_var("CLANG_BIN")): + self.Logger.error(f"Path for CLANGPDB toolchain is invalid. {ClangBin}") + return -2 + + version_aggregator.GetVersionAggregator().ReportVersion( + "CLANG Version", self._get_clang_version(ClangBin), version_aggregator.VersionTypes.TOOL) + + return 0 + + ## + ## Get the clang version to report + ## + ## clang --version + ## clang version 12.0.0 + ## + def _get_clang_version(self, clang_bin_path): + return_buffer = StringIO() + ret = RunCmd(os.path.join(clang_bin_path, "clang"), "--version", outstream=return_buffer) + if (ret != 0): + logging.warning("Failed to find version of clang") + return -1 + line = return_buffer.getvalue().splitlines()[0].strip() return line[14:].strip() \ No newline at end of file diff --git a/BaseTools/Plugin/ClangPdbToolChain/ClangPdbToolChain_plug_in.yaml b/BaseTools/Plugin/ClangPdbToolChain/ClangPdbToolChain_plug_in.yaml index 4eacac6d80..3daefa9a58 100644 --- a/BaseTools/Plugin/ClangPdbToolChain/ClangPdbToolChain_plug_in.yaml +++ b/BaseTools/Plugin/ClangPdbToolChain/ClangPdbToolChain_plug_in.yaml @@ -1,11 +1,11 @@ -## @file -# Build Plugin used to set the path to the Clang/LLVM PDB tools chain -# -# Copyright (c) Microsoft Corporation. -# SPDX-License-Identifier: BSD-2-Clause-Patent -## -{ - "scope": "global", - "name": "Clang Pdb Tool Chain Support", - "module": "ClangPdbToolChain" -} +## @file +# Build Plugin used to set the path to the Clang/LLVM PDB tools chain +# +# Copyright (c) Microsoft Corporation. +# SPDX-License-Identifier: BSD-2-Clause-Patent +## +{ + "scope": "global", + "name": "Clang Pdb Tool Chain Support", + "module": "ClangPdbToolChain" +} diff --git a/BaseTools/Plugin/Edk2ToolHelper/Edk2ToolHelper.py b/BaseTools/Plugin/Edk2ToolHelper/Edk2ToolHelper.py index 1145e79150..61fab328ba 100644 --- a/BaseTools/Plugin/Edk2ToolHelper/Edk2ToolHelper.py +++ b/BaseTools/Plugin/Edk2ToolHelper/Edk2ToolHelper.py @@ -1,166 +1,166 @@ -from edk2toolext.environment.plugintypes.uefi_helper_plugin import IUefiHelperPlugin -import logging -import os -import uuid -from edk2toollib.utility_functions import RunCmd -from edk2toollib.utility_functions import RunPythonScript -from edk2toollib.utility_functions import CatalogSignWithSignTool -import shutil -import datetime -from Common.Edk2.Capsule.FmpPayloadHeader import FmpPayloadHeaderClass -from Common.Uefi.Capsule.FmpCapsuleHeader import FmpCapsuleHeaderClass -from edk2toollib.windows.locate_tools import FindToolInWinSdk - - -class Edk2ToolHelper(IUefiHelperPlugin): - - def RegisterHelpers(self, obj): - fp = os.path.abspath(__file__) - obj.Register("PackageMsFmpHeader", Edk2ToolHelper.PackageMsFmpHeader, fp) - obj.Register("PackageFmpImageAuth", Edk2ToolHelper.PackageFmpImageAuth, fp) - obj.Register("PackageFmpCapsuleHeader", Edk2ToolHelper.PackageFmpCapsuleHeader, fp) - obj.Register("PackageCapsuleHeader", Edk2ToolHelper.PackageCapsuleHeader, fp) - - - ## - # Function to Create binary with MsFmp Header prepended with data supplied - # InputBin: Input binary to wrap with new header (file path) - # OutputBin: file path to write Output binary to - # VersionInt: integer parameter for the version - # LsvInt: Integer parameter for the lowest supported version - # DepList: (optional) list of dependences. Dep format is tuple (FmpGuidForDep, FmpIndex, IntFmpMinVersion, IntFlags ) - ### Dep format can change overtime. Flags can be added for new behavior. See the version and library implementing behavior. - ### V1 details. - ####Flag bit 0: dep MUST be in system if 1. Otherwise dep only applied if fmp found in system. - ####Flag bit 1: dep version MUST be exact match if 1. Otherwise dep must be equal or greater than version. - ## - @staticmethod - def PackageMsFmpHeader(InputBin, OutputBin, VersionInt, LsvInt, DepList = []): - # NOTE: Crash if deps are passed. Return a useful error. - # Currently not ported to the new tooling. - if len(DepList) > 0: - raise RuntimeError("PackageMsFmpHeader has not been ported to support dependencies yet!") - # Should not take a capsule whose Version <= LSV - if (VersionInt < LsvInt): - logging.error("Version number 0x%08x lower than Lowest supported version 0x%08x is not allowed!" % (VersionInt, LsvInt)) - return -1 - - #append depedency if supplied - # for dep in DepList: - # depGuid = dep[0] - # depIndex = int(dep[1]) - # depMinVer = hex(dep[2]) - # depFlag = hex(dep[3]) - # logging.debug("Adding a Dependency:\n\tFMP Guid: %s \nt\tFmp Descriptor Index: %d \n\tFmp DepVersion: %s \n\tFmp Flags: %s\n" % (depGuid, depIndex, depMinVer, depFlag)) - # params += " --dep " + depGuid + " " + str(depIndex) + " " + depMinVer + " " + depFlag - # raise Exception("GenMsPayloadHeader Failed with errorcode %d" % ret) - - # Attempt to write the payload to the file. - # This would normally - with open(InputBin, 'rb') as in_file: - payload_data = in_file.read() - - fmp_header = FmpPayloadHeaderClass() - fmp_header.FwVersion = VersionInt - fmp_header.LowestSupportedVersion = LsvInt - fmp_header.Payload = payload_data - - with open(OutputBin, 'wb') as out_file: - out_file.write(fmp_header.Encode()) - - return 0 - - ## - # Function to create binary wrapped with FmpImage Auth using input supplied - # InputBin: Input binary to wrap with new fmp image auth header (file path) - # OutputBin: file path to write final output binary to - # DevPfxFilePath: (optional) file path to dev pfx file to sign with. If not supplied production signing is assumed. - # - ## - @staticmethod - def PackageFmpImageAuth(InputBin, OutputBin, DevPfxFilePath = None, DevPfxPassword = None, DetachedSignatureFile = None, Eku = None): - logging.debug("CapsulePackage: Fmp Image Auth Header/Signing") - - #temp output dir is in the outputbin folder - ret = 0 - TempOutDir = os.path.join(os.path.dirname(os.path.abspath(OutputBin)), "_Temp_FmpImageAuth_" + str(datetime.datetime.now().time()).replace(":", "_")) - logging.debug("Temp Output dir for FmpImageAuth: %s" % TempOutDir) - os.mkdir(TempOutDir) - cmd = "GenFmpImageAuth.py" - params = "-o " + OutputBin - params = params + " -p " + InputBin + " -m 1" - params = params + " --debug" - params = params + " -l " + os.path.join(TempOutDir, "GenFmpImageAuth_Log.log") - if(DevPfxFilePath is not None): - logging.debug("FmpImageAuth is dev signed. Do entire process in 1 step locally.") - - #Find Signtool - SignToolPath = FindToolInWinSdk("signtool.exe") - if not os.path.exists(SignToolPath): - raise Exception("Can't find signtool on this machine.") - - params = params + " --SignTool \"" + SignToolPath + "\"" - - params = params + " --pfxfile " + DevPfxFilePath - if( DevPfxPassword is not None): - params += " --pfxpass " + DevPfxPassword - if (Eku is not None): - params += " --eku " + Eku - ret = RunPythonScript(cmd, params, workingdir=TempOutDir) - #delete the temp dir - shutil.rmtree(TempOutDir, ignore_errors=True) - else: - #production - logging.debug("FmpImageAuth is Production signed") - - if(DetachedSignatureFile is None): - logging.debug("FmpImageAuth Step1: Make ToBeSigned file for production") - params = params + " --production" - ret = RunPythonScript(cmd, params, workingdir=TempOutDir) - if(ret != 0): - raise Exception("GenFmpImageAuth Failed production signing: step 1. Errorcode %d" % ret) - #now we have a file to sign at - TBS = os.path.join(os.path.dirname(OutputBin), "payload.Temp.ToBeSigned") - if(not os.path.exists(TBS)): - raise Exception("GenFmpImageAuth didn't create ToBeSigned file") - os.rename(TBS, OutputBin) - - else: - logging.debug("FmpImageAuth Step3: Final Packaging of production signed") - params = params + " --production -s " + DetachedSignatureFile - ret = RunPythonScript(cmd, params, workingdir=TempOutDir) - #delete the temp dir - shutil.rmtree(TempOutDir, ignore_errors=True) - - if(ret != 0): - raise Exception("GenFmpImageAuth Failed with errorcode %d" % ret) - return ret - - @staticmethod - def PackageFmpCapsuleHeader(InputBin, OutputBin, FmpGuid): - with open(InputBin, 'rb') as in_file: - capsule_data = in_file.read() - - fmp_capsule = FmpCapsuleHeaderClass() - fmp_capsule.AddPayload(uuid.UUID(FmpGuid), capsule_data) - - with open(OutputBin, 'wb') as out_file: - out_file.write(fmp_capsule.Encode()) - - return 0 - - @staticmethod - def PackageCapsuleHeader(InputBin, OutputBin, FmpDeviceGuid=None): - logging.debug("CapsulePackage: Final Capsule Header") - if(FmpDeviceGuid == None): - logging.debug("CapsulePackage: Using default industry standard FMP guid") - FmpDeviceGuid = "6dcbd5ed-e82d-4c44-bda1-7194199ad92a" - - params = "-o " + OutputBin - params = params + " -g " + FmpDeviceGuid - params = params + " --capsule -v -f " + InputBin - params = params + " --capFlag PersistAcrossReset --capFlag InitiateReset" - ret = RunCmd("genfv", params) - if(ret != 0): - raise Exception("GenFv Failed with errorcode" % ret) - return ret +from edk2toolext.environment.plugintypes.uefi_helper_plugin import IUefiHelperPlugin +import logging +import os +import uuid +from edk2toollib.utility_functions import RunCmd +from edk2toollib.utility_functions import RunPythonScript +from edk2toollib.utility_functions import CatalogSignWithSignTool +import shutil +import datetime +from Common.Edk2.Capsule.FmpPayloadHeader import FmpPayloadHeaderClass +from Common.Uefi.Capsule.FmpCapsuleHeader import FmpCapsuleHeaderClass +from edk2toollib.windows.locate_tools import FindToolInWinSdk + + +class Edk2ToolHelper(IUefiHelperPlugin): + + def RegisterHelpers(self, obj): + fp = os.path.abspath(__file__) + obj.Register("PackageMsFmpHeader", Edk2ToolHelper.PackageMsFmpHeader, fp) + obj.Register("PackageFmpImageAuth", Edk2ToolHelper.PackageFmpImageAuth, fp) + obj.Register("PackageFmpCapsuleHeader", Edk2ToolHelper.PackageFmpCapsuleHeader, fp) + obj.Register("PackageCapsuleHeader", Edk2ToolHelper.PackageCapsuleHeader, fp) + + + ## + # Function to Create binary with MsFmp Header prepended with data supplied + # InputBin: Input binary to wrap with new header (file path) + # OutputBin: file path to write Output binary to + # VersionInt: integer parameter for the version + # LsvInt: Integer parameter for the lowest supported version + # DepList: (optional) list of dependences. Dep format is tuple (FmpGuidForDep, FmpIndex, IntFmpMinVersion, IntFlags ) + ### Dep format can change overtime. Flags can be added for new behavior. See the version and library implementing behavior. + ### V1 details. + ####Flag bit 0: dep MUST be in system if 1. Otherwise dep only applied if fmp found in system. + ####Flag bit 1: dep version MUST be exact match if 1. Otherwise dep must be equal or greater than version. + ## + @staticmethod + def PackageMsFmpHeader(InputBin, OutputBin, VersionInt, LsvInt, DepList = []): + # NOTE: Crash if deps are passed. Return a useful error. + # Currently not ported to the new tooling. + if len(DepList) > 0: + raise RuntimeError("PackageMsFmpHeader has not been ported to support dependencies yet!") + # Should not take a capsule whose Version <= LSV + if (VersionInt < LsvInt): + logging.error("Version number 0x%08x lower than Lowest supported version 0x%08x is not allowed!" % (VersionInt, LsvInt)) + return -1 + + #append depedency if supplied + # for dep in DepList: + # depGuid = dep[0] + # depIndex = int(dep[1]) + # depMinVer = hex(dep[2]) + # depFlag = hex(dep[3]) + # logging.debug("Adding a Dependency:\n\tFMP Guid: %s \nt\tFmp Descriptor Index: %d \n\tFmp DepVersion: %s \n\tFmp Flags: %s\n" % (depGuid, depIndex, depMinVer, depFlag)) + # params += " --dep " + depGuid + " " + str(depIndex) + " " + depMinVer + " " + depFlag + # raise Exception("GenMsPayloadHeader Failed with errorcode %d" % ret) + + # Attempt to write the payload to the file. + # This would normally + with open(InputBin, 'rb') as in_file: + payload_data = in_file.read() + + fmp_header = FmpPayloadHeaderClass() + fmp_header.FwVersion = VersionInt + fmp_header.LowestSupportedVersion = LsvInt + fmp_header.Payload = payload_data + + with open(OutputBin, 'wb') as out_file: + out_file.write(fmp_header.Encode()) + + return 0 + + ## + # Function to create binary wrapped with FmpImage Auth using input supplied + # InputBin: Input binary to wrap with new fmp image auth header (file path) + # OutputBin: file path to write final output binary to + # DevPfxFilePath: (optional) file path to dev pfx file to sign with. If not supplied production signing is assumed. + # + ## + @staticmethod + def PackageFmpImageAuth(InputBin, OutputBin, DevPfxFilePath = None, DevPfxPassword = None, DetachedSignatureFile = None, Eku = None): + logging.debug("CapsulePackage: Fmp Image Auth Header/Signing") + + #temp output dir is in the outputbin folder + ret = 0 + TempOutDir = os.path.join(os.path.dirname(os.path.abspath(OutputBin)), "_Temp_FmpImageAuth_" + str(datetime.datetime.now().time()).replace(":", "_")) + logging.debug("Temp Output dir for FmpImageAuth: %s" % TempOutDir) + os.mkdir(TempOutDir) + cmd = "GenFmpImageAuth.py" + params = "-o " + OutputBin + params = params + " -p " + InputBin + " -m 1" + params = params + " --debug" + params = params + " -l " + os.path.join(TempOutDir, "GenFmpImageAuth_Log.log") + if(DevPfxFilePath is not None): + logging.debug("FmpImageAuth is dev signed. Do entire process in 1 step locally.") + + #Find Signtool + SignToolPath = FindToolInWinSdk("signtool.exe") + if not os.path.exists(SignToolPath): + raise Exception("Can't find signtool on this machine.") + + params = params + " --SignTool \"" + SignToolPath + "\"" + + params = params + " --pfxfile " + DevPfxFilePath + if( DevPfxPassword is not None): + params += " --pfxpass " + DevPfxPassword + if (Eku is not None): + params += " --eku " + Eku + ret = RunPythonScript(cmd, params, workingdir=TempOutDir) + #delete the temp dir + shutil.rmtree(TempOutDir, ignore_errors=True) + else: + #production + logging.debug("FmpImageAuth is Production signed") + + if(DetachedSignatureFile is None): + logging.debug("FmpImageAuth Step1: Make ToBeSigned file for production") + params = params + " --production" + ret = RunPythonScript(cmd, params, workingdir=TempOutDir) + if(ret != 0): + raise Exception("GenFmpImageAuth Failed production signing: step 1. Errorcode %d" % ret) + #now we have a file to sign at + TBS = os.path.join(os.path.dirname(OutputBin), "payload.Temp.ToBeSigned") + if(not os.path.exists(TBS)): + raise Exception("GenFmpImageAuth didn't create ToBeSigned file") + os.rename(TBS, OutputBin) + + else: + logging.debug("FmpImageAuth Step3: Final Packaging of production signed") + params = params + " --production -s " + DetachedSignatureFile + ret = RunPythonScript(cmd, params, workingdir=TempOutDir) + #delete the temp dir + shutil.rmtree(TempOutDir, ignore_errors=True) + + if(ret != 0): + raise Exception("GenFmpImageAuth Failed with errorcode %d" % ret) + return ret + + @staticmethod + def PackageFmpCapsuleHeader(InputBin, OutputBin, FmpGuid): + with open(InputBin, 'rb') as in_file: + capsule_data = in_file.read() + + fmp_capsule = FmpCapsuleHeaderClass() + fmp_capsule.AddPayload(uuid.UUID(FmpGuid), capsule_data) + + with open(OutputBin, 'wb') as out_file: + out_file.write(fmp_capsule.Encode()) + + return 0 + + @staticmethod + def PackageCapsuleHeader(InputBin, OutputBin, FmpDeviceGuid=None): + logging.debug("CapsulePackage: Final Capsule Header") + if(FmpDeviceGuid == None): + logging.debug("CapsulePackage: Using default industry standard FMP guid") + FmpDeviceGuid = "6dcbd5ed-e82d-4c44-bda1-7194199ad92a" + + params = "-o " + OutputBin + params = params + " -g " + FmpDeviceGuid + params = params + " --capsule -v -f " + InputBin + params = params + " --capFlag PersistAcrossReset --capFlag InitiateReset" + ret = RunCmd("genfv", params) + if(ret != 0): + raise Exception("GenFv Failed with errorcode" % ret) + return ret diff --git a/BaseTools/Plugin/FdSizeReport/FdSizeReportGenerator.py b/BaseTools/Plugin/FdSizeReport/FdSizeReportGenerator.py index be8fc9c917..42e2a6c0d9 100644 --- a/BaseTools/Plugin/FdSizeReport/FdSizeReportGenerator.py +++ b/BaseTools/Plugin/FdSizeReport/FdSizeReportGenerator.py @@ -1,525 +1,525 @@ -## -# Tool to generate a report on Flash Usage and Module sizes for a UEFI build. -# This tool depends on EDK2 and will parse UEFI build reports, fdf files, and other -# standard EDK2 assets -# -# Copyright (c) Microsoft Corporation. All rights reserved. -# SPDX-License-Identifier: BSD-2-Clause-Patent -## - - -import os -import sys -import re -import logging -import datetime -from decimal import Decimal - -# -# for now i want to keep this file as both a command line tool and a plugin for the Uefi Build system. -# To do this the plugin class is only defined if in the build environment where the plugin classes are importable. -# -# -try: - from edk2toolext.environment.plugintypes.uefi_build_plugin import IUefiBuildPlugin - - class FdSizeReportGenerator(IUefiBuildPlugin): - - def do_post_build(self, thebuilder): - - #not an error...just means don't use it - if(thebuilder.env.GetValue("BUILDREPORTING") != "TRUE"): - logging.debug("FdSize Report Generator Post Build Not Active due to BuildReporting Turned Off") - return 0 - - #Not an error just means a builder wants build reports but is building a product without - # an FDF file - elif(thebuilder.env.GetValue("FLASH_DEFINITION") is None): - logging.debug("FdSize Report Generator Post Build Not Active due to FDF file not being defined") - return 0 - - #Error - User has build reporting on but hasn't defined the build report output file - elif(thebuilder.env.GetValue("BUILDREPORT_FILE") is None): - logging.error("FdSize Report Generator Post Build failed because Build Report file not defined") - return -1 - - - - # - User has build reporting on but hasn't defined - if(thebuilder.env.GetValue("FDSIZEREPORT_FILE") is None): - logging.debug("FdSize Report Generator Post Build - Fd Size Report file not defined in build system. Setting to plugin default.") - thebuilder.env.SetValue("FDSIZEREPORT_FILE", os.path.join(thebuilder.env.GetValue("BUILD_OUTPUT_BASE"), "FD_REPORT.HTML"), "Value defined by plugin") - - #1 - Get the output path for report file - OutF = thebuilder.env.GetValue("FDSIZEREPORT_FILE") - #2 - Get the FDF path - FdfF = thebuilder.mws.join(thebuilder.ws, thebuilder.env.GetValue("FLASH_DEFINITION")) - #3 - Get the product name - Product = thebuilder.env.GetValue("PRODUCT_NAME") - if Product is None: - logging.debug("Environment variable PRODUCT_NAME is not set") - Product = "not set" - #4 - Get the Fw version - FwVersion = thebuilder.env.GetBuildValue("BUILDID_STRING") - if FwVersion is None: - logging.debug("Environment variable BUILDID_STRING is not set") - FwVersion = "not set" - #5 - Get the build Report file - BuildReportF = thebuilder.env.GetValue("BUILDREPORT_FILE") - - Report = FdReport() - - ret = Report.MakeReport(Product, FwVersion, OutF, FdfF, BuildReportF, thebuilder.ws, thebuilder.pp) - logging.debug("Build Report generation returned %d" % ret) - return ret - -except ImportError: - pass - - -## -# Support code/classes for parsing and creating report -## - - - -class FvModule(object): - - def __init__(self): - self.Path = '' - self.Name = '' - - -class FdRegion(object): - - def __init__(self): - self.Type = '' - self.Base = '' - self.Size = '' - self.Desc = 'Unknown' - self.Used = '' - self.Free = '' - self.SystemAddress = '0' - self.FvModuleList = [] - self.Nested = "False" - - def GetFreePercent(self): - try: - v = Decimal(int(self.Free, 0)) *100 / Decimal(int(self.Size, 0)) - return "%0.2f%%" % v - except: - return 'NA' - - def GetUsedPercent(self): - try: - v = Decimal(int(self.Used, 0)) *100 / Decimal(int(self.Size, 0)) - return "%0.2f%%" % v - except: - return "NA" - -class ModuleSummary(object): - - def __init__(self): - self.Name = '' - self.Size = 0 - self.SizeString = '' - self.Guid = '' - self.InfPath = '' - self.Type = '' - self.MapFilePath = '' - self.FvList = [] - -class FdfMiniParser(object): - - - def __init__(self, fdfFileLines): - self.FileLines = fdfFileLines - self.MaxLines = len(self.FileLines) - self.RE_RegionDescLine = re.compile('^ *#Region_Description:') - - - def GetRegionDescComment(self, BaseAddress): - current = 0 - while(current < self.MaxLines): - if self.RE_RegionDescLine.match(self.FileLines[current]): - al = self.FileLines[current+1] - if al.count("|") == 1 and al.count("x") == 2: - #found a good base address. Now compare - add = int(al.strip().partition('|')[0], 0) - if add == BaseAddress: - return self.FileLines[current].partition(":")[2].strip() - current = current + 1 - return "" - - -class FlashReportParser(object): - - def __init__(self, ReportFileLines, FdfFileLines = None, ToolVersion="1.00", ProductName="Unset", ProductVersion="Unset"): - self.ReportFile = ReportFileLines - self.Parsed = False - self.FdRegions = [] - self.Modules = [] - self.TotalLines = len(ReportFileLines) - - self.FdBase = '' - self.FdName = '' - self.FdSize = '' - self.FdSizeNum = 0 - self.FdBaseNum = 0 - self.FdfMiniParser = None - self.ToolVersion = ToolVersion - self.ProductVersion = ProductVersion - self.ProductName = ProductName - - if FdfFileLines != None and len(FdfFileLines) > 0: - self.FdfMiniParser = FdfMiniParser(FdfFileLines) - - def ParseFdInfo(self): - CurrentLine = 0 - FoundAll = False - FoundIt = False - while(CurrentLine < self.TotalLines) and not FoundAll: - line = self.ReportFile[CurrentLine] - - if FoundIt: - tokens = line.strip().split(':') - if len(tokens) == 2: - if(tokens[0].strip().lower() == "fd name"): - self.FdName = tokens[1] - elif(tokens[0].strip().lower() == 'base address'): - self.FdBase=tokens[1] - self.FdBaseNum = int(self.FdBase, 0) - elif(tokens[0].strip().lower() == 'size'): - self.FdSize = tokens[1].split()[0].strip() - self.FdSizeNum = int(self.FdSize, 0) - FoundAll = True - elif line.strip().lower() == 'firmware device (fd)': - FoundIt = True - - CurrentLine = CurrentLine + 1 - - def ParseAllModules(self): - InModSummary = False - CurrentMod = 0 - CurrentLine = 0 - while(CurrentLine < self.TotalLines): - line = self.ReportFile[CurrentLine] - - #look for module summary section region - if line.strip().lower() == 'module summary': - #new summary - InModSummary = True - mod = ModuleSummary() - self.Modules.append(mod) - CurrentMod = len(self.Modules) - 1 - - #parse within mod summary - elif InModSummary: - tokens = line.strip().split() - if len(tokens) > 0: - if tokens[0].strip() == 'Module': - if tokens[1].strip() == 'Name:': - (self.Modules[CurrentMod]).Name = tokens[2].strip() - elif tokens[1].strip() == 'INF': - self.Modules[CurrentMod].InfPath = tokens[3].strip().replace("\\", "/") - if(not tokens[3].strip().lower().endswith(".inf")): - #get next line - CurrentLine += 1 - line = self.ReportFile[CurrentLine] - self.Modules[CurrentMod].InfPath += line.strip().replace("\\", "/") - - elif (tokens[0].strip() == 'File'): - if(tokens[1].strip() == 'GUID:'): - (self.Modules[CurrentMod]).Guid = tokens[2].strip() - - elif (tokens[0].strip() == 'Size:'): - (self.Modules[CurrentMod]).SizeString = tokens[1].strip() - (self.Modules[CurrentMod]).Size = int(tokens[1].strip(), 0) - - elif (tokens[0].strip() == 'Driver'): - (self.Modules[CurrentMod]).Type = tokens[3].strip() - - elif tokens[0].strip() == '========================================================================================================================': - InModSummary = False - - #increment the currentline - CurrentLine = CurrentLine + 1 - #done processing report file. - #sort list descending - self.Modules.sort(key=lambda x: x.Size, reverse=True) - - - - def ParseFdRegions(self): - InFdRegion = False - CurrentRegion = 0 - CurrentLine = 0 - while(CurrentLine < self.TotalLines): - line = self.ReportFile[CurrentLine] - - #look for fd region - if line.strip().lower() == 'fd region': - #new fd region - InFdRegion = True - Region = FdRegion() - self.FdRegions.append(Region) - CurrentRegion = len(self.FdRegions) - 1 - - elif line.strip().lower() == "nested fv": - #nested fv region. just track the module info - Region = FdRegion() - Region.Nested = "True" - InFdRegion = True - self.FdRegions.append(Region) - CurrentRegion = len(self.FdRegions) -1 - - - #parse within fd region - elif InFdRegion: - tokens = line.strip().split() - if len(tokens) > 0: - if tokens[0].strip() == 'Type:': - (self.FdRegions[CurrentRegion]).Type = tokens[1] - (self.FdRegions[CurrentRegion]).Desc = (self.FdRegions[CurrentRegion]).Type - elif tokens[0].strip() == 'Base': - (self.FdRegions[CurrentRegion]).Base = tokens[2] - bv = int(tokens[2], 0) - (self.FdRegions[CurrentRegion]).SystemAddress = str("0x%X" % (self.FdBaseNum + bv)) - elif tokens[0].strip() == 'Size:': - (self.FdRegions[CurrentRegion]).Size = tokens[1] - elif tokens[0].strip() == 'Occupied': - (self.FdRegions[CurrentRegion]).Used = tokens[2] - elif tokens[0].strip() == 'Free': - (self.FdRegions[CurrentRegion]).Free = tokens[2] - elif (tokens[0].strip() == 'Fv'): - if(tokens[1].strip() == 'Name:'): - if len((self.FdRegions[CurrentRegion]).Desc) > len((self.FdRegions[CurrentRegion]).Type): - (self.FdRegions[CurrentRegion]).Desc = (self.FdRegions[CurrentRegion]).Desc + " --> FV: " + tokens[2] - else: - (self.FdRegions[CurrentRegion]).Desc = "FV: " + tokens[2] - - elif (tokens[0].strip() == 'Capsule'): - if (tokens[1].strip() == "Name:"): - (self.FdRegions[CurrentRegion]).Desc = "Capsule: " + tokens[2] - elif (tokens[1].strip() == 'Size:'): - (self.FdRegions[CurrentRegion]).Used = tokens[2] - filed = int((self.FdRegions[CurrentRegion]).Used, 0) - total = int((self.FdRegions[CurrentRegion]).Size, 0) - free = total - filed - (self.FdRegions[CurrentRegion]).Free = str("0x%X" % free) - - elif (tokens[0].strip() == 'File'): - if (tokens[1].strip() == "Name:"): - (self.FdRegions[CurrentRegion]).Desc = "File: " + tokens[2] - elif (tokens[1].strip() == 'Size:'): - (self.FdRegions[CurrentRegion]).Used = tokens[2] - filed = int((self.FdRegions[CurrentRegion]).Used, 0) - total = int((self.FdRegions[CurrentRegion]).Size, 0) - free = total - filed - (self.FdRegions[CurrentRegion]).Free = str("0x%X" % free) - - - elif tokens[0].strip() == '<---------------------------------------------------------------------------------------------------------------------->': - InFdRegion = False - if (self.FdfMiniParser != None): - #try to get comment for region - desc = self.FdfMiniParser.GetRegionDescComment(int((self.FdRegions[CurrentRegion]).Base, 0)) - if len (desc) > 0: - (self.FdRegions[CurrentRegion]).Desc = (self.FdRegions[CurrentRegion]).Desc + " - " + desc - elif len(tokens) == 3 and tokens[0].lower().startswith("0x"): - #This is the module section - mo = FvModule() - mo.Name = tokens[1] - mo.Path = tokens[2] - if(mo.Path.startswith('(') and not mo.Path.endswith(')')): - #build report line wrapped around. Go get next line - CurrentLine += 1 - mo.Path = mo.Path.strip() + self.ReportFile[CurrentLine].strip() - mo.Path = mo.Path.rstrip(')').lstrip('(') - self.FdRegions[CurrentRegion].FvModuleList.append(mo) - - #increment the currentline - CurrentLine = CurrentLine + 1 - - # - #loop thru all the mods and all the fv regions trying to match up - # - def UpdateModsWithFvs(self, ws): - #go thru each Module Summary - for ms in self.Modules: - logging.debug("Looking for FVs for Mod named %s path: %s" % (ms.Name, ms.InfPath)) - #loop thru all modules in all FVs to find all matches - for fv in self.FdRegions: - for modinfv in fv.FvModuleList: - #to much output logging.debug("Comparing against mod %s" % modinfv.Name) - if(ms.Name.lower() == modinfv.Name.lower()): - #possible match - logging.debug("Name Match. P1 %s p2 %s" % (ms.InfPath.lower().replace("/", "\\"), modinfv.Path.lower().replace("/", "\\"))) - #if(os.path.join(ws, ms.InfPath).lower().replace("/", "\\") == modinfv.Path.lower().replace("/", "\\") ): - if((modinfv.Path.lower().replace("/", "\\")).endswith(ms.InfPath.lower().replace("/", "\\")) ): - #good match - logging.debug("Match found for ModInFV. Mod %s is in FV %s" % (ms.InfPath, fv.Desc)) - if(fv.Desc not in ms.FvList): - ms.FvList.append(fv.Desc) - break #break out of this FV - - - - def JS(self, key, value, comma=True): - r = '"' + key.strip() + '": "' + value.strip() + '"' - if comma: - r = r + "," - return r - - def JSRegion(self, region): - return "{" + self.JS("nested", region.Nested) + self.JS("description", region.Desc) + self.JS("systemAddress", region.SystemAddress) + self.JS("baseAddress", region.Base) + self.JS("size", region.Size) + self.JS("used", region.Used) + self.JS("usedPercentage", region.GetUsedPercent()) + self.JS("free", region.Free) + self.JS("freePercentage", region.GetFreePercent(), False) + "}," - - def JSModule(self, mod): - fvlistjson = '"FV":[' - for f in mod.FvList: - fvlistjson += "'" + f + "'," - fvlistjson = fvlistjson.rstrip(',') + ']' - - return "{" + self.JS("name", mod.Name) + self.JS("path", mod.InfPath) + self.JS("guid", mod.Guid) + self.JS("size", str(mod.Size)) + self.JS("sizeString", mod.SizeString) + self.JS("type", mod.Type) + fvlistjson + "}," - - def ToJsonString(self): - js = "{" + self.JS("FdSizeReportGeneratorVersion", self.ToolVersion) + self.JS("ProductName", self.ProductName) - js += self.JS("ProductVersion", self.ProductVersion) + self.JS("DateCollected", datetime.datetime.strftime(datetime.datetime.now(), "%A, %B %d, %Y %I:%M%p" )) - js += self.JS("fdName", self.FdName) + self.JS("fdBase", self.FdBase) + self.JS("fdSize", self.FdSize) + '"fdRegions": [' - for fdr in self.FdRegions: - js = js + self.JSRegion(fdr) - - js = js.rstrip(",") - js = js + '], "modules": [' - - for mod in self.Modules: - js = js + self.JSModule(mod) - js = js.rstrip(",") - js = js + "]}" - return js - - -class FdReport(object): - MY_FOLDER = os.path.dirname(os.path.realpath(__file__)) - VERSION = "2.02" - - def __init__(self): - pass - - def MakeReport(self, ProductName, ProductVersion, OutputReport, InputFdf, InputBuildReport, Workspace, PackagesPathList=[]): - - if not os.path.isfile(InputFdf): - logging.critical("Invalid path to input FDF file") - return -2 - - if not os.path.isfile(InputBuildReport): - logging.critical("Invalid path to input Build Report file") - return -1 - - if not os.path.isdir(Workspace): - logging.critical("Invalid path to workspace dir") - return -3 - - - f = open(InputBuildReport, "r") - lines = f.readlines() - f.close() - - f = open(InputFdf, "r") - fdfLines = f.readlines() - f.close() - - rep = FlashReportParser(lines, fdfLines, FdReport.VERSION, ProductName, ProductVersion) - rep.ParseFdInfo() - rep.ParseFdRegions() - rep.ParseAllModules() - rep.UpdateModsWithFvs(Workspace) - - - f = open(OutputReport, "w") - template = open(os.path.join(FdReport.MY_FOLDER, "FdReport_Template.html"), "r") - for line in template.readlines(): - if "%TO_BE_FILLED_IN_BY_PYTHON_SCRIPT%" in line: - line = line.replace("%TO_BE_FILLED_IN_BY_PYTHON_SCRIPT%", rep.ToJsonString()) - f.write(line) - template.close() - f.close() - - return 0 - - -################################################ -# This plugin python file is also -# a command line tool -# -################################################ -if __name__ == '__main__': - from optparse import OptionParser - #setup main console as logger - logger = logging.getLogger('') - logger.setLevel(logging.DEBUG) - formatter = logging.Formatter("%(levelname)s - %(message)s") - console = logging.StreamHandler() - console.setLevel(logging.CRITICAL) - console.setFormatter(formatter) - logger.addHandler(console) - - #Do real work cmdline work here - parser = OptionParser() - #Output debug log - parser.add_option("-l", dest="OutputReport", help="Create an output log file: ie -l out.txt", default=None) - parser.add_option("-o", dest="OutputFile", help="Output file (Will be HTML file) : ie -o MyOutput.html", default=None) - parser.add_option("-i", dest="InputReport", help="Input Report File." , default=None) - parser.add_option("-f", dest="FdfFile", help="Input Fdf File used for additional information gathering (optional).", default=None) - parser.add_option("-w", dest="Workspace", help="Absolute path to workspace", default=None) - parser.add_option("--product", dest="ProductName", help="Name of product for report", default="Unknown") - parser.add_option("--fwVersion", dest="FirmwareVersion", help="Firmware Version", default="Unknown") - #Turn on dubug level logging - parser.add_option("--debug", action="store_true", dest="debug", help="turn on debug logging level for file log", default=False) - - (options, args) = parser.parse_args() - - #setup file based logging if outputReport specified - if(options.OutputReport): - if(len(options.OutputReport) < 2): - logging.critical("the output report file parameter is invalid") - sys.exit(-2) - else: - #setup file based logging - filelogger = logging.FileHandler(filename=options.OutputReport, mode='w') - if(options.debug): - filelogger.setLevel(logging.DEBUG) - else: - filelogger.setLevel(logging.INFO) - - filelogger.setFormatter(formatter) - logging.getLogger('').addHandler(filelogger) - - logging.info("Log Started: " + datetime.datetime.strftime(datetime.datetime.now(), "%A, %B %d, %Y %I:%M%p" )) - - #parse report and generate output - if not options.InputReport: - logging.critical("No Input report file") - sys.exit(-1) - - if not os.path.isfile(options.InputReport): - logging.critical("Invalid path to input report") - sys.exit(-2) - - if not options.OutputFile: - logging.critical("No Output file") - sys.exit(-3) - - if not options.Workspace: - logging.critical("No workspace specified") - sys.exit(-4) - - Report = FdReport() - ret = Report.MakeReport(options.ProductName, options.FirmwareVersion, options.OutputFile, options.FdfFile, options.InputReport, options.Workspace) - logging.debug("Build Report generation returned %d" % ret) - - if ret != 0: - logging.critical("Tool Failed. Return Code: %i" % ret) - #end logging - logging.shutdown() - sys.exit(ret) +## +# Tool to generate a report on Flash Usage and Module sizes for a UEFI build. +# This tool depends on EDK2 and will parse UEFI build reports, fdf files, and other +# standard EDK2 assets +# +# Copyright (c) Microsoft Corporation. All rights reserved. +# SPDX-License-Identifier: BSD-2-Clause-Patent +## + + +import os +import sys +import re +import logging +import datetime +from decimal import Decimal + +# +# for now i want to keep this file as both a command line tool and a plugin for the Uefi Build system. +# To do this the plugin class is only defined if in the build environment where the plugin classes are importable. +# +# +try: + from edk2toolext.environment.plugintypes.uefi_build_plugin import IUefiBuildPlugin + + class FdSizeReportGenerator(IUefiBuildPlugin): + + def do_post_build(self, thebuilder): + + #not an error...just means don't use it + if(thebuilder.env.GetValue("BUILDREPORTING") != "TRUE"): + logging.debug("FdSize Report Generator Post Build Not Active due to BuildReporting Turned Off") + return 0 + + #Not an error just means a builder wants build reports but is building a product without + # an FDF file + elif(thebuilder.env.GetValue("FLASH_DEFINITION") is None): + logging.debug("FdSize Report Generator Post Build Not Active due to FDF file not being defined") + return 0 + + #Error - User has build reporting on but hasn't defined the build report output file + elif(thebuilder.env.GetValue("BUILDREPORT_FILE") is None): + logging.error("FdSize Report Generator Post Build failed because Build Report file not defined") + return -1 + + + + # - User has build reporting on but hasn't defined + if(thebuilder.env.GetValue("FDSIZEREPORT_FILE") is None): + logging.debug("FdSize Report Generator Post Build - Fd Size Report file not defined in build system. Setting to plugin default.") + thebuilder.env.SetValue("FDSIZEREPORT_FILE", os.path.join(thebuilder.env.GetValue("BUILD_OUTPUT_BASE"), "FD_REPORT.HTML"), "Value defined by plugin") + + #1 - Get the output path for report file + OutF = thebuilder.env.GetValue("FDSIZEREPORT_FILE") + #2 - Get the FDF path + FdfF = thebuilder.mws.join(thebuilder.ws, thebuilder.env.GetValue("FLASH_DEFINITION")) + #3 - Get the product name + Product = thebuilder.env.GetValue("PRODUCT_NAME") + if Product is None: + logging.debug("Environment variable PRODUCT_NAME is not set") + Product = "not set" + #4 - Get the Fw version + FwVersion = thebuilder.env.GetBuildValue("BUILDID_STRING") + if FwVersion is None: + logging.debug("Environment variable BUILDID_STRING is not set") + FwVersion = "not set" + #5 - Get the build Report file + BuildReportF = thebuilder.env.GetValue("BUILDREPORT_FILE") + + Report = FdReport() + + ret = Report.MakeReport(Product, FwVersion, OutF, FdfF, BuildReportF, thebuilder.ws, thebuilder.pp) + logging.debug("Build Report generation returned %d" % ret) + return ret + +except ImportError: + pass + + +## +# Support code/classes for parsing and creating report +## + + + +class FvModule(object): + + def __init__(self): + self.Path = '' + self.Name = '' + + +class FdRegion(object): + + def __init__(self): + self.Type = '' + self.Base = '' + self.Size = '' + self.Desc = 'Unknown' + self.Used = '' + self.Free = '' + self.SystemAddress = '0' + self.FvModuleList = [] + self.Nested = "False" + + def GetFreePercent(self): + try: + v = Decimal(int(self.Free, 0)) *100 / Decimal(int(self.Size, 0)) + return "%0.2f%%" % v + except: + return 'NA' + + def GetUsedPercent(self): + try: + v = Decimal(int(self.Used, 0)) *100 / Decimal(int(self.Size, 0)) + return "%0.2f%%" % v + except: + return "NA" + +class ModuleSummary(object): + + def __init__(self): + self.Name = '' + self.Size = 0 + self.SizeString = '' + self.Guid = '' + self.InfPath = '' + self.Type = '' + self.MapFilePath = '' + self.FvList = [] + +class FdfMiniParser(object): + + + def __init__(self, fdfFileLines): + self.FileLines = fdfFileLines + self.MaxLines = len(self.FileLines) + self.RE_RegionDescLine = re.compile('^ *#Region_Description:') + + + def GetRegionDescComment(self, BaseAddress): + current = 0 + while(current < self.MaxLines): + if self.RE_RegionDescLine.match(self.FileLines[current]): + al = self.FileLines[current+1] + if al.count("|") == 1 and al.count("x") == 2: + #found a good base address. Now compare + add = int(al.strip().partition('|')[0], 0) + if add == BaseAddress: + return self.FileLines[current].partition(":")[2].strip() + current = current + 1 + return "" + + +class FlashReportParser(object): + + def __init__(self, ReportFileLines, FdfFileLines = None, ToolVersion="1.00", ProductName="Unset", ProductVersion="Unset"): + self.ReportFile = ReportFileLines + self.Parsed = False + self.FdRegions = [] + self.Modules = [] + self.TotalLines = len(ReportFileLines) + + self.FdBase = '' + self.FdName = '' + self.FdSize = '' + self.FdSizeNum = 0 + self.FdBaseNum = 0 + self.FdfMiniParser = None + self.ToolVersion = ToolVersion + self.ProductVersion = ProductVersion + self.ProductName = ProductName + + if FdfFileLines != None and len(FdfFileLines) > 0: + self.FdfMiniParser = FdfMiniParser(FdfFileLines) + + def ParseFdInfo(self): + CurrentLine = 0 + FoundAll = False + FoundIt = False + while(CurrentLine < self.TotalLines) and not FoundAll: + line = self.ReportFile[CurrentLine] + + if FoundIt: + tokens = line.strip().split(':') + if len(tokens) == 2: + if(tokens[0].strip().lower() == "fd name"): + self.FdName = tokens[1] + elif(tokens[0].strip().lower() == 'base address'): + self.FdBase=tokens[1] + self.FdBaseNum = int(self.FdBase, 0) + elif(tokens[0].strip().lower() == 'size'): + self.FdSize = tokens[1].split()[0].strip() + self.FdSizeNum = int(self.FdSize, 0) + FoundAll = True + elif line.strip().lower() == 'firmware device (fd)': + FoundIt = True + + CurrentLine = CurrentLine + 1 + + def ParseAllModules(self): + InModSummary = False + CurrentMod = 0 + CurrentLine = 0 + while(CurrentLine < self.TotalLines): + line = self.ReportFile[CurrentLine] + + #look for module summary section region + if line.strip().lower() == 'module summary': + #new summary + InModSummary = True + mod = ModuleSummary() + self.Modules.append(mod) + CurrentMod = len(self.Modules) - 1 + + #parse within mod summary + elif InModSummary: + tokens = line.strip().split() + if len(tokens) > 0: + if tokens[0].strip() == 'Module': + if tokens[1].strip() == 'Name:': + (self.Modules[CurrentMod]).Name = tokens[2].strip() + elif tokens[1].strip() == 'INF': + self.Modules[CurrentMod].InfPath = tokens[3].strip().replace("\\", "/") + if(not tokens[3].strip().lower().endswith(".inf")): + #get next line + CurrentLine += 1 + line = self.ReportFile[CurrentLine] + self.Modules[CurrentMod].InfPath += line.strip().replace("\\", "/") + + elif (tokens[0].strip() == 'File'): + if(tokens[1].strip() == 'GUID:'): + (self.Modules[CurrentMod]).Guid = tokens[2].strip() + + elif (tokens[0].strip() == 'Size:'): + (self.Modules[CurrentMod]).SizeString = tokens[1].strip() + (self.Modules[CurrentMod]).Size = int(tokens[1].strip(), 0) + + elif (tokens[0].strip() == 'Driver'): + (self.Modules[CurrentMod]).Type = tokens[3].strip() + + elif tokens[0].strip() == '========================================================================================================================': + InModSummary = False + + #increment the currentline + CurrentLine = CurrentLine + 1 + #done processing report file. + #sort list descending + self.Modules.sort(key=lambda x: x.Size, reverse=True) + + + + def ParseFdRegions(self): + InFdRegion = False + CurrentRegion = 0 + CurrentLine = 0 + while(CurrentLine < self.TotalLines): + line = self.ReportFile[CurrentLine] + + #look for fd region + if line.strip().lower() == 'fd region': + #new fd region + InFdRegion = True + Region = FdRegion() + self.FdRegions.append(Region) + CurrentRegion = len(self.FdRegions) - 1 + + elif line.strip().lower() == "nested fv": + #nested fv region. just track the module info + Region = FdRegion() + Region.Nested = "True" + InFdRegion = True + self.FdRegions.append(Region) + CurrentRegion = len(self.FdRegions) -1 + + + #parse within fd region + elif InFdRegion: + tokens = line.strip().split() + if len(tokens) > 0: + if tokens[0].strip() == 'Type:': + (self.FdRegions[CurrentRegion]).Type = tokens[1] + (self.FdRegions[CurrentRegion]).Desc = (self.FdRegions[CurrentRegion]).Type + elif tokens[0].strip() == 'Base': + (self.FdRegions[CurrentRegion]).Base = tokens[2] + bv = int(tokens[2], 0) + (self.FdRegions[CurrentRegion]).SystemAddress = str("0x%X" % (self.FdBaseNum + bv)) + elif tokens[0].strip() == 'Size:': + (self.FdRegions[CurrentRegion]).Size = tokens[1] + elif tokens[0].strip() == 'Occupied': + (self.FdRegions[CurrentRegion]).Used = tokens[2] + elif tokens[0].strip() == 'Free': + (self.FdRegions[CurrentRegion]).Free = tokens[2] + elif (tokens[0].strip() == 'Fv'): + if(tokens[1].strip() == 'Name:'): + if len((self.FdRegions[CurrentRegion]).Desc) > len((self.FdRegions[CurrentRegion]).Type): + (self.FdRegions[CurrentRegion]).Desc = (self.FdRegions[CurrentRegion]).Desc + " --> FV: " + tokens[2] + else: + (self.FdRegions[CurrentRegion]).Desc = "FV: " + tokens[2] + + elif (tokens[0].strip() == 'Capsule'): + if (tokens[1].strip() == "Name:"): + (self.FdRegions[CurrentRegion]).Desc = "Capsule: " + tokens[2] + elif (tokens[1].strip() == 'Size:'): + (self.FdRegions[CurrentRegion]).Used = tokens[2] + filed = int((self.FdRegions[CurrentRegion]).Used, 0) + total = int((self.FdRegions[CurrentRegion]).Size, 0) + free = total - filed + (self.FdRegions[CurrentRegion]).Free = str("0x%X" % free) + + elif (tokens[0].strip() == 'File'): + if (tokens[1].strip() == "Name:"): + (self.FdRegions[CurrentRegion]).Desc = "File: " + tokens[2] + elif (tokens[1].strip() == 'Size:'): + (self.FdRegions[CurrentRegion]).Used = tokens[2] + filed = int((self.FdRegions[CurrentRegion]).Used, 0) + total = int((self.FdRegions[CurrentRegion]).Size, 0) + free = total - filed + (self.FdRegions[CurrentRegion]).Free = str("0x%X" % free) + + + elif tokens[0].strip() == '<---------------------------------------------------------------------------------------------------------------------->': + InFdRegion = False + if (self.FdfMiniParser != None): + #try to get comment for region + desc = self.FdfMiniParser.GetRegionDescComment(int((self.FdRegions[CurrentRegion]).Base, 0)) + if len (desc) > 0: + (self.FdRegions[CurrentRegion]).Desc = (self.FdRegions[CurrentRegion]).Desc + " - " + desc + elif len(tokens) == 3 and tokens[0].lower().startswith("0x"): + #This is the module section + mo = FvModule() + mo.Name = tokens[1] + mo.Path = tokens[2] + if(mo.Path.startswith('(') and not mo.Path.endswith(')')): + #build report line wrapped around. Go get next line + CurrentLine += 1 + mo.Path = mo.Path.strip() + self.ReportFile[CurrentLine].strip() + mo.Path = mo.Path.rstrip(')').lstrip('(') + self.FdRegions[CurrentRegion].FvModuleList.append(mo) + + #increment the currentline + CurrentLine = CurrentLine + 1 + + # + #loop thru all the mods and all the fv regions trying to match up + # + def UpdateModsWithFvs(self, ws): + #go thru each Module Summary + for ms in self.Modules: + logging.debug("Looking for FVs for Mod named %s path: %s" % (ms.Name, ms.InfPath)) + #loop thru all modules in all FVs to find all matches + for fv in self.FdRegions: + for modinfv in fv.FvModuleList: + #to much output logging.debug("Comparing against mod %s" % modinfv.Name) + if(ms.Name.lower() == modinfv.Name.lower()): + #possible match + logging.debug("Name Match. P1 %s p2 %s" % (ms.InfPath.lower().replace("/", "\\"), modinfv.Path.lower().replace("/", "\\"))) + #if(os.path.join(ws, ms.InfPath).lower().replace("/", "\\") == modinfv.Path.lower().replace("/", "\\") ): + if((modinfv.Path.lower().replace("/", "\\")).endswith(ms.InfPath.lower().replace("/", "\\")) ): + #good match + logging.debug("Match found for ModInFV. Mod %s is in FV %s" % (ms.InfPath, fv.Desc)) + if(fv.Desc not in ms.FvList): + ms.FvList.append(fv.Desc) + break #break out of this FV + + + + def JS(self, key, value, comma=True): + r = '"' + key.strip() + '": "' + value.strip() + '"' + if comma: + r = r + "," + return r + + def JSRegion(self, region): + return "{" + self.JS("nested", region.Nested) + self.JS("description", region.Desc) + self.JS("systemAddress", region.SystemAddress) + self.JS("baseAddress", region.Base) + self.JS("size", region.Size) + self.JS("used", region.Used) + self.JS("usedPercentage", region.GetUsedPercent()) + self.JS("free", region.Free) + self.JS("freePercentage", region.GetFreePercent(), False) + "}," + + def JSModule(self, mod): + fvlistjson = '"FV":[' + for f in mod.FvList: + fvlistjson += "'" + f + "'," + fvlistjson = fvlistjson.rstrip(',') + ']' + + return "{" + self.JS("name", mod.Name) + self.JS("path", mod.InfPath) + self.JS("guid", mod.Guid) + self.JS("size", str(mod.Size)) + self.JS("sizeString", mod.SizeString) + self.JS("type", mod.Type) + fvlistjson + "}," + + def ToJsonString(self): + js = "{" + self.JS("FdSizeReportGeneratorVersion", self.ToolVersion) + self.JS("ProductName", self.ProductName) + js += self.JS("ProductVersion", self.ProductVersion) + self.JS("DateCollected", datetime.datetime.strftime(datetime.datetime.now(), "%A, %B %d, %Y %I:%M%p" )) + js += self.JS("fdName", self.FdName) + self.JS("fdBase", self.FdBase) + self.JS("fdSize", self.FdSize) + '"fdRegions": [' + for fdr in self.FdRegions: + js = js + self.JSRegion(fdr) + + js = js.rstrip(",") + js = js + '], "modules": [' + + for mod in self.Modules: + js = js + self.JSModule(mod) + js = js.rstrip(",") + js = js + "]}" + return js + + +class FdReport(object): + MY_FOLDER = os.path.dirname(os.path.realpath(__file__)) + VERSION = "2.02" + + def __init__(self): + pass + + def MakeReport(self, ProductName, ProductVersion, OutputReport, InputFdf, InputBuildReport, Workspace, PackagesPathList=[]): + + if not os.path.isfile(InputFdf): + logging.critical("Invalid path to input FDF file") + return -2 + + if not os.path.isfile(InputBuildReport): + logging.critical("Invalid path to input Build Report file") + return -1 + + if not os.path.isdir(Workspace): + logging.critical("Invalid path to workspace dir") + return -3 + + + f = open(InputBuildReport, "r") + lines = f.readlines() + f.close() + + f = open(InputFdf, "r") + fdfLines = f.readlines() + f.close() + + rep = FlashReportParser(lines, fdfLines, FdReport.VERSION, ProductName, ProductVersion) + rep.ParseFdInfo() + rep.ParseFdRegions() + rep.ParseAllModules() + rep.UpdateModsWithFvs(Workspace) + + + f = open(OutputReport, "w") + template = open(os.path.join(FdReport.MY_FOLDER, "FdReport_Template.html"), "r") + for line in template.readlines(): + if "%TO_BE_FILLED_IN_BY_PYTHON_SCRIPT%" in line: + line = line.replace("%TO_BE_FILLED_IN_BY_PYTHON_SCRIPT%", rep.ToJsonString()) + f.write(line) + template.close() + f.close() + + return 0 + + +################################################ +# This plugin python file is also +# a command line tool +# +################################################ +if __name__ == '__main__': + from optparse import OptionParser + #setup main console as logger + logger = logging.getLogger('') + logger.setLevel(logging.DEBUG) + formatter = logging.Formatter("%(levelname)s - %(message)s") + console = logging.StreamHandler() + console.setLevel(logging.CRITICAL) + console.setFormatter(formatter) + logger.addHandler(console) + + #Do real work cmdline work here + parser = OptionParser() + #Output debug log + parser.add_option("-l", dest="OutputReport", help="Create an output log file: ie -l out.txt", default=None) + parser.add_option("-o", dest="OutputFile", help="Output file (Will be HTML file) : ie -o MyOutput.html", default=None) + parser.add_option("-i", dest="InputReport", help="Input Report File." , default=None) + parser.add_option("-f", dest="FdfFile", help="Input Fdf File used for additional information gathering (optional).", default=None) + parser.add_option("-w", dest="Workspace", help="Absolute path to workspace", default=None) + parser.add_option("--product", dest="ProductName", help="Name of product for report", default="Unknown") + parser.add_option("--fwVersion", dest="FirmwareVersion", help="Firmware Version", default="Unknown") + #Turn on dubug level logging + parser.add_option("--debug", action="store_true", dest="debug", help="turn on debug logging level for file log", default=False) + + (options, args) = parser.parse_args() + + #setup file based logging if outputReport specified + if(options.OutputReport): + if(len(options.OutputReport) < 2): + logging.critical("the output report file parameter is invalid") + sys.exit(-2) + else: + #setup file based logging + filelogger = logging.FileHandler(filename=options.OutputReport, mode='w') + if(options.debug): + filelogger.setLevel(logging.DEBUG) + else: + filelogger.setLevel(logging.INFO) + + filelogger.setFormatter(formatter) + logging.getLogger('').addHandler(filelogger) + + logging.info("Log Started: " + datetime.datetime.strftime(datetime.datetime.now(), "%A, %B %d, %Y %I:%M%p" )) + + #parse report and generate output + if not options.InputReport: + logging.critical("No Input report file") + sys.exit(-1) + + if not os.path.isfile(options.InputReport): + logging.critical("Invalid path to input report") + sys.exit(-2) + + if not options.OutputFile: + logging.critical("No Output file") + sys.exit(-3) + + if not options.Workspace: + logging.critical("No workspace specified") + sys.exit(-4) + + Report = FdReport() + ret = Report.MakeReport(options.ProductName, options.FirmwareVersion, options.OutputFile, options.FdfFile, options.InputReport, options.Workspace) + logging.debug("Build Report generation returned %d" % ret) + + if ret != 0: + logging.critical("Tool Failed. Return Code: %i" % ret) + #end logging + logging.shutdown() + sys.exit(ret) diff --git a/BaseTools/Plugin/FlattenPdbs/FlattenPdbs.py b/BaseTools/Plugin/FlattenPdbs/FlattenPdbs.py index e007b4dedf..4724fc338b 100644 --- a/BaseTools/Plugin/FlattenPdbs/FlattenPdbs.py +++ b/BaseTools/Plugin/FlattenPdbs/FlattenPdbs.py @@ -1,64 +1,64 @@ -## @file FlattenPdbs.py -# Plugin to support copying all PDBs to 1 directory. -# This makes symbol publishing easier and with the usage of -# ALT PDB PATH can shrink the size of each module. -# -## -# Copyright (c) Microsoft Corporation. All rights reserved. -# SPDX-License-Identifier: BSD-2-Clause-Patent -# -# All rights reserved. -# Redistribution and use in source and binary forms, with or without -# modification, are permitted provided that the following conditions are met: -# 1. Redistributions of source code must retain the above copyright notice, -# this list of conditions and the following disclaimer. -# 2. Redistributions in binary form must reproduce the above copyright notice, -# this list of conditions and the following disclaimer in the documentation -# and/or other materials provided with the distribution. -# -# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. -# IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, -# INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, -# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF -# LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE -# OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF -# ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -## -### -from edk2toolext.environment.plugintypes.uefi_build_plugin import IUefiBuildPlugin -import logging -import shutil -import os - -class FlattenPdbs(IUefiBuildPlugin): - - def do_post_build(self, thebuilder): - #Path to Build output - BuildPath = thebuilder.env.GetValue("BUILD_OUTPUT_BASE") - #Path to where the PDBs will be stored - PDBpath = os.path.join(BuildPath, "PDB") - - IgnorePdbs = ['vc1'] #make lower case - - try: - if not os.path.isdir(PDBpath): - os.mkdir(PDBpath) - except: - logging.critical("Error making PDB directory") - - logging.critical("Copying PDBs to flat directory") - for dirpath, dirnames, filenames in os.walk(BuildPath): - if PDBpath in dirpath: - continue - for filename in filenames: - fnl = filename.strip().lower() - if(fnl.endswith(".pdb")): - if(any(e for e in IgnorePdbs if e in fnl)): - # too much info. logging.debug("Flatten PDB - Ignore Pdb: %s" % filename) - pass - else: - shutil.copy(os.path.join(dirpath, filename), os.path.join(PDBpath, filename)) +## @file FlattenPdbs.py +# Plugin to support copying all PDBs to 1 directory. +# This makes symbol publishing easier and with the usage of +# ALT PDB PATH can shrink the size of each module. +# +## +# Copyright (c) Microsoft Corporation. All rights reserved. +# SPDX-License-Identifier: BSD-2-Clause-Patent +# +# All rights reserved. +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are met: +# 1. Redistributions of source code must retain the above copyright notice, +# this list of conditions and the following disclaimer. +# 2. Redistributions in binary form must reproduce the above copyright notice, +# this list of conditions and the following disclaimer in the documentation +# and/or other materials provided with the distribution. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. +# IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, +# INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, +# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF +# LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE +# OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF +# ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +## +### +from edk2toolext.environment.plugintypes.uefi_build_plugin import IUefiBuildPlugin +import logging +import shutil +import os + +class FlattenPdbs(IUefiBuildPlugin): + + def do_post_build(self, thebuilder): + #Path to Build output + BuildPath = thebuilder.env.GetValue("BUILD_OUTPUT_BASE") + #Path to where the PDBs will be stored + PDBpath = os.path.join(BuildPath, "PDB") + + IgnorePdbs = ['vc1'] #make lower case + + try: + if not os.path.isdir(PDBpath): + os.mkdir(PDBpath) + except: + logging.critical("Error making PDB directory") + + logging.critical("Copying PDBs to flat directory") + for dirpath, dirnames, filenames in os.walk(BuildPath): + if PDBpath in dirpath: + continue + for filename in filenames: + fnl = filename.strip().lower() + if(fnl.endswith(".pdb")): + if(any(e for e in IgnorePdbs if e in fnl)): + # too much info. logging.debug("Flatten PDB - Ignore Pdb: %s" % filename) + pass + else: + shutil.copy(os.path.join(dirpath, filename), os.path.join(PDBpath, filename)) return 0 \ No newline at end of file diff --git a/BaseTools/Plugin/OverrideValidation/OverrideValidation.py b/BaseTools/Plugin/OverrideValidation/OverrideValidation.py index 76dbf9609d..973a1de9e1 100644 --- a/BaseTools/Plugin/OverrideValidation/OverrideValidation.py +++ b/BaseTools/Plugin/OverrideValidation/OverrideValidation.py @@ -1,709 +1,709 @@ -## -# Tool to generate a report on Module Level Overriding status for a UEFI build. -# This tool depends on EDK2 and will parse dsc files, inf files and other standard -# EDK2 assets -# -# Copyright (c) Microsoft Corporation. All rights reserved. -# SPDX-License-Identifier: BSD-2-Clause-Patent -## - - -import logging -import os -import io -import sys -from datetime import datetime -import subprocess -import argparse -import hashlib -import re -from io import StringIO - -# -# for now i want to keep this file as both a command line tool and a plugin for the Uefi Build system. -# To do this the plugin class is only defined if in the build environment where the plugin classes are importable. -# -# -try: - from edk2toolext.environment.plugintypes.uefi_build_plugin import IUefiBuildPlugin - from edk2toollib.uefi.edk2.parsers.inf_parser import InfParser - from edk2toollib.utility_functions import RunCmd - from edk2toollib.uefi.edk2.parsers.dsc_parser import * - from edk2toollib.uefi.edk2.path_utilities import Edk2Path - - #Tuple for (version, entrycount) - FORMAT_VERSION_1 = (1, 4) #Version 1: #OVERRIDE : VERSION | PATH_TO_MODULE | HASH | YYYY-MM-DDThh-mm-ss - FORMAT_VERSION_2 = (2, 5) #Version 2: #OVERRIDE : VERSION | PATH_TO_MODULE | HASH | YYYY-MM-DDThh-mm-ss | GIT_COMMIT - FORMAT_VERSIONS = [FORMAT_VERSION_1, FORMAT_VERSION_2] - - - class OverrideValidation(IUefiBuildPlugin): - - class OverrideResult(object): - OR_ALL_GOOD = 0 - OR_FILE_CHANGE = 1 - OR_VER_UNRECOG = 2 - OR_INVALID_FORMAT = 3 - OR_DSC_INF_NOT_FOUND = 4 - OR_TARGET_INF_NOT_FOUND = 5 - - @classmethod - def GetErrStr (cls, errcode): - str = '' - if (errcode == cls.OR_ALL_GOOD): - str = 'SUCCESS' - elif (errcode == cls.OR_FILE_CHANGE): - str = 'MISMATCH' - elif (errcode == cls.OR_VER_UNRECOG): - str = 'INVALID_VERSION' - elif (errcode == cls.OR_INVALID_FORMAT): - str = 'INVALID_FORMAT' - elif (errcode == cls.OR_DSC_INF_NOT_FOUND): - str = 'FILE_NOT_FOUND' - elif (errcode == cls.OR_TARGET_INF_NOT_FOUND): - str = 'INF_FILE_NOT_FOUND' - else: - str = 'UNKNOWN' - return str - # END: GetErrStr (errcode) - - class ModuleNode: - # path: the workspace/package path based path - def __init__(self, path, status, age): - self.path = path - self.status = status - self.age = age - self.expect_hash = '' - self.entry_hash = '' - self.reflist = [] - - # Check and see if there is any line in the inf files that follows the pattern below: - def do_pre_build(self, thebuilder): - # Setup timestamp to log time cost in this section - starttime = datetime.now() - logging.info("---------------------------------------------------------") - logging.info("--------------Override Validation Starting---------------") - logging.info("---------------------------------------------------------") - - rc = self.override_plat_validate(thebuilder) - if(rc == self.OverrideResult.OR_ALL_GOOD): - logging.debug("Override validation all in sync") - else: - logging.error("Override validation failed") - - endtime = datetime.now() - delta = endtime - starttime - logging.info("---------------------------------------------------------") - logging.info("--------------Override Validation Finished---------------") - logging.info("-------------- Running Time (mm:ss): {0[0]:02}:{0[1]:02} --------------".format(divmod(delta.seconds, 60))) - logging.info("---------------------------------------------------------") - - return rc - # END: do_pre_build(self, thebuilder) - - # Walk through the target inf files in platform dsc file for override validation - def override_plat_validate(self, thebuilder): - result = self.OverrideResult.OR_ALL_GOOD - InfFileList = self.get_dsc_inf_list(thebuilder) - - ws = thebuilder.ws - pp = thebuilder.pp.split(os.pathsep) - self.PathTool = Edk2Path(ws, pp) - - if (InfFileList == []): - return result - - modulelist = [] - status = [0, 0] - - # Search through the workspace and package paths - for file in InfFileList: - temp_list = [] - modulenode = self.ModuleNode(file, self.OverrideResult.OR_ALL_GOOD, 0) - fullpath = thebuilder.mws.join(thebuilder.ws, file) - - m_result = self.override_detect_process(thebuilder, fullpath, temp_list, modulenode, status) - # Do not log the module that does not have any override records - if (len(modulenode.reflist) > 0): - modulelist.append(modulenode) - - if m_result != self.OverrideResult.OR_ALL_GOOD: - if m_result != self.OverrideResult.OR_DSC_INF_NOT_FOUND: - result = m_result - logging.error("Override processing error %s in file/dir %s" % (self.OverrideResult.GetErrStr(m_result), file)) - - self.override_log_print(thebuilder, modulelist, status) - - return result - # END: override_plat_validate(self, thebuilder) - - # Check and see if the picked file has this flag - # filepath: the absolute path to the overriding module's inf file - # filelist: the stack of files collected during a dfs for loop detection, should be absolute path and lower case all the time - # modulenode: Module node of this "filepath" module - # status: tuple that contains the count for succeeded modules scanned and total scanned - def override_detect_process(self, thebuilder, filepath, filelist, modulenode, status): - # Find the specific line of Override flag - result = self.OverrideResult.OR_ALL_GOOD - lineno = 0 - trackno = 0 - track_nf = [] - track_fc = [] - track_ag = [] - - list_path = os.path.normpath(filepath).lower() - - if (list_path in filelist): - return result - - # This processing step is only for files. If the filepath is a directory (meaning the directory is hashed), skip this step - if os.path.isdir(filepath): - return result - - # Check for file existence, fail otherwise. - if not os.path.isfile(filepath): - return self.OverrideResult.OR_DSC_INF_NOT_FOUND - - # Loop detection happen here by adding the visited module into stack - filelist.append(list_path) - - # Look for a comment line that starts with Override - with open(filepath, "r") as my_file: - for Line in my_file : - lineno = lineno + 1 - Line = Line.strip() - if not Line.startswith('#'): - continue - - CommentLine = Line.strip('#').split(':') - if (len(CommentLine) != 2) or\ - ((CommentLine[0].strip().lower() != 'override') and\ - (CommentLine[0].strip().lower() != 'track')): - continue - - # Process the override content, 1. Bail on bad data; 2. Print on formatted data (matched or not) - tagtype = CommentLine[0].strip().lower() - m_result = self.override_process_line(thebuilder, CommentLine[1], filepath, filelist, modulenode, status, tagtype) - - if CommentLine[0].strip().lower() == 'override': - # For override tags, the hash has to match - if m_result != self.OverrideResult.OR_ALL_GOOD: - result = m_result - logging.error("At Line %d: %s" %(lineno, Line)) - - elif CommentLine[0].strip().lower() == 'track': - # For track tags, ignore the tags of which inf modules are not found - trackno = trackno + 1 - if m_result == self.OverrideResult.OR_TARGET_INF_NOT_FOUND: - track_nf.append ((lineno, Line)) - logging.info("At Line %d: %s" %(lineno, Line)) - elif m_result == self.OverrideResult.OR_FILE_CHANGE: - track_fc.append([lineno, Line, modulenode.reflist[-1].path, False]) - logging.info("At Line %d: %s" %(lineno, Line)) - elif m_result != self.OverrideResult.OR_ALL_GOOD: - result = m_result - logging.error("At Line %d: %s" %(lineno, Line)) - else: - track_ag.append(modulenode.reflist[-1].path) - - if trackno != 0 and len(track_nf) == trackno: - # All track tags in this file are not found, this will enforce a failure, if not already failed - if result == self.OverrideResult.OR_ALL_GOOD: - result = self.OverrideResult.OR_TARGET_INF_NOT_FOUND - for (lineno, Line) in track_nf: - logging.error("Track tag failed to locate target module at Line %d: %s" %(lineno, Line)) - - if len(track_fc) != 0: - canceled_cnt = 0 - # Some track tags failed, see if they can be canceled out by other passed track tags - for entry in track_fc: - for all_good_line in track_ag: - if entry[2] == all_good_line: - canceled_cnt = canceled_cnt + 1 - entry[3] = True - break - if canceled_cnt != len(track_fc) and result == self.OverrideResult.OR_ALL_GOOD: - result = self.OverrideResult.OR_FILE_CHANGE - - for (lineno, Line, _, canceled) in track_fc: - if not canceled: - logging.error("Track tag failed to match module hash at Line %d: %s" %(lineno, Line)) - - # Revert this visitied indicator after this branch is done searching - filelist.remove(list_path) - return result - # END: override_detect_process(self, thebuilder, filepath, filelist, modulenode, status) - - # Process the comment line that starts with Override - # overridecnt: Content of Override record, should include the content after "Override:" - # filepath: the absolute path to the overriding module's inf file - # filelist: the stack of files collected during a dfs for loop detection, should be absolute path and lower case all the time - # modulenode: Module node of this "filepath" module - # status: tuple that contains the count for succeeded modules scanned and total scanned - def override_process_line(self, thebuilder, overridecnt, filepath, filelist, modulenode, status, tagtype): - # Prepare the potential node and update total processed number here - m_node = self.ModuleNode("", self.OverrideResult.OR_ALL_GOOD, 0) - modulenode.reflist.append(m_node) - status[1] = status[1] + 1 - - # Handle tail comments and/or empty spaces - EndIndex = overridecnt.find('#') - EndIndex = EndIndex if (EndIndex != -1) else len(overridecnt) - - OverrideEntry = overridecnt[0:EndIndex].split('|') - - # Step 1: Check version and number of blocks in this entry - EntryVersion = 0 - try: - EntryVersion = int(OverrideEntry[0]) - except ValueError: - logging.error("Inf Override Parse Error, override parameter has invalid version %s" %(OverrideEntry[0])) - result = self.OverrideResult.OR_INVALID_FORMAT - m_node.status = result - return result - - # Verify this is a known version and has valid number of entries - version_match = False - for VERSION_FORMAT in FORMAT_VERSIONS: - if len(VERSION_FORMAT) < 2: - logging.warning("Invalid formatted version: " + str(VERSION_FORMAT)) - continue - if EntryVersion == VERSION_FORMAT[0] and len(OverrideEntry) == VERSION_FORMAT[1]: - version_match = VERSION_FORMAT - break - if version_match == False: - logging.error(f"Inf Override Unrecognized Version {EntryVersion} or corrupted format ({len(OverrideEntry)}) in this entry: {filepath}") - result = self.OverrideResult.OR_VER_UNRECOG - m_node.status = result - return result - - if version_match[0] == 1: - return self.override_process_line_with_version1(thebuilder, filelist, OverrideEntry, m_node, status, tagtype) - elif version_match[0] == 2: - return self.override_process_line_with_version2(thebuilder, filelist, OverrideEntry, m_node, status, tagtype) - else: - raise ValueError(f"Handler is not provided for {version_match}") - - # END: override_process_line(self, thebuilder, overridecnt, filepath, filelist, modulenode, status) - - def override_process_line_with_version1(self, thebuilder, filelist, OverrideEntry, m_node, status, tagtype): - EntryVersion = 1 - # Step 2: Process the path to overridden module - # Normalize the path to support different slashes, then strip the initial '\\' to make sure os.path.join will work correctly - overriddenpath = os.path.normpath(OverrideEntry[1].strip()).strip('\\') - fullpath = os.path.normpath(thebuilder.mws.join(thebuilder.ws, overriddenpath)) - # Search overridden module in workspace - if not os.path.isfile(fullpath) and not os.path.isdir(fullpath): - logging.info("Inf Overridden File/Path Not Found in Workspace or Packages_Path: %s" %(overriddenpath)) - result = self.OverrideResult.OR_TARGET_INF_NOT_FOUND - m_node.path = overriddenpath - m_node.status = result - return result - - # Step 3: Grep hash entry - EntryHash = OverrideEntry[2].strip() - - # Step 4: Parse the time of hash generation - try: - EntryTimestamp = datetime.strptime(OverrideEntry[3].strip(), "%Y-%m-%dT%H-%M-%S") - except ValueError: - logging.error("Inf Override Parse Error, override parameter has invalid timestamp %s" %(OverrideEntry[3].strip())) - result = self.OverrideResult.OR_INVALID_FORMAT - m_node.status = result - return result - - # Step 5: Calculate the hash of overridden module and compare with our record in the overriding module - res_tuple = self.override_hash_compare(thebuilder, EntryVersion, EntryHash, fullpath) - result = res_tuple.get('result') - m_node.expect_hash = res_tuple.get('hash_val') - - # Step 6: House keeping - # Process the path to workspace/package path based add it to the parent node - overridden_rel_path = self.PathTool.GetEdk2RelativePathFromAbsolutePath(fullpath) - date_delta = datetime.utcnow() - EntryTimestamp - - m_node.entry_hash = EntryHash - m_node.path = overridden_rel_path - m_node.status = result - m_node.age = date_delta.days - - if (result == self.OverrideResult.OR_ALL_GOOD): - status[0] = status[0] + 1 - else: - pnt_str = "Inf Override Hash Error: %s, expecting %s, has %s" %(self.OverrideResult.GetErrStr(result), m_node.expect_hash, m_node.entry_hash) - if tagtype == 'override': - logging.error(pnt_str) - else: - logging.info(pnt_str) - - # Step 7: Do depth-first-search for cascaded modules - m_result = self.override_detect_process(thebuilder, fullpath, filelist, m_node, status) - if (m_result != self.OverrideResult.OR_ALL_GOOD) and \ - (result == self.OverrideResult.OR_ALL_GOOD): - result = m_result - - # The result will be inherited from above function calls - return result - # END: override_process_line_version1(self, thebuilder, filelist, OverrideEntry, m_node, status) - - def override_process_line_with_version2(self, thebuilder, filelist, OverrideEntry, m_node, status, tagtype): - ''' #Version 2: #OVERRIDE : VERSION | PATH_TO_MODULE | HASH | YYYY-MM-DDThh-mm-ss | GIT_COMMIT ''' - GitHash = OverrideEntry[4].strip() - del OverrideEntry[4] - result = self.override_process_line_with_version1(thebuilder, filelist, OverrideEntry, m_node, status, tagtype) - # if we failed, do a diff of the overridden file (as long as exist) and show the output - if result != self.OverrideResult.OR_ALL_GOOD and result != self.OverrideResult.OR_TARGET_INF_NOT_FOUND: - overriddenpath = os.path.normpath(OverrideEntry[1].strip()).strip('\\') - fullpath = os.path.normpath(thebuilder.mws.join(thebuilder.ws, overriddenpath)) - if os.path.exists(fullpath): - patch = ModuleGitPatch(fullpath, GitHash) - # TODO: figure out how to get the log file - pnt_str = f"Override diff since last update at commit {GitHash}" - if tagtype == 'override': - logging.error(pnt_str) - else: - logging.info(pnt_str) - - return result - # END: override_process_line_version2(self, thebuilder, filelist, OverrideEntry, m_node, status) - - # Check override record against parsed entries - # version: Override record's version number, normally parsed from the override record line - # hash: Override record's hash field, normally parsed from the override record line, calculated by the standalone ModuleHash tool - # fullpath: the absolute path to the overridden module's inf file - def override_hash_compare(self, thebuilder, version, hash, fullpath): - result = self.OverrideResult.OR_ALL_GOOD - hash_val = '' - - # Error out the unknown version - if (version == FORMAT_VERSION_1[0]): - hash_val = ModuleHashCal(fullpath) - if (hash_val != hash): - result = self.OverrideResult.OR_FILE_CHANGE - else: - # Should not happen - result = self.OverrideResult.OR_VER_UNRECOG - return {'result':result, 'hash_val':hash_val} - # END: override_hash_compare(self, thebuilder, version, hash, fullpath) - - # Print the log after override validation is complete - # modulelist: list of modules collected while processing inf files - # status: tuple that contains the count for succeeded modules scanned and total scanned - def override_log_print(self, thebuilder, modulelist, status): - # Check and specify log file path - base_path = thebuilder.env.GetValue("BUILD_OUTPUT_BASE") - if (base_path is None): - return - - logfile = os.path.join(base_path, "OVERRIDELOG.TXT") - logfile = os.path.normpath(logfile) - if not os.path.isdir(os.path.dirname(logfile)): - os.makedirs(os.path.dirname(logfile)) - - with open(logfile, 'w') as log: - log.write("Platform: %s\n" %(thebuilder.env.GetValue("PRODUCT_NAME"))) - log.write("Version: %s\n" %(thebuilder.env.GetValue("BLD_*_BUILDID_STRING"))) - log.write("Date: %s\n" %(datetime.utcnow().strftime("%Y-%m-%dT%H-%M-%S"))) - log.write("Commit: %s\n" %(thebuilder.env.GetValue("BLD_*_BUILDSHA"))) - log.write("State: %d/%d\n" %(status[0], status[1])) - - log.write("\n") - log.write("Overrides\n") - log.write("----------------------------------------------------------------\n") - log.write("\n") - - for node in modulelist: - # Pass in a "stack" into the function for loop detection while doing dfs - stack = [] - log.write("OVERRIDER: %s\n" %(node.path)) - log.write("ORIGINALS:\n") - self.node_dfs(thebuilder, node, stack, log) - log.write("\n") - - logfile = logfile.replace('\\', '/') - logging.critical("Override Log file at %s" %(logfile)) - # END: override_log_print(self, thebuilder, modulelist, status) - - # Traverse through the collect structure and print log - # node: Module Node representing the overriding module - # stack: the stack of paths collected during a dfs for loop detection, should be absolute path and lower case all the time - # log: log file object, must be readily open for file write when called - def node_dfs(self, thebuilder, node, stack, log): - fullpath = os.path.normpath(thebuilder.mws.join(thebuilder.ws, node.path)).lower() - if (node.path in stack): - return - stack.append(fullpath) - - for m_node in node.reflist: - list_len = len(stack) - str = "\t"*list_len+"+ %s | %s | %d days\n" %(m_node.path, self.OverrideResult.GetErrStr(m_node.status), m_node.age) - if (m_node.status == self.OverrideResult.OR_ALL_GOOD): - log.write(str) - self.node_dfs(thebuilder, m_node, stack, log) - elif (m_node.status == self.OverrideResult.OR_FILE_CHANGE): - log.write(str) - log.write("\t"*list_len+"| \tCurrent State: %s | Last Fingerprint: %s\n" %(m_node.expect_hash, m_node.entry_hash)) - self.node_dfs(thebuilder, m_node, stack, log) - else: - log.write("\t"*list_len+"+ %s | %s\n" % (m_node.path, self.OverrideResult.GetErrStr(m_node.status))) - - stack.remove(fullpath) - # END: node_dfs(self, thebuilder, node, stack, log) - - # Create a list of inf files that is included in a dsc file (including !Include entries) - def get_dsc_inf_list(self, thebuilder): - InfFileList = [] - - # Dsc parser is used in this instance - logging.debug("Parse Active Platform DSC file") - input_vars = thebuilder.env.GetAllBuildKeyValues() - input_vars["TARGET"] = thebuilder.env.GetValue("TARGET") - dscp = DscParser().SetBaseAbsPath(thebuilder.ws).SetPackagePaths(thebuilder.pp.split(os.pathsep)).SetInputVars(input_vars) - plat_dsc = thebuilder.env.GetValue("ACTIVE_PLATFORM") - if (plat_dsc is None): - return InfFileList - - # Parse the DSC - pa = thebuilder.mws.join(thebuilder.ws, plat_dsc) - dscp.ParseFile(pa) - # Add the DSC itself (including all the includes) - InfFileList.extend(dscp.GetAllDscPaths()) - # Add the FDF - if "FLASH_DEFINITION" in dscp.LocalVars: - fd = thebuilder.mws.join(thebuilder.ws, dscp.LocalVars["FLASH_DEFINITION"]) - InfFileList.append(fd) - # Here we collect all the reference libraries, IA-32 modules, x64 modules and other modules - if (dscp.Parsed) : - for lib in dscp.Libs: - InfFileList.append(lib) - for ThreeMod in dscp.ThreeMods: - InfFileList.append(ThreeMod) - for SixMod in dscp.SixMods: - InfFileList.append(SixMod) - for OtherMod in dscp.OtherMods: - InfFileList.append(OtherMod) - return InfFileList - # END: get_dsc_inf_list(self, thebuilder) -except ImportError: - pass - -# This calculates the md5 for the inf file as well as all the first order include source files -# path: the absolute path to the module's inf file -def ModuleHashCal(path): - - sourcefileList = [] - binaryfileList = [] - hash_obj = hashlib.md5() - - # Find the specific line of Sources section - folderpath = os.path.dirname(path) - - if os.path.isdir(path): - # Collect all files in this folder to the list - for subdir, _, files in os.walk(path): - for file in files: - sourcefileList.append(os.path.join(subdir, file)) - else: - sourcefileList.append(path) - - if path.lower().endswith(".inf") and os.path.isfile(path): - - # Use InfParser to parse sources section - ip = InfParser() - ip.ParseFile(path) - - # Add all referenced source files in addition to our inf file list - for source in ip.Sources: - sourcefileList.append(os.path.normpath(os.path.join(folderpath, source))) - - # Add all referenced binary files to our binary file list - for binary in ip.Binaries: - binaryfileList.append(os.path.normpath(os.path.join(folderpath, binary))) - - for sfile in sourcefileList: - #print('Calculated: %s' %(sfile)) #Debug only - with open(sfile, 'rb') as entry: - # replace \r\n with \n to take care of line terminators - hash_obj.update(entry.read().replace(b'\r\n', b'\n')) - - for bfile in binaryfileList: - #print('Calculated: %s' %(bfile)) #Debug only - with open(bfile, 'rb') as entry: - hash_obj.update(entry.read()) - - result = hash_obj.hexdigest() - return result - -def ModuleGitPatch(path, git_hash): - ''' return a git patch of the given file since the hash ''' - GitOutput = io.StringIO() - # TODO - let this go to console so we get colors - path_dir = os.path.dirname(path) - ret = RunCmd("git", f"diff {git_hash} {path}", workingdir=path_dir, outstream=GitOutput) - if ret != 0: - return "" - GitOutput.seek(0) - result = [] - for line in GitOutput.readlines(): - result.append(line.strip()) - return "\n".join(result) - -def ModuleGitHash(path): - ''' gets the current git hash of the given directory that path is ''' - abspath_dir = os.path.dirname(os.path.abspath(path)) - git_stream = StringIO() - ret = RunCmd("git", "rev-parse --verify HEAD", workingdir=abspath_dir, outstream=git_stream) - if ret != 0: - return None - git_stream.seek(0) - git_hash = git_stream.readline().strip() - if git_hash.count(" ") != 0: - raise RuntimeError("Unable to get GIT HASH for: " + abspath_dir) - return git_hash - -# Setup import and argument parser -def path_parse(): - - parser = argparse.ArgumentParser() - - parser.add_argument ( - '-w', '--workspace', dest = 'WorkSpace', required = True, type=str, - help = '''Specify the absolute path to your workspace by passing -w WORKSPACE or --workspace WORKSPACE.''' - ) - group = parser.add_mutually_exclusive_group(required=True) - group.add_argument ( - '-m', '--modulepath', dest = 'ModulePath', type=str, - help = '''Specify the absolute path to your module by passing -m Path/To/Module.inf or --modulepath Path/To/Module.inf.''' - ) - group.add_argument ( - '-t', '--targetpath', dest = 'TargetPath', type=str, - help = '''Specify the absolute path to your target module/file/folder by passing t Path/To/Target or --targetpath Path/To/Target.''' - ) - group.add_argument ( - '-r', '--regenpath', dest = 'RegenPath', type=str, - help = '''Specify the absolute path to an inf with existing overrides to regen by passing r Path/To/Target or --regenpath Path/To/Target.''' - ) - parser.add_argument ( - '-p', '--packagepath', dest = 'RegenPackagePath', nargs="*", default=[], - help = '''Specify the packages path to be used to resolve relative paths when using --regenpath. ignored otherwise. Workspace is always included.''' - ) - parser.add_argument ( - '-v', '--version', dest = 'Version', default= 2, type=int, - help = '''This is the version of the override hash to produce (currently only 1 and 2 are valid)''' - ) - parser.add_argument ( - '--track', action="store_true", dest = 'Track', default= False, - help = '''Indicate whether to create a track tag or override tag. Track tags will be treated as ignorable if the - overridden modules are not found. However, for each module that contains track tags, at least one tracked modules - has to be found, otherwise build will fail. By default, all tags will be generated as override tags.''' - ) - - Paths = parser.parse_args() - # pre-process the parsed paths to abspath - Paths.WorkSpace = os.path.abspath(Paths.WorkSpace) - if Paths.TargetPath is not None: - Paths.TargetPath = os.path.abspath(Paths.TargetPath) - - if Paths.ModulePath is not None: - Paths.TargetPath = os.path.abspath(Paths.ModulePath) - if not os.path.isfile(Paths.TargetPath): - raise RuntimeError("Module path is invalid.") - - if Paths.Version < 1 or Paths.Version > len(FORMAT_VERSIONS): - raise RuntimeError("Version is invalid") - - if not os.path.isdir(Paths.WorkSpace): - raise RuntimeError("Workspace path is invalid.") - if Paths.TargetPath is not None: - if not os.path.isfile(Paths.TargetPath) and not os.path.isdir(Paths.TargetPath): - raise RuntimeError("Module path is invalid.") - # Needs to strip os.sep is to take care of the root path case - # For a folder, this will do nothing on a formatted abspath - # For a drive root, this will rip off the os.sep - if not os.path.normcase(Paths.TargetPath).startswith(os.path.normcase(Paths.WorkSpace.rstrip(os.sep)) + os.sep): - raise RuntimeError("Module is not within specified Workspace.") - - if Paths.RegenPath is not None: - if not os.path.isfile(Paths.RegenPath): - raise RuntimeError("Regen path is invalid.") - # Needs to strip os.sep is to take care of the root path case - # For a folder, this will do nothing on a formatted abspath - # For a drive root, this will rip off the os.sep - if not os.path.normcase(Paths.RegenPath).startswith(os.path.normcase(Paths.WorkSpace.rstrip(os.sep)) + os.sep): - raise RuntimeError("Module is not within specified Workspace.") - - return Paths - -################################################ -# This plugin python file is also -# a command line tool -# -################################################ -if __name__ == '__main__': - - from edk2toollib.uefi.edk2.parsers.inf_parser import InfParser - from edk2toollib.uefi.edk2.path_utilities import Edk2Path - - # Parse required paths passed from cmd line arguments - Paths = path_parse() - - # check if we are asked to update an .inf file "in-place" - if (Paths.RegenPath is not None): - pathtool = Edk2Path(Paths.WorkSpace, Paths.RegenPackagePath) - - v1_regex = re.compile(r"#(Override|Track) : (.*?) \| (.*?) \| (.*?) \| (.*?)") - v2_regex = re.compile(r"#(Override|Track) : (.*?) \| (.*?) \| (.*?) \| (.*?) \| (.*?)") - with open (Paths.RegenPath) as fd: - RegenInfData = fd.read() - - RegenInfOutData = "" - for line in RegenInfData.splitlines (True): - match = v1_regex.match(line) - if match is None: - match = v2_regex.match(line) - - if match is not None: - rel_path = match.group(3) - abs_path = pathtool.GetAbsolutePathOnThisSystemFromEdk2RelativePath(rel_path) - if abs_path is not None: - mod_hash = ModuleHashCal(abs_path) - # only update the line if the hash has changed - this ensures the timestamp tracks actual changes rather than last time it was run. - if (mod_hash != match.group(4)): - VERSION_INDEX = Paths.Version - 1 - - if VERSION_INDEX == 0: - line = '#%s : %08d | %s | %s | %s\n' % (match.group(1), FORMAT_VERSION_1[0], rel_path, mod_hash, datetime.utcnow().strftime("%Y-%m-%dT%H-%M-%S")) - elif VERSION_INDEX == 1: - git_hash = ModuleGitHash(abs_path) - line = '#%s : %08d | %s | %s | %s | %s\n' % (match.group(1), FORMAT_VERSION_2[0], rel_path, mod_hash, datetime.utcnow().strftime("%Y-%m-%dT%H-%M-%S"), git_hash) - print("Updating:\n" + line) - else: - print(f"Warning: Could not resolve relative path {rel_path}. Override line not updated.\n") - - RegenInfOutData += line - - with open (Paths.RegenPath, "w") as fd: - fd.write(RegenInfOutData) - - else: - dummy_list = [] - pathtool = Edk2Path(Paths.WorkSpace, dummy_list) - - # Generate and print the override for pasting into the file. - # Use absolute module path to find package path - pkg_path = pathtool.GetContainingPackage(Paths.TargetPath) - rel_path = Paths.TargetPath[Paths.TargetPath.find(pkg_path):] - - rel_path = rel_path.replace('\\', '/') - mod_hash = ModuleHashCal(Paths.TargetPath) - - VERSION_INDEX = Paths.Version - 1 - - if VERSION_INDEX == 0: - print("Copy and paste the following line(s) to your overrider inf file(s):\n") - print('#%s : %08d | %s | %s | %s' % ("Override" if not Paths.Track else "Track", FORMAT_VERSION_1[0], rel_path, mod_hash, datetime.utcnow().strftime("%Y-%m-%dT%H-%M-%S"))) - - elif VERSION_INDEX == 1: - git_hash = ModuleGitHash(Paths.TargetPath) - print("Copy and paste the following line(s) to your overrider inf file(s):\n") - print('#%s : %08d | %s | %s | %s | %s' % ("Override" if not Paths.Track else "Track", FORMAT_VERSION_2[0], rel_path, mod_hash, datetime.utcnow().strftime("%Y-%m-%dT%H-%M-%S"), git_hash)) +## +# Tool to generate a report on Module Level Overriding status for a UEFI build. +# This tool depends on EDK2 and will parse dsc files, inf files and other standard +# EDK2 assets +# +# Copyright (c) Microsoft Corporation. All rights reserved. +# SPDX-License-Identifier: BSD-2-Clause-Patent +## + + +import logging +import os +import io +import sys +from datetime import datetime +import subprocess +import argparse +import hashlib +import re +from io import StringIO + +# +# for now i want to keep this file as both a command line tool and a plugin for the Uefi Build system. +# To do this the plugin class is only defined if in the build environment where the plugin classes are importable. +# +# +try: + from edk2toolext.environment.plugintypes.uefi_build_plugin import IUefiBuildPlugin + from edk2toollib.uefi.edk2.parsers.inf_parser import InfParser + from edk2toollib.utility_functions import RunCmd + from edk2toollib.uefi.edk2.parsers.dsc_parser import * + from edk2toollib.uefi.edk2.path_utilities import Edk2Path + + #Tuple for (version, entrycount) + FORMAT_VERSION_1 = (1, 4) #Version 1: #OVERRIDE : VERSION | PATH_TO_MODULE | HASH | YYYY-MM-DDThh-mm-ss + FORMAT_VERSION_2 = (2, 5) #Version 2: #OVERRIDE : VERSION | PATH_TO_MODULE | HASH | YYYY-MM-DDThh-mm-ss | GIT_COMMIT + FORMAT_VERSIONS = [FORMAT_VERSION_1, FORMAT_VERSION_2] + + + class OverrideValidation(IUefiBuildPlugin): + + class OverrideResult(object): + OR_ALL_GOOD = 0 + OR_FILE_CHANGE = 1 + OR_VER_UNRECOG = 2 + OR_INVALID_FORMAT = 3 + OR_DSC_INF_NOT_FOUND = 4 + OR_TARGET_INF_NOT_FOUND = 5 + + @classmethod + def GetErrStr (cls, errcode): + str = '' + if (errcode == cls.OR_ALL_GOOD): + str = 'SUCCESS' + elif (errcode == cls.OR_FILE_CHANGE): + str = 'MISMATCH' + elif (errcode == cls.OR_VER_UNRECOG): + str = 'INVALID_VERSION' + elif (errcode == cls.OR_INVALID_FORMAT): + str = 'INVALID_FORMAT' + elif (errcode == cls.OR_DSC_INF_NOT_FOUND): + str = 'FILE_NOT_FOUND' + elif (errcode == cls.OR_TARGET_INF_NOT_FOUND): + str = 'INF_FILE_NOT_FOUND' + else: + str = 'UNKNOWN' + return str + # END: GetErrStr (errcode) + + class ModuleNode: + # path: the workspace/package path based path + def __init__(self, path, status, age): + self.path = path + self.status = status + self.age = age + self.expect_hash = '' + self.entry_hash = '' + self.reflist = [] + + # Check and see if there is any line in the inf files that follows the pattern below: + def do_pre_build(self, thebuilder): + # Setup timestamp to log time cost in this section + starttime = datetime.now() + logging.info("---------------------------------------------------------") + logging.info("--------------Override Validation Starting---------------") + logging.info("---------------------------------------------------------") + + rc = self.override_plat_validate(thebuilder) + if(rc == self.OverrideResult.OR_ALL_GOOD): + logging.debug("Override validation all in sync") + else: + logging.error("Override validation failed") + + endtime = datetime.now() + delta = endtime - starttime + logging.info("---------------------------------------------------------") + logging.info("--------------Override Validation Finished---------------") + logging.info("-------------- Running Time (mm:ss): {0[0]:02}:{0[1]:02} --------------".format(divmod(delta.seconds, 60))) + logging.info("---------------------------------------------------------") + + return rc + # END: do_pre_build(self, thebuilder) + + # Walk through the target inf files in platform dsc file for override validation + def override_plat_validate(self, thebuilder): + result = self.OverrideResult.OR_ALL_GOOD + InfFileList = self.get_dsc_inf_list(thebuilder) + + ws = thebuilder.ws + pp = thebuilder.pp.split(os.pathsep) + self.PathTool = Edk2Path(ws, pp) + + if (InfFileList == []): + return result + + modulelist = [] + status = [0, 0] + + # Search through the workspace and package paths + for file in InfFileList: + temp_list = [] + modulenode = self.ModuleNode(file, self.OverrideResult.OR_ALL_GOOD, 0) + fullpath = thebuilder.mws.join(thebuilder.ws, file) + + m_result = self.override_detect_process(thebuilder, fullpath, temp_list, modulenode, status) + # Do not log the module that does not have any override records + if (len(modulenode.reflist) > 0): + modulelist.append(modulenode) + + if m_result != self.OverrideResult.OR_ALL_GOOD: + if m_result != self.OverrideResult.OR_DSC_INF_NOT_FOUND: + result = m_result + logging.error("Override processing error %s in file/dir %s" % (self.OverrideResult.GetErrStr(m_result), file)) + + self.override_log_print(thebuilder, modulelist, status) + + return result + # END: override_plat_validate(self, thebuilder) + + # Check and see if the picked file has this flag + # filepath: the absolute path to the overriding module's inf file + # filelist: the stack of files collected during a dfs for loop detection, should be absolute path and lower case all the time + # modulenode: Module node of this "filepath" module + # status: tuple that contains the count for succeeded modules scanned and total scanned + def override_detect_process(self, thebuilder, filepath, filelist, modulenode, status): + # Find the specific line of Override flag + result = self.OverrideResult.OR_ALL_GOOD + lineno = 0 + trackno = 0 + track_nf = [] + track_fc = [] + track_ag = [] + + list_path = os.path.normpath(filepath).lower() + + if (list_path in filelist): + return result + + # This processing step is only for files. If the filepath is a directory (meaning the directory is hashed), skip this step + if os.path.isdir(filepath): + return result + + # Check for file existence, fail otherwise. + if not os.path.isfile(filepath): + return self.OverrideResult.OR_DSC_INF_NOT_FOUND + + # Loop detection happen here by adding the visited module into stack + filelist.append(list_path) + + # Look for a comment line that starts with Override + with open(filepath, "r") as my_file: + for Line in my_file : + lineno = lineno + 1 + Line = Line.strip() + if not Line.startswith('#'): + continue + + CommentLine = Line.strip('#').split(':') + if (len(CommentLine) != 2) or\ + ((CommentLine[0].strip().lower() != 'override') and\ + (CommentLine[0].strip().lower() != 'track')): + continue + + # Process the override content, 1. Bail on bad data; 2. Print on formatted data (matched or not) + tagtype = CommentLine[0].strip().lower() + m_result = self.override_process_line(thebuilder, CommentLine[1], filepath, filelist, modulenode, status, tagtype) + + if CommentLine[0].strip().lower() == 'override': + # For override tags, the hash has to match + if m_result != self.OverrideResult.OR_ALL_GOOD: + result = m_result + logging.error("At Line %d: %s" %(lineno, Line)) + + elif CommentLine[0].strip().lower() == 'track': + # For track tags, ignore the tags of which inf modules are not found + trackno = trackno + 1 + if m_result == self.OverrideResult.OR_TARGET_INF_NOT_FOUND: + track_nf.append ((lineno, Line)) + logging.info("At Line %d: %s" %(lineno, Line)) + elif m_result == self.OverrideResult.OR_FILE_CHANGE: + track_fc.append([lineno, Line, modulenode.reflist[-1].path, False]) + logging.info("At Line %d: %s" %(lineno, Line)) + elif m_result != self.OverrideResult.OR_ALL_GOOD: + result = m_result + logging.error("At Line %d: %s" %(lineno, Line)) + else: + track_ag.append(modulenode.reflist[-1].path) + + if trackno != 0 and len(track_nf) == trackno: + # All track tags in this file are not found, this will enforce a failure, if not already failed + if result == self.OverrideResult.OR_ALL_GOOD: + result = self.OverrideResult.OR_TARGET_INF_NOT_FOUND + for (lineno, Line) in track_nf: + logging.error("Track tag failed to locate target module at Line %d: %s" %(lineno, Line)) + + if len(track_fc) != 0: + canceled_cnt = 0 + # Some track tags failed, see if they can be canceled out by other passed track tags + for entry in track_fc: + for all_good_line in track_ag: + if entry[2] == all_good_line: + canceled_cnt = canceled_cnt + 1 + entry[3] = True + break + if canceled_cnt != len(track_fc) and result == self.OverrideResult.OR_ALL_GOOD: + result = self.OverrideResult.OR_FILE_CHANGE + + for (lineno, Line, _, canceled) in track_fc: + if not canceled: + logging.error("Track tag failed to match module hash at Line %d: %s" %(lineno, Line)) + + # Revert this visitied indicator after this branch is done searching + filelist.remove(list_path) + return result + # END: override_detect_process(self, thebuilder, filepath, filelist, modulenode, status) + + # Process the comment line that starts with Override + # overridecnt: Content of Override record, should include the content after "Override:" + # filepath: the absolute path to the overriding module's inf file + # filelist: the stack of files collected during a dfs for loop detection, should be absolute path and lower case all the time + # modulenode: Module node of this "filepath" module + # status: tuple that contains the count for succeeded modules scanned and total scanned + def override_process_line(self, thebuilder, overridecnt, filepath, filelist, modulenode, status, tagtype): + # Prepare the potential node and update total processed number here + m_node = self.ModuleNode("", self.OverrideResult.OR_ALL_GOOD, 0) + modulenode.reflist.append(m_node) + status[1] = status[1] + 1 + + # Handle tail comments and/or empty spaces + EndIndex = overridecnt.find('#') + EndIndex = EndIndex if (EndIndex != -1) else len(overridecnt) + + OverrideEntry = overridecnt[0:EndIndex].split('|') + + # Step 1: Check version and number of blocks in this entry + EntryVersion = 0 + try: + EntryVersion = int(OverrideEntry[0]) + except ValueError: + logging.error("Inf Override Parse Error, override parameter has invalid version %s" %(OverrideEntry[0])) + result = self.OverrideResult.OR_INVALID_FORMAT + m_node.status = result + return result + + # Verify this is a known version and has valid number of entries + version_match = False + for VERSION_FORMAT in FORMAT_VERSIONS: + if len(VERSION_FORMAT) < 2: + logging.warning("Invalid formatted version: " + str(VERSION_FORMAT)) + continue + if EntryVersion == VERSION_FORMAT[0] and len(OverrideEntry) == VERSION_FORMAT[1]: + version_match = VERSION_FORMAT + break + if version_match == False: + logging.error(f"Inf Override Unrecognized Version {EntryVersion} or corrupted format ({len(OverrideEntry)}) in this entry: {filepath}") + result = self.OverrideResult.OR_VER_UNRECOG + m_node.status = result + return result + + if version_match[0] == 1: + return self.override_process_line_with_version1(thebuilder, filelist, OverrideEntry, m_node, status, tagtype) + elif version_match[0] == 2: + return self.override_process_line_with_version2(thebuilder, filelist, OverrideEntry, m_node, status, tagtype) + else: + raise ValueError(f"Handler is not provided for {version_match}") + + # END: override_process_line(self, thebuilder, overridecnt, filepath, filelist, modulenode, status) + + def override_process_line_with_version1(self, thebuilder, filelist, OverrideEntry, m_node, status, tagtype): + EntryVersion = 1 + # Step 2: Process the path to overridden module + # Normalize the path to support different slashes, then strip the initial '\\' to make sure os.path.join will work correctly + overriddenpath = os.path.normpath(OverrideEntry[1].strip()).strip('\\') + fullpath = os.path.normpath(thebuilder.mws.join(thebuilder.ws, overriddenpath)) + # Search overridden module in workspace + if not os.path.isfile(fullpath) and not os.path.isdir(fullpath): + logging.info("Inf Overridden File/Path Not Found in Workspace or Packages_Path: %s" %(overriddenpath)) + result = self.OverrideResult.OR_TARGET_INF_NOT_FOUND + m_node.path = overriddenpath + m_node.status = result + return result + + # Step 3: Grep hash entry + EntryHash = OverrideEntry[2].strip() + + # Step 4: Parse the time of hash generation + try: + EntryTimestamp = datetime.strptime(OverrideEntry[3].strip(), "%Y-%m-%dT%H-%M-%S") + except ValueError: + logging.error("Inf Override Parse Error, override parameter has invalid timestamp %s" %(OverrideEntry[3].strip())) + result = self.OverrideResult.OR_INVALID_FORMAT + m_node.status = result + return result + + # Step 5: Calculate the hash of overridden module and compare with our record in the overriding module + res_tuple = self.override_hash_compare(thebuilder, EntryVersion, EntryHash, fullpath) + result = res_tuple.get('result') + m_node.expect_hash = res_tuple.get('hash_val') + + # Step 6: House keeping + # Process the path to workspace/package path based add it to the parent node + overridden_rel_path = self.PathTool.GetEdk2RelativePathFromAbsolutePath(fullpath) + date_delta = datetime.utcnow() - EntryTimestamp + + m_node.entry_hash = EntryHash + m_node.path = overridden_rel_path + m_node.status = result + m_node.age = date_delta.days + + if (result == self.OverrideResult.OR_ALL_GOOD): + status[0] = status[0] + 1 + else: + pnt_str = "Inf Override Hash Error: %s, expecting %s, has %s" %(self.OverrideResult.GetErrStr(result), m_node.expect_hash, m_node.entry_hash) + if tagtype == 'override': + logging.error(pnt_str) + else: + logging.info(pnt_str) + + # Step 7: Do depth-first-search for cascaded modules + m_result = self.override_detect_process(thebuilder, fullpath, filelist, m_node, status) + if (m_result != self.OverrideResult.OR_ALL_GOOD) and \ + (result == self.OverrideResult.OR_ALL_GOOD): + result = m_result + + # The result will be inherited from above function calls + return result + # END: override_process_line_version1(self, thebuilder, filelist, OverrideEntry, m_node, status) + + def override_process_line_with_version2(self, thebuilder, filelist, OverrideEntry, m_node, status, tagtype): + ''' #Version 2: #OVERRIDE : VERSION | PATH_TO_MODULE | HASH | YYYY-MM-DDThh-mm-ss | GIT_COMMIT ''' + GitHash = OverrideEntry[4].strip() + del OverrideEntry[4] + result = self.override_process_line_with_version1(thebuilder, filelist, OverrideEntry, m_node, status, tagtype) + # if we failed, do a diff of the overridden file (as long as exist) and show the output + if result != self.OverrideResult.OR_ALL_GOOD and result != self.OverrideResult.OR_TARGET_INF_NOT_FOUND: + overriddenpath = os.path.normpath(OverrideEntry[1].strip()).strip('\\') + fullpath = os.path.normpath(thebuilder.mws.join(thebuilder.ws, overriddenpath)) + if os.path.exists(fullpath): + patch = ModuleGitPatch(fullpath, GitHash) + # TODO: figure out how to get the log file + pnt_str = f"Override diff since last update at commit {GitHash}" + if tagtype == 'override': + logging.error(pnt_str) + else: + logging.info(pnt_str) + + return result + # END: override_process_line_version2(self, thebuilder, filelist, OverrideEntry, m_node, status) + + # Check override record against parsed entries + # version: Override record's version number, normally parsed from the override record line + # hash: Override record's hash field, normally parsed from the override record line, calculated by the standalone ModuleHash tool + # fullpath: the absolute path to the overridden module's inf file + def override_hash_compare(self, thebuilder, version, hash, fullpath): + result = self.OverrideResult.OR_ALL_GOOD + hash_val = '' + + # Error out the unknown version + if (version == FORMAT_VERSION_1[0]): + hash_val = ModuleHashCal(fullpath) + if (hash_val != hash): + result = self.OverrideResult.OR_FILE_CHANGE + else: + # Should not happen + result = self.OverrideResult.OR_VER_UNRECOG + return {'result':result, 'hash_val':hash_val} + # END: override_hash_compare(self, thebuilder, version, hash, fullpath) + + # Print the log after override validation is complete + # modulelist: list of modules collected while processing inf files + # status: tuple that contains the count for succeeded modules scanned and total scanned + def override_log_print(self, thebuilder, modulelist, status): + # Check and specify log file path + base_path = thebuilder.env.GetValue("BUILD_OUTPUT_BASE") + if (base_path is None): + return + + logfile = os.path.join(base_path, "OVERRIDELOG.TXT") + logfile = os.path.normpath(logfile) + if not os.path.isdir(os.path.dirname(logfile)): + os.makedirs(os.path.dirname(logfile)) + + with open(logfile, 'w') as log: + log.write("Platform: %s\n" %(thebuilder.env.GetValue("PRODUCT_NAME"))) + log.write("Version: %s\n" %(thebuilder.env.GetValue("BLD_*_BUILDID_STRING"))) + log.write("Date: %s\n" %(datetime.utcnow().strftime("%Y-%m-%dT%H-%M-%S"))) + log.write("Commit: %s\n" %(thebuilder.env.GetValue("BLD_*_BUILDSHA"))) + log.write("State: %d/%d\n" %(status[0], status[1])) + + log.write("\n") + log.write("Overrides\n") + log.write("----------------------------------------------------------------\n") + log.write("\n") + + for node in modulelist: + # Pass in a "stack" into the function for loop detection while doing dfs + stack = [] + log.write("OVERRIDER: %s\n" %(node.path)) + log.write("ORIGINALS:\n") + self.node_dfs(thebuilder, node, stack, log) + log.write("\n") + + logfile = logfile.replace('\\', '/') + logging.critical("Override Log file at %s" %(logfile)) + # END: override_log_print(self, thebuilder, modulelist, status) + + # Traverse through the collect structure and print log + # node: Module Node representing the overriding module + # stack: the stack of paths collected during a dfs for loop detection, should be absolute path and lower case all the time + # log: log file object, must be readily open for file write when called + def node_dfs(self, thebuilder, node, stack, log): + fullpath = os.path.normpath(thebuilder.mws.join(thebuilder.ws, node.path)).lower() + if (node.path in stack): + return + stack.append(fullpath) + + for m_node in node.reflist: + list_len = len(stack) + str = "\t"*list_len+"+ %s | %s | %d days\n" %(m_node.path, self.OverrideResult.GetErrStr(m_node.status), m_node.age) + if (m_node.status == self.OverrideResult.OR_ALL_GOOD): + log.write(str) + self.node_dfs(thebuilder, m_node, stack, log) + elif (m_node.status == self.OverrideResult.OR_FILE_CHANGE): + log.write(str) + log.write("\t"*list_len+"| \tCurrent State: %s | Last Fingerprint: %s\n" %(m_node.expect_hash, m_node.entry_hash)) + self.node_dfs(thebuilder, m_node, stack, log) + else: + log.write("\t"*list_len+"+ %s | %s\n" % (m_node.path, self.OverrideResult.GetErrStr(m_node.status))) + + stack.remove(fullpath) + # END: node_dfs(self, thebuilder, node, stack, log) + + # Create a list of inf files that is included in a dsc file (including !Include entries) + def get_dsc_inf_list(self, thebuilder): + InfFileList = [] + + # Dsc parser is used in this instance + logging.debug("Parse Active Platform DSC file") + input_vars = thebuilder.env.GetAllBuildKeyValues() + input_vars["TARGET"] = thebuilder.env.GetValue("TARGET") + dscp = DscParser().SetBaseAbsPath(thebuilder.ws).SetPackagePaths(thebuilder.pp.split(os.pathsep)).SetInputVars(input_vars) + plat_dsc = thebuilder.env.GetValue("ACTIVE_PLATFORM") + if (plat_dsc is None): + return InfFileList + + # Parse the DSC + pa = thebuilder.mws.join(thebuilder.ws, plat_dsc) + dscp.ParseFile(pa) + # Add the DSC itself (including all the includes) + InfFileList.extend(dscp.GetAllDscPaths()) + # Add the FDF + if "FLASH_DEFINITION" in dscp.LocalVars: + fd = thebuilder.mws.join(thebuilder.ws, dscp.LocalVars["FLASH_DEFINITION"]) + InfFileList.append(fd) + # Here we collect all the reference libraries, IA-32 modules, x64 modules and other modules + if (dscp.Parsed) : + for lib in dscp.Libs: + InfFileList.append(lib) + for ThreeMod in dscp.ThreeMods: + InfFileList.append(ThreeMod) + for SixMod in dscp.SixMods: + InfFileList.append(SixMod) + for OtherMod in dscp.OtherMods: + InfFileList.append(OtherMod) + return InfFileList + # END: get_dsc_inf_list(self, thebuilder) +except ImportError: + pass + +# This calculates the md5 for the inf file as well as all the first order include source files +# path: the absolute path to the module's inf file +def ModuleHashCal(path): + + sourcefileList = [] + binaryfileList = [] + hash_obj = hashlib.md5() + + # Find the specific line of Sources section + folderpath = os.path.dirname(path) + + if os.path.isdir(path): + # Collect all files in this folder to the list + for subdir, _, files in os.walk(path): + for file in files: + sourcefileList.append(os.path.join(subdir, file)) + else: + sourcefileList.append(path) + + if path.lower().endswith(".inf") and os.path.isfile(path): + + # Use InfParser to parse sources section + ip = InfParser() + ip.ParseFile(path) + + # Add all referenced source files in addition to our inf file list + for source in ip.Sources: + sourcefileList.append(os.path.normpath(os.path.join(folderpath, source))) + + # Add all referenced binary files to our binary file list + for binary in ip.Binaries: + binaryfileList.append(os.path.normpath(os.path.join(folderpath, binary))) + + for sfile in sourcefileList: + #print('Calculated: %s' %(sfile)) #Debug only + with open(sfile, 'rb') as entry: + # replace \r\n with \n to take care of line terminators + hash_obj.update(entry.read().replace(b'\r\n', b'\n')) + + for bfile in binaryfileList: + #print('Calculated: %s' %(bfile)) #Debug only + with open(bfile, 'rb') as entry: + hash_obj.update(entry.read()) + + result = hash_obj.hexdigest() + return result + +def ModuleGitPatch(path, git_hash): + ''' return a git patch of the given file since the hash ''' + GitOutput = io.StringIO() + # TODO - let this go to console so we get colors + path_dir = os.path.dirname(path) + ret = RunCmd("git", f"diff {git_hash} {path}", workingdir=path_dir, outstream=GitOutput) + if ret != 0: + return "" + GitOutput.seek(0) + result = [] + for line in GitOutput.readlines(): + result.append(line.strip()) + return "\n".join(result) + +def ModuleGitHash(path): + ''' gets the current git hash of the given directory that path is ''' + abspath_dir = os.path.dirname(os.path.abspath(path)) + git_stream = StringIO() + ret = RunCmd("git", "rev-parse --verify HEAD", workingdir=abspath_dir, outstream=git_stream) + if ret != 0: + return None + git_stream.seek(0) + git_hash = git_stream.readline().strip() + if git_hash.count(" ") != 0: + raise RuntimeError("Unable to get GIT HASH for: " + abspath_dir) + return git_hash + +# Setup import and argument parser +def path_parse(): + + parser = argparse.ArgumentParser() + + parser.add_argument ( + '-w', '--workspace', dest = 'WorkSpace', required = True, type=str, + help = '''Specify the absolute path to your workspace by passing -w WORKSPACE or --workspace WORKSPACE.''' + ) + group = parser.add_mutually_exclusive_group(required=True) + group.add_argument ( + '-m', '--modulepath', dest = 'ModulePath', type=str, + help = '''Specify the absolute path to your module by passing -m Path/To/Module.inf or --modulepath Path/To/Module.inf.''' + ) + group.add_argument ( + '-t', '--targetpath', dest = 'TargetPath', type=str, + help = '''Specify the absolute path to your target module/file/folder by passing t Path/To/Target or --targetpath Path/To/Target.''' + ) + group.add_argument ( + '-r', '--regenpath', dest = 'RegenPath', type=str, + help = '''Specify the absolute path to an inf with existing overrides to regen by passing r Path/To/Target or --regenpath Path/To/Target.''' + ) + parser.add_argument ( + '-p', '--packagepath', dest = 'RegenPackagePath', nargs="*", default=[], + help = '''Specify the packages path to be used to resolve relative paths when using --regenpath. ignored otherwise. Workspace is always included.''' + ) + parser.add_argument ( + '-v', '--version', dest = 'Version', default= 2, type=int, + help = '''This is the version of the override hash to produce (currently only 1 and 2 are valid)''' + ) + parser.add_argument ( + '--track', action="store_true", dest = 'Track', default= False, + help = '''Indicate whether to create a track tag or override tag. Track tags will be treated as ignorable if the + overridden modules are not found. However, for each module that contains track tags, at least one tracked modules + has to be found, otherwise build will fail. By default, all tags will be generated as override tags.''' + ) + + Paths = parser.parse_args() + # pre-process the parsed paths to abspath + Paths.WorkSpace = os.path.abspath(Paths.WorkSpace) + if Paths.TargetPath is not None: + Paths.TargetPath = os.path.abspath(Paths.TargetPath) + + if Paths.ModulePath is not None: + Paths.TargetPath = os.path.abspath(Paths.ModulePath) + if not os.path.isfile(Paths.TargetPath): + raise RuntimeError("Module path is invalid.") + + if Paths.Version < 1 or Paths.Version > len(FORMAT_VERSIONS): + raise RuntimeError("Version is invalid") + + if not os.path.isdir(Paths.WorkSpace): + raise RuntimeError("Workspace path is invalid.") + if Paths.TargetPath is not None: + if not os.path.isfile(Paths.TargetPath) and not os.path.isdir(Paths.TargetPath): + raise RuntimeError("Module path is invalid.") + # Needs to strip os.sep is to take care of the root path case + # For a folder, this will do nothing on a formatted abspath + # For a drive root, this will rip off the os.sep + if not os.path.normcase(Paths.TargetPath).startswith(os.path.normcase(Paths.WorkSpace.rstrip(os.sep)) + os.sep): + raise RuntimeError("Module is not within specified Workspace.") + + if Paths.RegenPath is not None: + if not os.path.isfile(Paths.RegenPath): + raise RuntimeError("Regen path is invalid.") + # Needs to strip os.sep is to take care of the root path case + # For a folder, this will do nothing on a formatted abspath + # For a drive root, this will rip off the os.sep + if not os.path.normcase(Paths.RegenPath).startswith(os.path.normcase(Paths.WorkSpace.rstrip(os.sep)) + os.sep): + raise RuntimeError("Module is not within specified Workspace.") + + return Paths + +################################################ +# This plugin python file is also +# a command line tool +# +################################################ +if __name__ == '__main__': + + from edk2toollib.uefi.edk2.parsers.inf_parser import InfParser + from edk2toollib.uefi.edk2.path_utilities import Edk2Path + + # Parse required paths passed from cmd line arguments + Paths = path_parse() + + # check if we are asked to update an .inf file "in-place" + if (Paths.RegenPath is not None): + pathtool = Edk2Path(Paths.WorkSpace, Paths.RegenPackagePath) + + v1_regex = re.compile(r"#(Override|Track) : (.*?) \| (.*?) \| (.*?) \| (.*?)") + v2_regex = re.compile(r"#(Override|Track) : (.*?) \| (.*?) \| (.*?) \| (.*?) \| (.*?)") + with open (Paths.RegenPath) as fd: + RegenInfData = fd.read() + + RegenInfOutData = "" + for line in RegenInfData.splitlines (True): + match = v1_regex.match(line) + if match is None: + match = v2_regex.match(line) + + if match is not None: + rel_path = match.group(3) + abs_path = pathtool.GetAbsolutePathOnThisSystemFromEdk2RelativePath(rel_path) + if abs_path is not None: + mod_hash = ModuleHashCal(abs_path) + # only update the line if the hash has changed - this ensures the timestamp tracks actual changes rather than last time it was run. + if (mod_hash != match.group(4)): + VERSION_INDEX = Paths.Version - 1 + + if VERSION_INDEX == 0: + line = '#%s : %08d | %s | %s | %s\n' % (match.group(1), FORMAT_VERSION_1[0], rel_path, mod_hash, datetime.utcnow().strftime("%Y-%m-%dT%H-%M-%S")) + elif VERSION_INDEX == 1: + git_hash = ModuleGitHash(abs_path) + line = '#%s : %08d | %s | %s | %s | %s\n' % (match.group(1), FORMAT_VERSION_2[0], rel_path, mod_hash, datetime.utcnow().strftime("%Y-%m-%dT%H-%M-%S"), git_hash) + print("Updating:\n" + line) + else: + print(f"Warning: Could not resolve relative path {rel_path}. Override line not updated.\n") + + RegenInfOutData += line + + with open (Paths.RegenPath, "w") as fd: + fd.write(RegenInfOutData) + + else: + dummy_list = [] + pathtool = Edk2Path(Paths.WorkSpace, dummy_list) + + # Generate and print the override for pasting into the file. + # Use absolute module path to find package path + pkg_path = pathtool.GetContainingPackage(Paths.TargetPath) + rel_path = Paths.TargetPath[Paths.TargetPath.find(pkg_path):] + + rel_path = rel_path.replace('\\', '/') + mod_hash = ModuleHashCal(Paths.TargetPath) + + VERSION_INDEX = Paths.Version - 1 + + if VERSION_INDEX == 0: + print("Copy and paste the following line(s) to your overrider inf file(s):\n") + print('#%s : %08d | %s | %s | %s' % ("Override" if not Paths.Track else "Track", FORMAT_VERSION_1[0], rel_path, mod_hash, datetime.utcnow().strftime("%Y-%m-%dT%H-%M-%S"))) + + elif VERSION_INDEX == 1: + git_hash = ModuleGitHash(Paths.TargetPath) + print("Copy and paste the following line(s) to your overrider inf file(s):\n") + print('#%s : %08d | %s | %s | %s | %s' % ("Override" if not Paths.Track else "Track", FORMAT_VERSION_2[0], rel_path, mod_hash, datetime.utcnow().strftime("%Y-%m-%dT%H-%M-%S"), git_hash)) diff --git a/BaseTools/Plugin/Sample/HelloWorld.py b/BaseTools/Plugin/Sample/HelloWorld.py index 8ce8c906ae..71220b84cd 100644 --- a/BaseTools/Plugin/Sample/HelloWorld.py +++ b/BaseTools/Plugin/Sample/HelloWorld.py @@ -1,43 +1,43 @@ -## @file HelloWorld.py -# Sample Project Mu pre/post build plugin -## -# Copyright (c) Microsoft Corporation. All rights reserved. -# SPDX-License-Identifier: BSD-2-Clause-Patent -# -# All rights reserved. -# Redistribution and use in source and binary forms, with or without -# modification, are permitted provided that the following conditions are met: -# 1. Redistributions of source code must retain the above copyright notice, -# this list of conditions and the following disclaimer. -# 2. Redistributions in binary form must reproduce the above copyright notice, -# this list of conditions and the following disclaimer in the documentation -# and/or other materials provided with the distribution. -# -# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. -# IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, -# INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, -# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF -# LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE -# OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF -# ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -## -### -from edk2toolext.environment.plugintypes.uefi_helper_plugin import IUefiHelperPlugin -import logging - -class HelloWorld(IUefiBuildPlugin): - - def do_post_build(self, thebuilder): - t = "PLUGIN HelloWorld: Hello World! - Post Build Plugin Hook" - print(t) - logging.debug(t) - return 0 - - def do_pre_build(self, thebuilder): - t ="PLUGIN HelloWorld: Hello World! - Pre Build Plugin Hook" - print(t) - logging.debug(t) - return 0 +## @file HelloWorld.py +# Sample Project Mu pre/post build plugin +## +# Copyright (c) Microsoft Corporation. All rights reserved. +# SPDX-License-Identifier: BSD-2-Clause-Patent +# +# All rights reserved. +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are met: +# 1. Redistributions of source code must retain the above copyright notice, +# this list of conditions and the following disclaimer. +# 2. Redistributions in binary form must reproduce the above copyright notice, +# this list of conditions and the following disclaimer in the documentation +# and/or other materials provided with the distribution. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. +# IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, +# INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, +# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF +# LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE +# OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF +# ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +## +### +from edk2toolext.environment.plugintypes.uefi_helper_plugin import IUefiHelperPlugin +import logging + +class HelloWorld(IUefiBuildPlugin): + + def do_post_build(self, thebuilder): + t = "PLUGIN HelloWorld: Hello World! - Post Build Plugin Hook" + print(t) + logging.debug(t) + return 0 + + def do_pre_build(self, thebuilder): + t ="PLUGIN HelloWorld: Hello World! - Pre Build Plugin Hook" + print(t) + logging.debug(t) + return 0 diff --git a/BaseTools/Plugin/WindowsCapsuleSupportHelper/WindowsCapsuleSupportHelper.py b/BaseTools/Plugin/WindowsCapsuleSupportHelper/WindowsCapsuleSupportHelper.py index 90edc82daa..ff78080ef1 100644 --- a/BaseTools/Plugin/WindowsCapsuleSupportHelper/WindowsCapsuleSupportHelper.py +++ b/BaseTools/Plugin/WindowsCapsuleSupportHelper/WindowsCapsuleSupportHelper.py @@ -1,62 +1,62 @@ -## -# UefiBuild Plugin that supports Window Capsule files based on the -# Windows Firmware Update Platform spec. -# Creates INF, Cat, and then signs it -# -# Copyright (c) Microsoft Corporation. All rights reserved. -# SPDX-License-Identifier: BSD-2-Clause-Patent -## - -import sys -import re -import datetime -import os -import logging -from edk2toolext.environment.plugintypes.uefi_helper_plugin import IUefiHelperPlugin -from edk2toollib.windows.capsule.cat_generator import * -from edk2toollib.windows.capsule.inf_generator import * -from edk2toollib.utility_functions import CatalogSignWithSignTool -from edk2toollib.windows.locate_tools import FindToolInWinSdk - - -class WindowsCapsuleSupportHelper(IUefiHelperPlugin): - - def RegisterHelpers(self, obj): - fp = os.path.abspath(__file__) - obj.Register("PackageWindowsCapsuleFiles", WindowsCapsuleSupportHelper.PackageWindowsCapsuleFiles, fp) - - - @staticmethod - def PackageWindowsCapsuleFiles(OutputFolder, ProductName, ProductFmpGuid, CapsuleVersion_DotString, - CapsuleVersion_HexString, ProductFwProvider, ProductFwMfgName, ProductFwDesc, CapsuleFileName, PfxFile=None, PfxPass=None, - Rollback=False, Arch='amd64', OperatingSystem_String='Win10'): - - logging.debug("CapsulePackage: Create Windows Capsule Files") - - #Make INF - InfFilePath = os.path.join(OutputFolder, ProductName + ".inf") - InfTool = InfGenerator(ProductName, ProductFwProvider, ProductFmpGuid, Arch, ProductFwDesc, CapsuleVersion_DotString, CapsuleVersion_HexString) - InfTool.Manufacturer = ProductFwMfgName #optional - ret = InfTool.MakeInf(InfFilePath, CapsuleFileName, Rollback) - if(ret != 0): - raise Exception("CreateWindowsInf Failed with errorcode %d" % ret) - - #Make CAT - CatFilePath = os.path.realpath(os.path.join(OutputFolder, ProductName + ".cat")) - CatTool = CatGenerator(Arch, OperatingSystem_String) - ret = CatTool.MakeCat(CatFilePath) - - if(ret != 0): - raise Exception("Creating Cat file Failed with errorcode %d" % ret) - - if(PfxFile is not None): - #Find Signtool - SignToolPath = FindToolInWinSdk("signtool.exe") - if not os.path.exists(SignToolPath): - raise Exception("Can't find signtool on this machine.") - #dev sign the cat file - ret = CatalogSignWithSignTool(SignToolPath, CatFilePath, PfxFile, PfxPass) - if(ret != 0): - raise Exception("Signing Cat file Failed with errorcode %d" % ret) - - return ret +## +# UefiBuild Plugin that supports Window Capsule files based on the +# Windows Firmware Update Platform spec. +# Creates INF, Cat, and then signs it +# +# Copyright (c) Microsoft Corporation. All rights reserved. +# SPDX-License-Identifier: BSD-2-Clause-Patent +## + +import sys +import re +import datetime +import os +import logging +from edk2toolext.environment.plugintypes.uefi_helper_plugin import IUefiHelperPlugin +from edk2toollib.windows.capsule.cat_generator import * +from edk2toollib.windows.capsule.inf_generator import * +from edk2toollib.utility_functions import CatalogSignWithSignTool +from edk2toollib.windows.locate_tools import FindToolInWinSdk + + +class WindowsCapsuleSupportHelper(IUefiHelperPlugin): + + def RegisterHelpers(self, obj): + fp = os.path.abspath(__file__) + obj.Register("PackageWindowsCapsuleFiles", WindowsCapsuleSupportHelper.PackageWindowsCapsuleFiles, fp) + + + @staticmethod + def PackageWindowsCapsuleFiles(OutputFolder, ProductName, ProductFmpGuid, CapsuleVersion_DotString, + CapsuleVersion_HexString, ProductFwProvider, ProductFwMfgName, ProductFwDesc, CapsuleFileName, PfxFile=None, PfxPass=None, + Rollback=False, Arch='amd64', OperatingSystem_String='Win10'): + + logging.debug("CapsulePackage: Create Windows Capsule Files") + + #Make INF + InfFilePath = os.path.join(OutputFolder, ProductName + ".inf") + InfTool = InfGenerator(ProductName, ProductFwProvider, ProductFmpGuid, Arch, ProductFwDesc, CapsuleVersion_DotString, CapsuleVersion_HexString) + InfTool.Manufacturer = ProductFwMfgName #optional + ret = InfTool.MakeInf(InfFilePath, CapsuleFileName, Rollback) + if(ret != 0): + raise Exception("CreateWindowsInf Failed with errorcode %d" % ret) + + #Make CAT + CatFilePath = os.path.realpath(os.path.join(OutputFolder, ProductName + ".cat")) + CatTool = CatGenerator(Arch, OperatingSystem_String) + ret = CatTool.MakeCat(CatFilePath) + + if(ret != 0): + raise Exception("Creating Cat file Failed with errorcode %d" % ret) + + if(PfxFile is not None): + #Find Signtool + SignToolPath = FindToolInWinSdk("signtool.exe") + if not os.path.exists(SignToolPath): + raise Exception("Can't find signtool on this machine.") + #dev sign the cat file + ret = CatalogSignWithSignTool(SignToolPath, CatFilePath, PfxFile, PfxPass) + if(ret != 0): + raise Exception("Signing Cat file Failed with errorcode %d" % ret) + + return ret diff --git a/BaseTools/Scripts/GenFmpImageAuth.py b/BaseTools/Scripts/GenFmpImageAuth.py index 9efd3f87d0..155399a656 100644 --- a/BaseTools/Scripts/GenFmpImageAuth.py +++ b/BaseTools/Scripts/GenFmpImageAuth.py @@ -1,231 +1,231 @@ -## -## Script to Generate a UEFI 2.4B FMP compliant Image Auth Header wrapped -## around the payload file. -## -## For dev purposes this script takes a payload file and signs it and encapsulates it -## in the correct headers. This file is then ready to be put into a FMP capsule. -## -## For production use this script has a production flag and a DetachedSignature parameter -## which allows the signing to be done offline. -## -## General process: -## Phase 1: Create payload file by combining payload and monotonic count -## Phase 2: Sign it using signtool -## Phase 3: Wrap payload in headers to create final FMP Image header/payload -## -## -## Copyright (c) Microsoft Corporation. All rights reserved. -## SPDX-License-Identifier: BSD-2-Clause-Patent -## - - -import os, sys -from optparse import OptionParser -import logging -import datetime -import struct -import subprocess -import uuid -from edk2toollib.utility_functions import RunCmd -from edk2toollib.utility_functions import DetachedSignWithSignTool - - -gPhase3PackageOnly = False - -# -#main script function -# -def main(): - parser = OptionParser() - #Output debug log - parser.add_option("-l", dest="OutputLog", help="Create an output log file: ie -l out.txt", default=None) - parser.add_option("-o", "--OutputFile", dest="OutputFile", help="Result/Output file", default=None) - parser.add_option("-p", "--payload", dest="Payload", help="Input unsigned payload file", default=None) - parser.add_option("--production", dest="ProductionSign", action="store_true", help="Production Sign Process (no dev signing)", default=False) - parser.add_option("-m", dest="MonotonicCount", help="Monotonic Count Value", default=0) - parser.add_option("-s", dest="DetachedSignature", help="Detached Signature file (production signed phase 3 step only)", default=None) - parser.add_option("--pfxfile", dest="PfxPath", help="Path to PFX file for dev signing", default=None) - parser.add_option("--pfxpass", dest="PfxPass", help="Optional - PFX password for dev signing with PFX cert", default=None) - parser.add_option("--eku", dest="Eku", help="Option -specify EKU value to pass to signtool if required", default=None) - parser.add_option("--SignTool", dest="SignToolPath", help="Path to signtool.exe") - #Turn on dubug level logging - parser.add_option("--debug", action="store_true", dest="debug", help="turn on debug logging level for file log", default=False) - parser.add_option("--dirty", action="store_true", dest="dirty", help="turn on dirty flag to keep intermediate files. Default is to delete them.", default=False) - - (options, args) = parser.parse_args() - - #setup file based logging if outputReport specified - if(options.OutputLog): - if(len(options.OutputLog) < 2): - logging.critical("the output log file parameter is invalid") - return -2 - else: - #setup file based logging - filelogger = logging.FileHandler(filename=options.OutputLog, mode='w') - if(options.debug): - filelogger.setLevel(logging.DEBUG) - else: - filelogger.setLevel(logging.INFO) - - filelogger.setFormatter(formatter) - logging.getLogger('').addHandler(filelogger) - - logging.info("Log Started: " + datetime.datetime.strftime(datetime.datetime.now(), "%A, %B %d, %Y %I:%M%p" )) - - #check for valid files - if not options.Payload: - logging.critical("No Payload file specified") - return -1 - - if not os.path.isfile(options.Payload): - logging.critical("Invalid Path to payload file") - return -2 - - if not options.DetachedSignature: - logging.debug("No Detached Signature File.") - else: - logging.debug("Parameter for detached signature file specified. " + options.DetachedSignature) - logging.debug("Entering Phase2-PackageOnly Mode") - global gPhase3PackageOnly - gPhase3PackageOnly = True - - if not options.OutputFile: - logging.debug("No output file specified. Using default. AuthPayload.FmImageAuth") - options.OutputFile = "AuthPayload.FmImageAuth" - - if(not gPhase3PackageOnly and not options.ProductionSign): - #must have a pfx file - if not options.PfxPath: - logging.critical("No Pfx File given.") - return -7 - if not os.path.isfile(options.PfxPath): - logging.critical("Invalid PFX Path. File doesn't exist. " + options.PfxPath) - return -6 - - logging.debug("Using PFX file: " + str(options.PfxPath)) - - - logging.debug("Production Mode: " + str(options.ProductionSign)) - logging.debug("Monotonic Count: " + str(options.MonotonicCount)) - logging.debug("Output File: " + str(options.OutputFile)) - logging.debug("Dirty Mode: " + str(options.dirty)) - - FileToSign = os.path.join("payload.Temp.ToBeSigned") - - - - #if not doing phase2 only then we need to do presign stuff - if not gPhase3PackageOnly: - #Since we are not in phase3packageonly mode we know no DetachedSignature file speficied. Set to the default output. - OutputDir = os.path.dirname(os.path.abspath(options.OutputFile)) - logging.debug("Temp files will be written to: " + str(OutputDir)) - - #change the path to temp location - FileToSign = os.path.join(OutputDir, FileToSign) - options.DetachedSignature = FileToSign + ".p7" - - #Create a temp file with payload + monotonic count - f = open(FileToSign, "wb") - pf = open(options.Payload, "rb") - f.write(pf.read()) - mc = struct.pack("Q", int(options.MonotonicCount)) - f.write(mc) - pf.close() - f.close() - - - #if not doing production signing then sign it - if not options.ProductionSign: - #check sign tool - if(os.path.exists(options.SignToolPath)): - logging.debug("Signtool.exe found at location: " + options.SignToolPath) - else: - logging.critical("Can't find signtool at location: " + options.SignToolPath) - return -5 - - ret = DetachedSignWithSignTool( - options.SignToolPath, - FileToSign, - options.DetachedSignature, - options.PfxPath, - PfxPass=options.PfxPass, - Eku=options.Eku - ) - - if ret != 0: - logging.critical("DetachedSignWithSignTool Failed: " + str(ret)) - return ret - - if not options.dirty: - logging.debug("Delete temp file: " + str(FileToSign)) - os.remove(FileToSign) - - - else: - logging.critical("File To Production Sign Created: " + FileToSign) - return 0 - - #package the final output (phase 3) - wcugSize = os.path.getsize(options.DetachedSignature) - logging.debug("PKCS7 Signed Data is size: " + str(wcugSize)) - wcugSize = wcugSize + 4 + 2 + 2 + 16 # matches the hdr + guid below - - # - #Header layout and structures defined in UEFI 2.4 Errata B. - # - - #EFI_FIRMWARE_IMAGE_AUTH - #UINT64 Monotonic Count <--count value used when signing it - #WIN_CERTIFICATE_UEFI_GUID AuthInfo - #WIN_CERTIFICATE Hdr - #UINT32 dwLength <--Length of cert header - #UINT16 wRevision <--Revision level of win cert current 0x0200 - #UINT16 wCertType <--WIN_CERT_TYPE_EFI_GUID 0x0EF1 - #EFI_GUID CertType <--gEfiCertPkcs7Guid = { 0x4aafd29d, 0x68df, 0x49ee, {0x8a, 0xa9, 0x34, 0x7d, 0x37, 0x56, 0x65, 0xa7 }} - #UINT8[] PKCS7 SignedData <--DetachedSignature from signtool - #UINT8[] Payload <--Payload file - - #struct format for the header - header = struct.pack("QLHH", int(options.MonotonicCount), int(wcugSize), int("200", 16), int("0EF1", 16)) - pkcsguid = uuid.UUID('{4aafd29d-68df-49ee-8aa9-347d375665a7}') - - f = open(options.OutputFile, "wb") - f.write(header) - f.write(pkcsguid.bytes_le) - sd = open(options.DetachedSignature, "rb") - f.write(sd.read()) - sd.close() - p = open(options.Payload, "rb") - f.write(p.read()) - p.close() - f.close() - logging.critical("Final FMP compliant Authenticated Payload Image File created:\n " + os.path.abspath(str(options.OutputFile))) - - #if user wants temp files deleted and didn't pass in the p7 file....then delete it now - if not options.dirty: - if not gPhase3PackageOnly: - logging.debug("Delete temp file: " + str(options.DetachedSignature)) - os.remove(options.DetachedSignature) - - - return 0 - - -if __name__ == '__main__': - #setup main console as logger - logger = logging.getLogger('') - logger.setLevel(logging.DEBUG) - formatter = logging.Formatter("%(levelname)s - %(message)s") - console = logging.StreamHandler() - console.setLevel(logging.CRITICAL) - console.setFormatter(formatter) - logger.addHandler(console) - - #call main worker function - retcode = main() - - if retcode != 0: - logging.critical("Failed. Return Code: %i" % retcode) - #end logging - logging.shutdown() - sys.exit(retcode) +## +## Script to Generate a UEFI 2.4B FMP compliant Image Auth Header wrapped +## around the payload file. +## +## For dev purposes this script takes a payload file and signs it and encapsulates it +## in the correct headers. This file is then ready to be put into a FMP capsule. +## +## For production use this script has a production flag and a DetachedSignature parameter +## which allows the signing to be done offline. +## +## General process: +## Phase 1: Create payload file by combining payload and monotonic count +## Phase 2: Sign it using signtool +## Phase 3: Wrap payload in headers to create final FMP Image header/payload +## +## +## Copyright (c) Microsoft Corporation. All rights reserved. +## SPDX-License-Identifier: BSD-2-Clause-Patent +## + + +import os, sys +from optparse import OptionParser +import logging +import datetime +import struct +import subprocess +import uuid +from edk2toollib.utility_functions import RunCmd +from edk2toollib.utility_functions import DetachedSignWithSignTool + + +gPhase3PackageOnly = False + +# +#main script function +# +def main(): + parser = OptionParser() + #Output debug log + parser.add_option("-l", dest="OutputLog", help="Create an output log file: ie -l out.txt", default=None) + parser.add_option("-o", "--OutputFile", dest="OutputFile", help="Result/Output file", default=None) + parser.add_option("-p", "--payload", dest="Payload", help="Input unsigned payload file", default=None) + parser.add_option("--production", dest="ProductionSign", action="store_true", help="Production Sign Process (no dev signing)", default=False) + parser.add_option("-m", dest="MonotonicCount", help="Monotonic Count Value", default=0) + parser.add_option("-s", dest="DetachedSignature", help="Detached Signature file (production signed phase 3 step only)", default=None) + parser.add_option("--pfxfile", dest="PfxPath", help="Path to PFX file for dev signing", default=None) + parser.add_option("--pfxpass", dest="PfxPass", help="Optional - PFX password for dev signing with PFX cert", default=None) + parser.add_option("--eku", dest="Eku", help="Option -specify EKU value to pass to signtool if required", default=None) + parser.add_option("--SignTool", dest="SignToolPath", help="Path to signtool.exe") + #Turn on dubug level logging + parser.add_option("--debug", action="store_true", dest="debug", help="turn on debug logging level for file log", default=False) + parser.add_option("--dirty", action="store_true", dest="dirty", help="turn on dirty flag to keep intermediate files. Default is to delete them.", default=False) + + (options, args) = parser.parse_args() + + #setup file based logging if outputReport specified + if(options.OutputLog): + if(len(options.OutputLog) < 2): + logging.critical("the output log file parameter is invalid") + return -2 + else: + #setup file based logging + filelogger = logging.FileHandler(filename=options.OutputLog, mode='w') + if(options.debug): + filelogger.setLevel(logging.DEBUG) + else: + filelogger.setLevel(logging.INFO) + + filelogger.setFormatter(formatter) + logging.getLogger('').addHandler(filelogger) + + logging.info("Log Started: " + datetime.datetime.strftime(datetime.datetime.now(), "%A, %B %d, %Y %I:%M%p" )) + + #check for valid files + if not options.Payload: + logging.critical("No Payload file specified") + return -1 + + if not os.path.isfile(options.Payload): + logging.critical("Invalid Path to payload file") + return -2 + + if not options.DetachedSignature: + logging.debug("No Detached Signature File.") + else: + logging.debug("Parameter for detached signature file specified. " + options.DetachedSignature) + logging.debug("Entering Phase2-PackageOnly Mode") + global gPhase3PackageOnly + gPhase3PackageOnly = True + + if not options.OutputFile: + logging.debug("No output file specified. Using default. AuthPayload.FmImageAuth") + options.OutputFile = "AuthPayload.FmImageAuth" + + if(not gPhase3PackageOnly and not options.ProductionSign): + #must have a pfx file + if not options.PfxPath: + logging.critical("No Pfx File given.") + return -7 + if not os.path.isfile(options.PfxPath): + logging.critical("Invalid PFX Path. File doesn't exist. " + options.PfxPath) + return -6 + + logging.debug("Using PFX file: " + str(options.PfxPath)) + + + logging.debug("Production Mode: " + str(options.ProductionSign)) + logging.debug("Monotonic Count: " + str(options.MonotonicCount)) + logging.debug("Output File: " + str(options.OutputFile)) + logging.debug("Dirty Mode: " + str(options.dirty)) + + FileToSign = os.path.join("payload.Temp.ToBeSigned") + + + + #if not doing phase2 only then we need to do presign stuff + if not gPhase3PackageOnly: + #Since we are not in phase3packageonly mode we know no DetachedSignature file speficied. Set to the default output. + OutputDir = os.path.dirname(os.path.abspath(options.OutputFile)) + logging.debug("Temp files will be written to: " + str(OutputDir)) + + #change the path to temp location + FileToSign = os.path.join(OutputDir, FileToSign) + options.DetachedSignature = FileToSign + ".p7" + + #Create a temp file with payload + monotonic count + f = open(FileToSign, "wb") + pf = open(options.Payload, "rb") + f.write(pf.read()) + mc = struct.pack("Q", int(options.MonotonicCount)) + f.write(mc) + pf.close() + f.close() + + + #if not doing production signing then sign it + if not options.ProductionSign: + #check sign tool + if(os.path.exists(options.SignToolPath)): + logging.debug("Signtool.exe found at location: " + options.SignToolPath) + else: + logging.critical("Can't find signtool at location: " + options.SignToolPath) + return -5 + + ret = DetachedSignWithSignTool( + options.SignToolPath, + FileToSign, + options.DetachedSignature, + options.PfxPath, + PfxPass=options.PfxPass, + Eku=options.Eku + ) + + if ret != 0: + logging.critical("DetachedSignWithSignTool Failed: " + str(ret)) + return ret + + if not options.dirty: + logging.debug("Delete temp file: " + str(FileToSign)) + os.remove(FileToSign) + + + else: + logging.critical("File To Production Sign Created: " + FileToSign) + return 0 + + #package the final output (phase 3) + wcugSize = os.path.getsize(options.DetachedSignature) + logging.debug("PKCS7 Signed Data is size: " + str(wcugSize)) + wcugSize = wcugSize + 4 + 2 + 2 + 16 # matches the hdr + guid below + + # + #Header layout and structures defined in UEFI 2.4 Errata B. + # + + #EFI_FIRMWARE_IMAGE_AUTH + #UINT64 Monotonic Count <--count value used when signing it + #WIN_CERTIFICATE_UEFI_GUID AuthInfo + #WIN_CERTIFICATE Hdr + #UINT32 dwLength <--Length of cert header + #UINT16 wRevision <--Revision level of win cert current 0x0200 + #UINT16 wCertType <--WIN_CERT_TYPE_EFI_GUID 0x0EF1 + #EFI_GUID CertType <--gEfiCertPkcs7Guid = { 0x4aafd29d, 0x68df, 0x49ee, {0x8a, 0xa9, 0x34, 0x7d, 0x37, 0x56, 0x65, 0xa7 }} + #UINT8[] PKCS7 SignedData <--DetachedSignature from signtool + #UINT8[] Payload <--Payload file + + #struct format for the header + header = struct.pack("QLHH", int(options.MonotonicCount), int(wcugSize), int("200", 16), int("0EF1", 16)) + pkcsguid = uuid.UUID('{4aafd29d-68df-49ee-8aa9-347d375665a7}') + + f = open(options.OutputFile, "wb") + f.write(header) + f.write(pkcsguid.bytes_le) + sd = open(options.DetachedSignature, "rb") + f.write(sd.read()) + sd.close() + p = open(options.Payload, "rb") + f.write(p.read()) + p.close() + f.close() + logging.critical("Final FMP compliant Authenticated Payload Image File created:\n " + os.path.abspath(str(options.OutputFile))) + + #if user wants temp files deleted and didn't pass in the p7 file....then delete it now + if not options.dirty: + if not gPhase3PackageOnly: + logging.debug("Delete temp file: " + str(options.DetachedSignature)) + os.remove(options.DetachedSignature) + + + return 0 + + +if __name__ == '__main__': + #setup main console as logger + logger = logging.getLogger('') + logger.setLevel(logging.DEBUG) + formatter = logging.Formatter("%(levelname)s - %(message)s") + console = logging.StreamHandler() + console.setLevel(logging.CRITICAL) + console.setFormatter(formatter) + logger.addHandler(console) + + #call main worker function + retcode = main() + + if retcode != 0: + logging.critical("Failed. Return Code: %i" % retcode) + #end logging + logging.shutdown() + sys.exit(retcode) diff --git a/BaseTools/Scripts/WindowsCapsuleFileGen.py b/BaseTools/Scripts/WindowsCapsuleFileGen.py index 6eb6694b61..f20a3962a9 100644 --- a/BaseTools/Scripts/WindowsCapsuleFileGen.py +++ b/BaseTools/Scripts/WindowsCapsuleFileGen.py @@ -1,129 +1,129 @@ -## -# Tool to create a Windows Capsule files that complies with -# the Windows Firmware Update Platform specification. -# -# Gen INF, CAT, and then dev sign the CAT if PFX supplied. -# -# -# Copyright (c) Microsoft Corporation. All rights reserved. -# SPDX-License-Identifier: BSD-2-Clause-Patent -## - -import os -import sys -import logging -import argparse -import datetime - -from edk2toollib.windows.capsule.cat_generator import * -from edk2toollib.windows.capsule.inf_generator import * -from edk2toollib.utility_functions import CatalogSignWithSignTool - -def main(): - parser = argparse.ArgumentParser(description='Generate Windows Firmware Update Platform Files for Capsules') - parser.add_argument("name", help="Firmware Name. No spaces") - parser.add_argument("provider", help="Firmware provider listed in INF") - parser.add_argument("description", help="Firmware description listed in INF") - parser.add_argument("version_string", help="Version String in form of XX.XX.XX[.XX]") - parser.add_argument("version_hex", help="Version String in Hex 0xAABBCCDD must be representable within 32bit") - parser.add_argument("esrt_guid", help="guid string in registry format (########-####-####-####-############) for this ESRT entry") - parser.add_argument("firmware_bin_file_path", help="full path to firmware bin / capsule file") - parser.add_argument('arch', choices=InfGenerator.SUPPORTED_ARCH, help="Architecture targeted by INF and CAT") - parser.add_argument('operating_sytem', choices=CatGenerator.SUPPORTED_OS, help="operating system targeted by INF and CAT") - parser.add_argument("--mfgname", help="Manufacturer name listed in INF") - parser.add_argument("--rollback", action="store_true", dest="rollback", help="build a rollback capsule", default=False) - parser.add_argument("--pfx_file", help="Full Path to PFX file. If not set then signing will not be performed.") - parser.add_argument("--pfx_pass", help="Password for PFX file. Optional based on PFX file") - - - #Turn on dubug level logging - parser.add_argument("--debug", action="store_true", dest="debug", help="turn on debug logging level for file log", default=False) - #Output debug log - parser.add_argument("-l", dest="OutputLog", help="Create an output debug log file: ie -l out.txt", default=None) - - args = parser.parse_args() - - #setup file based logging if outputReport specified - if(args.OutputLog): - if(len(args.OutputLog) < 2): - logging.critical("the output log file parameter is invalid") - return -2 - else: - #setup file based logging - filelogger = logging.FileHandler(filename=args.OutputLog, mode='w') - if(args.debug): - filelogger.setLevel(logging.DEBUG) - else: - filelogger.setLevel(logging.INFO) - - filelogger.setFormatter(formatter) - logging.getLogger('').addHandler(filelogger) - - logging.info("Log Started: " + datetime.datetime.strftime(datetime.datetime.now(), "%A, %B %d, %Y %I:%M%p" )) - OutputFolder = os.path.dirname(args.firmware_bin_file_path) - FirmwareFile = os.path.basename(args.firmware_bin_file_path) - - logging.debug("Make INF") - #Make INF - InfFilePath = os.path.join(OutputFolder, args.name + ".inf") - InfTool = InfGenerator(args.name, args.provider, args.esrt_guid, args.arch, args.description, args.version_string, args.version_hex) - if(args.mfgname is not None): - InfTool.Manufacturer = args.mfgname #optional - ret = InfTool.MakeInf(InfFilePath, FirmwareFile, args.rollback) - if(ret != 0): - logging.critical("CreateWindowsInf Failed with errorcode %d" % ret) - return ret - - #Make CAT - CatFilePath = os.path.realpath(os.path.join(OutputFolder, args.name + ".cat")) - CatTool = CatGenerator(args.arch, args.operating_sytem) - ret = CatTool.MakeCat(CatFilePath) - - if(ret != 0): - logging.critical("Creating Cat file Failed with errorcode %d" % ret) - return ret - - if(args.pfx_file is not None): - logging.debug("PFX file set. Going to do signing") - #Find Signtool - SignToolPath = os.path.join(os.getenv("ProgramFiles(x86)"), "Windows Kits", "8.1", "bin", "x64", "signtool.exe") - if not os.path.exists(SignToolPath): - logging.debug("Failed to find 8.1 version of signtool. Trying 10") - SignToolPath = SignToolPath.replace('8.1', '10') - - if not os.path.exists(SignToolPath): - logging.critical("Can't find signtool on this machine.") - return -3 - #dev sign the cat file - ret = CatalogSignWithSignTool(SignToolPath, CatFilePath, args.pfx_file, args.pfx_pass) - if(ret != 0): - logging.critical("Signing Cat file Failed with errorcode %d" % ret) - return ret - else: - logging.info("No PFX. Not signing") - - return ret - - -#-------------------------------- -# Control starts here -# -#-------------------------------- -if __name__ == '__main__': - #setup main console as logger - logger = logging.getLogger('') - logger.setLevel(logging.DEBUG) - formatter = logging.Formatter("%(levelname)s - %(message)s") - console = logging.StreamHandler() - console.setLevel(logging.CRITICAL) - console.setFormatter(formatter) - logger.addHandler(console) - - #call main worker function - retcode = main() - - if retcode != 0: - logging.critical("Failed. Return Code: %i" % retcode) - #end logging - logging.shutdown() - sys.exit(retcode) +## +# Tool to create a Windows Capsule files that complies with +# the Windows Firmware Update Platform specification. +# +# Gen INF, CAT, and then dev sign the CAT if PFX supplied. +# +# +# Copyright (c) Microsoft Corporation. All rights reserved. +# SPDX-License-Identifier: BSD-2-Clause-Patent +## + +import os +import sys +import logging +import argparse +import datetime + +from edk2toollib.windows.capsule.cat_generator import * +from edk2toollib.windows.capsule.inf_generator import * +from edk2toollib.utility_functions import CatalogSignWithSignTool + +def main(): + parser = argparse.ArgumentParser(description='Generate Windows Firmware Update Platform Files for Capsules') + parser.add_argument("name", help="Firmware Name. No spaces") + parser.add_argument("provider", help="Firmware provider listed in INF") + parser.add_argument("description", help="Firmware description listed in INF") + parser.add_argument("version_string", help="Version String in form of XX.XX.XX[.XX]") + parser.add_argument("version_hex", help="Version String in Hex 0xAABBCCDD must be representable within 32bit") + parser.add_argument("esrt_guid", help="guid string in registry format (########-####-####-####-############) for this ESRT entry") + parser.add_argument("firmware_bin_file_path", help="full path to firmware bin / capsule file") + parser.add_argument('arch', choices=InfGenerator.SUPPORTED_ARCH, help="Architecture targeted by INF and CAT") + parser.add_argument('operating_sytem', choices=CatGenerator.SUPPORTED_OS, help="operating system targeted by INF and CAT") + parser.add_argument("--mfgname", help="Manufacturer name listed in INF") + parser.add_argument("--rollback", action="store_true", dest="rollback", help="build a rollback capsule", default=False) + parser.add_argument("--pfx_file", help="Full Path to PFX file. If not set then signing will not be performed.") + parser.add_argument("--pfx_pass", help="Password for PFX file. Optional based on PFX file") + + + #Turn on dubug level logging + parser.add_argument("--debug", action="store_true", dest="debug", help="turn on debug logging level for file log", default=False) + #Output debug log + parser.add_argument("-l", dest="OutputLog", help="Create an output debug log file: ie -l out.txt", default=None) + + args = parser.parse_args() + + #setup file based logging if outputReport specified + if(args.OutputLog): + if(len(args.OutputLog) < 2): + logging.critical("the output log file parameter is invalid") + return -2 + else: + #setup file based logging + filelogger = logging.FileHandler(filename=args.OutputLog, mode='w') + if(args.debug): + filelogger.setLevel(logging.DEBUG) + else: + filelogger.setLevel(logging.INFO) + + filelogger.setFormatter(formatter) + logging.getLogger('').addHandler(filelogger) + + logging.info("Log Started: " + datetime.datetime.strftime(datetime.datetime.now(), "%A, %B %d, %Y %I:%M%p" )) + OutputFolder = os.path.dirname(args.firmware_bin_file_path) + FirmwareFile = os.path.basename(args.firmware_bin_file_path) + + logging.debug("Make INF") + #Make INF + InfFilePath = os.path.join(OutputFolder, args.name + ".inf") + InfTool = InfGenerator(args.name, args.provider, args.esrt_guid, args.arch, args.description, args.version_string, args.version_hex) + if(args.mfgname is not None): + InfTool.Manufacturer = args.mfgname #optional + ret = InfTool.MakeInf(InfFilePath, FirmwareFile, args.rollback) + if(ret != 0): + logging.critical("CreateWindowsInf Failed with errorcode %d" % ret) + return ret + + #Make CAT + CatFilePath = os.path.realpath(os.path.join(OutputFolder, args.name + ".cat")) + CatTool = CatGenerator(args.arch, args.operating_sytem) + ret = CatTool.MakeCat(CatFilePath) + + if(ret != 0): + logging.critical("Creating Cat file Failed with errorcode %d" % ret) + return ret + + if(args.pfx_file is not None): + logging.debug("PFX file set. Going to do signing") + #Find Signtool + SignToolPath = os.path.join(os.getenv("ProgramFiles(x86)"), "Windows Kits", "8.1", "bin", "x64", "signtool.exe") + if not os.path.exists(SignToolPath): + logging.debug("Failed to find 8.1 version of signtool. Trying 10") + SignToolPath = SignToolPath.replace('8.1', '10') + + if not os.path.exists(SignToolPath): + logging.critical("Can't find signtool on this machine.") + return -3 + #dev sign the cat file + ret = CatalogSignWithSignTool(SignToolPath, CatFilePath, args.pfx_file, args.pfx_pass) + if(ret != 0): + logging.critical("Signing Cat file Failed with errorcode %d" % ret) + return ret + else: + logging.info("No PFX. Not signing") + + return ret + + +#-------------------------------- +# Control starts here +# +#-------------------------------- +if __name__ == '__main__': + #setup main console as logger + logger = logging.getLogger('') + logger.setLevel(logging.DEBUG) + formatter = logging.Formatter("%(levelname)s - %(message)s") + console = logging.StreamHandler() + console.setLevel(logging.CRITICAL) + console.setFormatter(formatter) + logger.addHandler(console) + + #call main worker function + retcode = main() + + if retcode != 0: + logging.critical("Failed. Return Code: %i" % retcode) + #end logging + logging.shutdown() + sys.exit(retcode) diff --git a/CryptoPkg/Driver/CryptoDxe.inf b/CryptoPkg/Driver/CryptoDxe.inf index 61a9082303..d268741060 100644 --- a/CryptoPkg/Driver/CryptoDxe.inf +++ b/CryptoPkg/Driver/CryptoDxe.inf @@ -1,176 +1,176 @@ -## @file -# Produces the EDK II Crypto Protocol using the library services from -# BaseCryptLib and TlsLib. -# -# Copyright (C) Microsoft Corporation. All rights reserved. -# SPDX-License-Identifier: BSD-2-Clause-Patent -# -## - -[Defines] - INF_VERSION = 0x0001001B - PI_SPECIFICATION_VERSION = 0x0001000A - BASE_NAME = CryptoDxe - MODULE_UNI_FILE = Crypto.uni - FILE_GUID = FEA01457-E381-4135-9475-C6AFD0076C61 - MODULE_TYPE = DXE_DRIVER - VERSION_STRING = 1.0 - ENTRY_POINT = CryptoDxeEntry - -# -# The following information is for reference only and not required by the build tools. -# -# VALID_ARCHITECTURES = IA32 X64 ARM AARCH64 -# - -[Sources] - Crypto.c - CryptoDxe.c - -[Packages] - MdePkg/MdePkg.dec - CryptoPkg/CryptoPkg.dec - -[LibraryClasses] - UefiDriverEntryPoint - UefiBootServicesTableLib - DebugLib - BaseCryptLib - TlsLib - -[Protocols] - gEdkiiCryptoProtocolGuid ## PRODUCES - -# MU_CHANGE -# **************************************************************************** -# AUTOGENERATED BY CryptoPkg\Driver\Packaging\generate_cryptodriver.py -# AUTOGENED AS temp_crypto_pcd.inc.inf -# DO NOT MODIFY -# GENERATED ON: 2023-02-18 14:13:45.978841 - -[Pcd] - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSha1GetContextSize # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSha1Init # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSha1Duplicate # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSha1Update # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSha1Final # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSha1HashAll # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSha256GetContextSize # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSha256Init # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSha256Duplicate # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSha256Update # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSha256Final # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSha256HashAll # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSha384GetContextSize # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSha384Init # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSha384Duplicate # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSha384Update # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSha384Final # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSha384HashAll # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSha512GetContextSize # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSha512Init # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSha512Duplicate # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSha512Update # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSha512Final # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSha512HashAll # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceParallelHash256HashAll # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSm3GetContextSize # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSm3Init # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSm3Duplicate # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSm3Update # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSm3Final # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSm3HashAll # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceHmacSha256New # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceHmacSha256Free # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceHmacSha256SetKey # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceHmacSha256Duplicate # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceHmacSha256Update # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceHmacSha256Final # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceAesGetContextSize # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceAesInit # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceAesCbcEncrypt # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceAesCbcDecrypt # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceRsaNew # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceRsaFree # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceRsaSetKey # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceRsaGetKey # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceRsaGenerateKey # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceRsaCheckKey # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceRsaPkcs1Sign # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceRsaPkcs1Verify # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceRsaPssSign # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceRsaPssVerify # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceRsaGetPrivateKeyFromPem # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceRsaGetPublicKeyFromX509 # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceX509GetSubjectName # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceX509GetCommonName # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceX509GetOrganizationName # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceX509VerifyCert # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceX509ConstructCertificate # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceX509ConstructCertificateStackV # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceX509ConstructCertificateStack # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceX509Free # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceX509StackFree # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceX509GetTBSCert # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServicePkcs5HashPassword # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServicePkcs1v2Encrypt # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServicePkcs7GetSigners # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServicePkcs7FreeSigners # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServicePkcs7GetCertificatesList # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServicePkcs7Sign # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServicePkcs7Verify # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceVerifyEKUsInPkcs7Signature # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServicePkcs7GetAttachedContent # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceAuthenticodeVerify # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceImageTimestampVerify # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceDhNew # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceDhFree # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceDhGenerateParameter # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceDhSetParameter # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceDhGenerateKey # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceDhComputeKey # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceRandomSeed # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceRandomBytes # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceHkdfSha256ExtractAndExpand # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsInitialize # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsCtxFree # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsCtxNew # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsFree # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsNew # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsInHandshake # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsDoHandshake # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsHandleAlert # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsCloseNotify # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsCtrlTrafficOut # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsCtrlTrafficIn # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsRead # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsWrite # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsSetVersion # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsSetConnectionEnd # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsSetCipherList # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsSetCompressionMethod # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsSetVerify # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsSetVerifyHost # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsSetSessionId # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsSetCaCertificate # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsSetHostPublicCert # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsSetHostPrivateKey # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsSetCertRevocationList # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsGetVersion # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsGetConnectionEnd # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsGetCurrentCipher # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsGetCurrentCompressionId # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsGetVerify # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsGetSessionId # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsGetClientRandom # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsGetServerRandom # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsGetKeyMaterial # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsGetCaCertificate # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsGetHostPublicCert # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsGetHostPrivateKey # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsGetCertRevocationList # CONSUMES -# AUTOGEN ENDS -# **************************************************************************** - -[Depex] - TRUE +## @file +# Produces the EDK II Crypto Protocol using the library services from +# BaseCryptLib and TlsLib. +# +# Copyright (C) Microsoft Corporation. All rights reserved. +# SPDX-License-Identifier: BSD-2-Clause-Patent +# +## + +[Defines] + INF_VERSION = 0x0001001B + PI_SPECIFICATION_VERSION = 0x0001000A + BASE_NAME = CryptoDxe + MODULE_UNI_FILE = Crypto.uni + FILE_GUID = FEA01457-E381-4135-9475-C6AFD0076C61 + MODULE_TYPE = DXE_DRIVER + VERSION_STRING = 1.0 + ENTRY_POINT = CryptoDxeEntry + +# +# The following information is for reference only and not required by the build tools. +# +# VALID_ARCHITECTURES = IA32 X64 ARM AARCH64 +# + +[Sources] + Crypto.c + CryptoDxe.c + +[Packages] + MdePkg/MdePkg.dec + CryptoPkg/CryptoPkg.dec + +[LibraryClasses] + UefiDriverEntryPoint + UefiBootServicesTableLib + DebugLib + BaseCryptLib + TlsLib + +[Protocols] + gEdkiiCryptoProtocolGuid ## PRODUCES + +# MU_CHANGE +# **************************************************************************** +# AUTOGENERATED BY CryptoPkg\Driver\Packaging\generate_cryptodriver.py +# AUTOGENED AS temp_crypto_pcd.inc.inf +# DO NOT MODIFY +# GENERATED ON: 2023-02-18 14:13:45.978841 + +[Pcd] + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSha1GetContextSize # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSha1Init # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSha1Duplicate # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSha1Update # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSha1Final # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSha1HashAll # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSha256GetContextSize # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSha256Init # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSha256Duplicate # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSha256Update # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSha256Final # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSha256HashAll # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSha384GetContextSize # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSha384Init # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSha384Duplicate # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSha384Update # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSha384Final # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSha384HashAll # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSha512GetContextSize # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSha512Init # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSha512Duplicate # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSha512Update # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSha512Final # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSha512HashAll # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceParallelHash256HashAll # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSm3GetContextSize # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSm3Init # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSm3Duplicate # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSm3Update # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSm3Final # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSm3HashAll # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceHmacSha256New # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceHmacSha256Free # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceHmacSha256SetKey # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceHmacSha256Duplicate # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceHmacSha256Update # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceHmacSha256Final # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceAesGetContextSize # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceAesInit # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceAesCbcEncrypt # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceAesCbcDecrypt # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceRsaNew # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceRsaFree # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceRsaSetKey # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceRsaGetKey # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceRsaGenerateKey # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceRsaCheckKey # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceRsaPkcs1Sign # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceRsaPkcs1Verify # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceRsaPssSign # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceRsaPssVerify # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceRsaGetPrivateKeyFromPem # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceRsaGetPublicKeyFromX509 # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceX509GetSubjectName # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceX509GetCommonName # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceX509GetOrganizationName # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceX509VerifyCert # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceX509ConstructCertificate # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceX509ConstructCertificateStackV # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceX509ConstructCertificateStack # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceX509Free # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceX509StackFree # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceX509GetTBSCert # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServicePkcs5HashPassword # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServicePkcs1v2Encrypt # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServicePkcs7GetSigners # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServicePkcs7FreeSigners # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServicePkcs7GetCertificatesList # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServicePkcs7Sign # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServicePkcs7Verify # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceVerifyEKUsInPkcs7Signature # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServicePkcs7GetAttachedContent # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceAuthenticodeVerify # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceImageTimestampVerify # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceDhNew # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceDhFree # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceDhGenerateParameter # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceDhSetParameter # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceDhGenerateKey # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceDhComputeKey # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceRandomSeed # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceRandomBytes # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceHkdfSha256ExtractAndExpand # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsInitialize # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsCtxFree # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsCtxNew # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsFree # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsNew # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsInHandshake # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsDoHandshake # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsHandleAlert # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsCloseNotify # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsCtrlTrafficOut # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsCtrlTrafficIn # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsRead # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsWrite # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsSetVersion # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsSetConnectionEnd # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsSetCipherList # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsSetCompressionMethod # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsSetVerify # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsSetVerifyHost # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsSetSessionId # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsSetCaCertificate # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsSetHostPublicCert # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsSetHostPrivateKey # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsSetCertRevocationList # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsGetVersion # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsGetConnectionEnd # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsGetCurrentCipher # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsGetCurrentCompressionId # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsGetVerify # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsGetSessionId # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsGetClientRandom # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsGetServerRandom # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsGetKeyMaterial # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsGetCaCertificate # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsGetHostPublicCert # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsGetHostPrivateKey # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsGetCertRevocationList # CONSUMES +# AUTOGEN ENDS +# **************************************************************************** + +[Depex] + TRUE diff --git a/CryptoPkg/Driver/CryptoPei.inf b/CryptoPkg/Driver/CryptoPei.inf index f680c7ee73..5d7d3febcb 100644 --- a/CryptoPkg/Driver/CryptoPei.inf +++ b/CryptoPkg/Driver/CryptoPei.inf @@ -1,178 +1,178 @@ -## @file -# Produces the EDK II Crypto PPI using the library services from BaseCryptLib -# and TlsLib. If this PEIM is dispatched before memory is discovered, -# the RegisterForShadow() feature is used to reload this PEIM into memory after -# memory is discovered. -# -# Copyright (C) Microsoft Corporation. All rights reserved. -# SPDX-License-Identifier: BSD-2-Clause-Patent -# -## - -[Defines] - INF_VERSION = 0x0001001B - BASE_NAME = CryptoPei - MODULE_UNI_FILE = Crypto.uni - FILE_GUID = 0D1CE46B-72D9-4BA7-95DA-23511865E661 - MODULE_TYPE = PEIM - VERSION_STRING = 1.0 - ENTRY_POINT = CryptoPeiEntry - -# -# The following information is for reference only and not required by the build tools. -# -# VALID_ARCHITECTURES = IA32 X64 ARM AARCH64 -# - -[Sources] - Crypto.c - CryptoPei.c - -[Packages] - MdePkg/MdePkg.dec - CryptoPkg/CryptoPkg.dec - -[LibraryClasses] - PeimEntryPoint - PeiServicesLib - DebugLib - BaseCryptLib - TlsLib - -[Ppis] - gEfiPeiMemoryDiscoveredPpiGuid ## CONSUMES - gEdkiiCryptoPpiGuid ## PRODUCES - -# MU_CHANGE -# **************************************************************************** -# AUTOGENERATED BY CryptoPkg\Driver\Packaging\generate_cryptodriver.py -# AUTOGENED AS temp_crypto_pcd.inc.inf -# DO NOT MODIFY -# GENERATED ON: 2023-02-18 14:13:45.978841 - -[Pcd] - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSha1GetContextSize # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSha1Init # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSha1Duplicate # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSha1Update # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSha1Final # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSha1HashAll # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSha256GetContextSize # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSha256Init # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSha256Duplicate # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSha256Update # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSha256Final # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSha256HashAll # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSha384GetContextSize # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSha384Init # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSha384Duplicate # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSha384Update # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSha384Final # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSha384HashAll # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSha512GetContextSize # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSha512Init # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSha512Duplicate # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSha512Update # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSha512Final # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSha512HashAll # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceParallelHash256HashAll # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSm3GetContextSize # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSm3Init # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSm3Duplicate # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSm3Update # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSm3Final # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSm3HashAll # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceHmacSha256New # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceHmacSha256Free # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceHmacSha256SetKey # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceHmacSha256Duplicate # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceHmacSha256Update # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceHmacSha256Final # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceAesGetContextSize # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceAesInit # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceAesCbcEncrypt # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceAesCbcDecrypt # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceRsaNew # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceRsaFree # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceRsaSetKey # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceRsaGetKey # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceRsaGenerateKey # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceRsaCheckKey # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceRsaPkcs1Sign # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceRsaPkcs1Verify # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceRsaPssSign # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceRsaPssVerify # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceRsaGetPrivateKeyFromPem # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceRsaGetPublicKeyFromX509 # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceX509GetSubjectName # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceX509GetCommonName # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceX509GetOrganizationName # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceX509VerifyCert # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceX509ConstructCertificate # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceX509ConstructCertificateStackV # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceX509ConstructCertificateStack # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceX509Free # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceX509StackFree # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceX509GetTBSCert # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServicePkcs5HashPassword # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServicePkcs1v2Encrypt # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServicePkcs7GetSigners # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServicePkcs7FreeSigners # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServicePkcs7GetCertificatesList # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServicePkcs7Sign # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServicePkcs7Verify # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceVerifyEKUsInPkcs7Signature # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServicePkcs7GetAttachedContent # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceAuthenticodeVerify # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceImageTimestampVerify # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceDhNew # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceDhFree # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceDhGenerateParameter # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceDhSetParameter # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceDhGenerateKey # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceDhComputeKey # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceRandomSeed # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceRandomBytes # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceHkdfSha256ExtractAndExpand # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsInitialize # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsCtxFree # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsCtxNew # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsFree # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsNew # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsInHandshake # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsDoHandshake # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsHandleAlert # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsCloseNotify # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsCtrlTrafficOut # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsCtrlTrafficIn # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsRead # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsWrite # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsSetVersion # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsSetConnectionEnd # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsSetCipherList # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsSetCompressionMethod # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsSetVerify # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsSetVerifyHost # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsSetSessionId # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsSetCaCertificate # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsSetHostPublicCert # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsSetHostPrivateKey # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsSetCertRevocationList # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsGetVersion # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsGetConnectionEnd # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsGetCurrentCipher # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsGetCurrentCompressionId # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsGetVerify # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsGetSessionId # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsGetClientRandom # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsGetServerRandom # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsGetKeyMaterial # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsGetCaCertificate # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsGetHostPublicCert # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsGetHostPrivateKey # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsGetCertRevocationList # CONSUMES -# AUTOGEN ENDS -# **************************************************************************** - -[Depex] - TRUE +## @file +# Produces the EDK II Crypto PPI using the library services from BaseCryptLib +# and TlsLib. If this PEIM is dispatched before memory is discovered, +# the RegisterForShadow() feature is used to reload this PEIM into memory after +# memory is discovered. +# +# Copyright (C) Microsoft Corporation. All rights reserved. +# SPDX-License-Identifier: BSD-2-Clause-Patent +# +## + +[Defines] + INF_VERSION = 0x0001001B + BASE_NAME = CryptoPei + MODULE_UNI_FILE = Crypto.uni + FILE_GUID = 0D1CE46B-72D9-4BA7-95DA-23511865E661 + MODULE_TYPE = PEIM + VERSION_STRING = 1.0 + ENTRY_POINT = CryptoPeiEntry + +# +# The following information is for reference only and not required by the build tools. +# +# VALID_ARCHITECTURES = IA32 X64 ARM AARCH64 +# + +[Sources] + Crypto.c + CryptoPei.c + +[Packages] + MdePkg/MdePkg.dec + CryptoPkg/CryptoPkg.dec + +[LibraryClasses] + PeimEntryPoint + PeiServicesLib + DebugLib + BaseCryptLib + TlsLib + +[Ppis] + gEfiPeiMemoryDiscoveredPpiGuid ## CONSUMES + gEdkiiCryptoPpiGuid ## PRODUCES + +# MU_CHANGE +# **************************************************************************** +# AUTOGENERATED BY CryptoPkg\Driver\Packaging\generate_cryptodriver.py +# AUTOGENED AS temp_crypto_pcd.inc.inf +# DO NOT MODIFY +# GENERATED ON: 2023-02-18 14:13:45.978841 + +[Pcd] + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSha1GetContextSize # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSha1Init # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSha1Duplicate # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSha1Update # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSha1Final # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSha1HashAll # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSha256GetContextSize # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSha256Init # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSha256Duplicate # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSha256Update # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSha256Final # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSha256HashAll # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSha384GetContextSize # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSha384Init # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSha384Duplicate # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSha384Update # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSha384Final # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSha384HashAll # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSha512GetContextSize # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSha512Init # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSha512Duplicate # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSha512Update # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSha512Final # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSha512HashAll # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceParallelHash256HashAll # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSm3GetContextSize # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSm3Init # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSm3Duplicate # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSm3Update # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSm3Final # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSm3HashAll # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceHmacSha256New # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceHmacSha256Free # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceHmacSha256SetKey # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceHmacSha256Duplicate # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceHmacSha256Update # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceHmacSha256Final # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceAesGetContextSize # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceAesInit # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceAesCbcEncrypt # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceAesCbcDecrypt # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceRsaNew # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceRsaFree # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceRsaSetKey # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceRsaGetKey # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceRsaGenerateKey # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceRsaCheckKey # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceRsaPkcs1Sign # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceRsaPkcs1Verify # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceRsaPssSign # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceRsaPssVerify # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceRsaGetPrivateKeyFromPem # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceRsaGetPublicKeyFromX509 # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceX509GetSubjectName # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceX509GetCommonName # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceX509GetOrganizationName # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceX509VerifyCert # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceX509ConstructCertificate # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceX509ConstructCertificateStackV # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceX509ConstructCertificateStack # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceX509Free # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceX509StackFree # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceX509GetTBSCert # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServicePkcs5HashPassword # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServicePkcs1v2Encrypt # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServicePkcs7GetSigners # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServicePkcs7FreeSigners # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServicePkcs7GetCertificatesList # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServicePkcs7Sign # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServicePkcs7Verify # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceVerifyEKUsInPkcs7Signature # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServicePkcs7GetAttachedContent # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceAuthenticodeVerify # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceImageTimestampVerify # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceDhNew # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceDhFree # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceDhGenerateParameter # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceDhSetParameter # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceDhGenerateKey # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceDhComputeKey # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceRandomSeed # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceRandomBytes # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceHkdfSha256ExtractAndExpand # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsInitialize # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsCtxFree # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsCtxNew # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsFree # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsNew # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsInHandshake # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsDoHandshake # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsHandleAlert # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsCloseNotify # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsCtrlTrafficOut # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsCtrlTrafficIn # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsRead # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsWrite # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsSetVersion # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsSetConnectionEnd # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsSetCipherList # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsSetCompressionMethod # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsSetVerify # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsSetVerifyHost # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsSetSessionId # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsSetCaCertificate # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsSetHostPublicCert # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsSetHostPrivateKey # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsSetCertRevocationList # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsGetVersion # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsGetConnectionEnd # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsGetCurrentCipher # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsGetCurrentCompressionId # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsGetVerify # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsGetSessionId # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsGetClientRandom # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsGetServerRandom # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsGetKeyMaterial # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsGetCaCertificate # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsGetHostPublicCert # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsGetHostPrivateKey # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsGetCertRevocationList # CONSUMES +# AUTOGEN ENDS +# **************************************************************************** + +[Depex] + TRUE diff --git a/CryptoPkg/Driver/CryptoSmm.inf b/CryptoPkg/Driver/CryptoSmm.inf index 1eccfd91b9..08f529b4e3 100644 --- a/CryptoPkg/Driver/CryptoSmm.inf +++ b/CryptoPkg/Driver/CryptoSmm.inf @@ -1,176 +1,176 @@ -## @file -# Produces the EDK II SMM Crypto Protocol using the library services from -# BaseCryptLib and TlsLib. -# -# Copyright (C) Microsoft Corporation. All rights reserved. -# SPDX-License-Identifier: BSD-2-Clause-Patent -# -## - -[Defines] - INF_VERSION = 0x0001001B - PI_SPECIFICATION_VERSION = 0x00010014 - BASE_NAME = CryptoSmm - MODULE_UNI_FILE = Crypto.uni - FILE_GUID = 391B853F-F488-479B-A3D6-870766C7A38F - MODULE_TYPE = DXE_SMM_DRIVER - VERSION_STRING = 1.0 - ENTRY_POINT = CryptoSmmEntry - -# -# The following information is for reference only and not required by the build tools. -# -# VALID_ARCHITECTURES = IA32 X64 -# - -[Sources] - Crypto.c - CryptoSmm.c - -[Packages] - MdePkg/MdePkg.dec - CryptoPkg/CryptoPkg.dec - -[LibraryClasses] - UefiDriverEntryPoint - SmmServicesTableLib - DebugLib - BaseCryptLib - TlsLib - -[Protocols] - gEdkiiSmmCryptoProtocolGuid ## PRODUCES - -# MU_CHANGE -# **************************************************************************** -# AUTOGENERATED BY CryptoPkg\Driver\Packaging\generate_cryptodriver.py -# AUTOGENED AS temp_crypto_pcd.inc.inf -# DO NOT MODIFY -# GENERATED ON: 2023-02-18 14:13:45.978841 - -[Pcd] - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSha1GetContextSize # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSha1Init # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSha1Duplicate # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSha1Update # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSha1Final # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSha1HashAll # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSha256GetContextSize # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSha256Init # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSha256Duplicate # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSha256Update # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSha256Final # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSha256HashAll # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSha384GetContextSize # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSha384Init # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSha384Duplicate # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSha384Update # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSha384Final # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSha384HashAll # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSha512GetContextSize # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSha512Init # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSha512Duplicate # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSha512Update # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSha512Final # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSha512HashAll # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceParallelHash256HashAll # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSm3GetContextSize # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSm3Init # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSm3Duplicate # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSm3Update # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSm3Final # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSm3HashAll # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceHmacSha256New # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceHmacSha256Free # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceHmacSha256SetKey # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceHmacSha256Duplicate # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceHmacSha256Update # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceHmacSha256Final # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceAesGetContextSize # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceAesInit # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceAesCbcEncrypt # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceAesCbcDecrypt # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceRsaNew # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceRsaFree # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceRsaSetKey # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceRsaGetKey # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceRsaGenerateKey # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceRsaCheckKey # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceRsaPkcs1Sign # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceRsaPkcs1Verify # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceRsaPssSign # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceRsaPssVerify # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceRsaGetPrivateKeyFromPem # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceRsaGetPublicKeyFromX509 # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceX509GetSubjectName # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceX509GetCommonName # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceX509GetOrganizationName # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceX509VerifyCert # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceX509ConstructCertificate # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceX509ConstructCertificateStackV # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceX509ConstructCertificateStack # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceX509Free # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceX509StackFree # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceX509GetTBSCert # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServicePkcs5HashPassword # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServicePkcs1v2Encrypt # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServicePkcs7GetSigners # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServicePkcs7FreeSigners # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServicePkcs7GetCertificatesList # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServicePkcs7Sign # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServicePkcs7Verify # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceVerifyEKUsInPkcs7Signature # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServicePkcs7GetAttachedContent # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceAuthenticodeVerify # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceImageTimestampVerify # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceDhNew # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceDhFree # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceDhGenerateParameter # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceDhSetParameter # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceDhGenerateKey # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceDhComputeKey # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceRandomSeed # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceRandomBytes # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceHkdfSha256ExtractAndExpand # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsInitialize # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsCtxFree # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsCtxNew # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsFree # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsNew # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsInHandshake # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsDoHandshake # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsHandleAlert # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsCloseNotify # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsCtrlTrafficOut # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsCtrlTrafficIn # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsRead # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsWrite # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsSetVersion # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsSetConnectionEnd # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsSetCipherList # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsSetCompressionMethod # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsSetVerify # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsSetVerifyHost # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsSetSessionId # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsSetCaCertificate # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsSetHostPublicCert # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsSetHostPrivateKey # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsSetCertRevocationList # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsGetVersion # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsGetConnectionEnd # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsGetCurrentCipher # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsGetCurrentCompressionId # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsGetVerify # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsGetSessionId # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsGetClientRandom # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsGetServerRandom # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsGetKeyMaterial # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsGetCaCertificate # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsGetHostPublicCert # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsGetHostPrivateKey # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsGetCertRevocationList # CONSUMES -# AUTOGEN ENDS -# **************************************************************************** - -[Depex] - TRUE +## @file +# Produces the EDK II SMM Crypto Protocol using the library services from +# BaseCryptLib and TlsLib. +# +# Copyright (C) Microsoft Corporation. All rights reserved. +# SPDX-License-Identifier: BSD-2-Clause-Patent +# +## + +[Defines] + INF_VERSION = 0x0001001B + PI_SPECIFICATION_VERSION = 0x00010014 + BASE_NAME = CryptoSmm + MODULE_UNI_FILE = Crypto.uni + FILE_GUID = 391B853F-F488-479B-A3D6-870766C7A38F + MODULE_TYPE = DXE_SMM_DRIVER + VERSION_STRING = 1.0 + ENTRY_POINT = CryptoSmmEntry + +# +# The following information is for reference only and not required by the build tools. +# +# VALID_ARCHITECTURES = IA32 X64 +# + +[Sources] + Crypto.c + CryptoSmm.c + +[Packages] + MdePkg/MdePkg.dec + CryptoPkg/CryptoPkg.dec + +[LibraryClasses] + UefiDriverEntryPoint + SmmServicesTableLib + DebugLib + BaseCryptLib + TlsLib + +[Protocols] + gEdkiiSmmCryptoProtocolGuid ## PRODUCES + +# MU_CHANGE +# **************************************************************************** +# AUTOGENERATED BY CryptoPkg\Driver\Packaging\generate_cryptodriver.py +# AUTOGENED AS temp_crypto_pcd.inc.inf +# DO NOT MODIFY +# GENERATED ON: 2023-02-18 14:13:45.978841 + +[Pcd] + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSha1GetContextSize # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSha1Init # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSha1Duplicate # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSha1Update # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSha1Final # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSha1HashAll # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSha256GetContextSize # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSha256Init # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSha256Duplicate # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSha256Update # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSha256Final # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSha256HashAll # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSha384GetContextSize # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSha384Init # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSha384Duplicate # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSha384Update # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSha384Final # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSha384HashAll # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSha512GetContextSize # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSha512Init # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSha512Duplicate # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSha512Update # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSha512Final # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSha512HashAll # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceParallelHash256HashAll # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSm3GetContextSize # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSm3Init # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSm3Duplicate # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSm3Update # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSm3Final # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSm3HashAll # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceHmacSha256New # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceHmacSha256Free # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceHmacSha256SetKey # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceHmacSha256Duplicate # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceHmacSha256Update # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceHmacSha256Final # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceAesGetContextSize # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceAesInit # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceAesCbcEncrypt # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceAesCbcDecrypt # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceRsaNew # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceRsaFree # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceRsaSetKey # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceRsaGetKey # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceRsaGenerateKey # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceRsaCheckKey # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceRsaPkcs1Sign # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceRsaPkcs1Verify # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceRsaPssSign # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceRsaPssVerify # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceRsaGetPrivateKeyFromPem # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceRsaGetPublicKeyFromX509 # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceX509GetSubjectName # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceX509GetCommonName # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceX509GetOrganizationName # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceX509VerifyCert # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceX509ConstructCertificate # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceX509ConstructCertificateStackV # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceX509ConstructCertificateStack # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceX509Free # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceX509StackFree # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceX509GetTBSCert # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServicePkcs5HashPassword # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServicePkcs1v2Encrypt # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServicePkcs7GetSigners # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServicePkcs7FreeSigners # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServicePkcs7GetCertificatesList # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServicePkcs7Sign # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServicePkcs7Verify # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceVerifyEKUsInPkcs7Signature # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServicePkcs7GetAttachedContent # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceAuthenticodeVerify # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceImageTimestampVerify # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceDhNew # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceDhFree # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceDhGenerateParameter # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceDhSetParameter # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceDhGenerateKey # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceDhComputeKey # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceRandomSeed # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceRandomBytes # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceHkdfSha256ExtractAndExpand # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsInitialize # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsCtxFree # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsCtxNew # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsFree # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsNew # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsInHandshake # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsDoHandshake # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsHandleAlert # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsCloseNotify # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsCtrlTrafficOut # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsCtrlTrafficIn # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsRead # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsWrite # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsSetVersion # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsSetConnectionEnd # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsSetCipherList # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsSetCompressionMethod # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsSetVerify # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsSetVerifyHost # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsSetSessionId # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsSetCaCertificate # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsSetHostPublicCert # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsSetHostPrivateKey # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsSetCertRevocationList # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsGetVersion # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsGetConnectionEnd # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsGetCurrentCipher # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsGetCurrentCompressionId # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsGetVerify # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsGetSessionId # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsGetClientRandom # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsGetServerRandom # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsGetKeyMaterial # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsGetCaCertificate # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsGetHostPublicCert # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsGetHostPrivateKey # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsGetCertRevocationList # CONSUMES +# AUTOGEN ENDS +# **************************************************************************** + +[Depex] + TRUE diff --git a/CryptoPkg/Driver/Packaging/License.txt b/CryptoPkg/Driver/Packaging/License.txt index ae7f1df096..2647015113 100644 --- a/CryptoPkg/Driver/Packaging/License.txt +++ b/CryptoPkg/Driver/Packaging/License.txt @@ -1,13 +1,13 @@ -This project contains several licenses. Please refer to microsoft.github.com/mu to read all the licenses included in this package. -Some of the licenses are included below. - -SPDX-License-Identifier: BSD-2-Clause-Patent - -The Companies that have contributed: - -Copyright (C) Microsoft Corporation. -Copyright (c) 2004 - 2016, Intel Corporation. All rights reserved. -Copyright (c) 2008 - 2010, Apple Inc. All rights reserved. -Copyright (c) 2011 - 2015, ARM Limited. All rights reserved. -Copyright (c) 2014 - 2015, Linaro Limited. All rights reserved. +This project contains several licenses. Please refer to microsoft.github.com/mu to read all the licenses included in this package. +Some of the licenses are included below. + +SPDX-License-Identifier: BSD-2-Clause-Patent + +The Companies that have contributed: + +Copyright (C) Microsoft Corporation. +Copyright (c) 2004 - 2016, Intel Corporation. All rights reserved. +Copyright (c) 2008 - 2010, Apple Inc. All rights reserved. +Copyright (c) 2011 - 2015, ARM Limited. All rights reserved. +Copyright (c) 2014 - 2015, Linaro Limited. All rights reserved. Copyright (c) 2013 - 2015, Red Hat, Inc. \ No newline at end of file diff --git a/CryptoPkg/Driver/Packaging/edk2-BaseCryptoDriver.config.json b/CryptoPkg/Driver/Packaging/edk2-BaseCryptoDriver.config.json index b1eb6c314e..330113dac5 100644 --- a/CryptoPkg/Driver/Packaging/edk2-BaseCryptoDriver.config.json +++ b/CryptoPkg/Driver/Packaging/edk2-BaseCryptoDriver.config.json @@ -1,9 +1,9 @@ -{ - "name": "edk2-basecrypto-driver-bin", - "author_string": "ProjectMu, TianoCore", - "server_url": "https://pkgs.dev.azure.com/projectmu/mu/_packaging/Mu-Public/nuget/v3/index.json", - "project_url": "https://aka.ms/projectmu", - "license_url": "https://github.com/Microsoft/mu/blob/master/LICENSE", - "description_string": "The precompiled BaseCryptLib instance", - "copyright_string": "Copyright 2020" +{ + "name": "edk2-basecrypto-driver-bin", + "author_string": "ProjectMu, TianoCore", + "server_url": "https://pkgs.dev.azure.com/projectmu/mu/_packaging/Mu-Public/nuget/v3/index.json", + "project_url": "https://aka.ms/projectmu", + "license_url": "https://github.com/Microsoft/mu/blob/master/LICENSE", + "description_string": "The precompiled BaseCryptLib instance", + "copyright_string": "Copyright 2020" } \ No newline at end of file diff --git a/CryptoPkg/Driver/readme.md b/CryptoPkg/Driver/readme.md index d8f8824e39..9fe5f14df7 100644 --- a/CryptoPkg/Driver/readme.md +++ b/CryptoPkg/Driver/readme.md @@ -1,154 +1,154 @@ -# Crypto Driver - -This is a potentially prepacked version of the BaseCryptLib and TlsLib, delivered via protocol. - -There are two routes: using the pre-compiled version and compiling it into your platform. - -## Benefits - -But first, why would you care about this? - -It has a few benefits, namely: - -- Smaller Binary sizes -- Easier to service/upgrade -- Transparency on what version of crypto you're using -- Reduced build times (if using pre-compiled version) - -There are different flavors of Crypto available, with different functions supported. -Don't need to use HMAC in your PEI phase? -Select a service level or flavor that doesn't include HMAC in your platform. - -## How include on your platform - -Now there are a few options for you. We'll start with the pre-compiled route. - -### The Pre-compiled (easy) way - -The easy way involves setting a few variables and a few includes. -The hard way is just to do it yourself. - -First the easy way: - -1. Define the service level that you want for each phase of UEFI in the defines section of your DSC. - - ``` dsc - [Defines] - DEFINE PEI_CRYPTO_SERVICES = TINY_SHA - DEFINE DXE_CRYPTO_SERVICES = STANDARD - DEFINE SMM_CRYPTO_SERVICES = STANDARD - DEFINE PEI_CRYPTO_ARCH = IA32 - DEFINE DXE_CRYPTO_ARCH = X64 - DEFINE SMM_CRYPTO_ARCH = X64 - ``` - - The above example is for a standard intel platform, and the service levels or flavors available. - -2. Add the DSC include - - ``` dsc - !include CryptoPkg/Driver/Bin/CryptoDriver.inc.dsc - ``` - - This sets the definitions for BaseCryptLib as well as includes the correct flavor level of the component you - wish to use. - -3. Add the FDF includes to your platform FDF - - Currently, it isn't possible in an FDF to redefine a FV section and have them be combined. - There are two includes: BOOTBLOCK and DXE. - The first includes the PEI phase and is meant to be stuck in your BOOTBLOCK FV. - The second contains the DXE and SMM modules and is meant to be stuck in your FVDXE. - - ``` fdf - [FV.FVBOOTBLOCK] - ... - !include CryptoPkg/Driver/Bin/CryptoDriver.BOOTBLOCK.inc.fdf - ... - - [FV.FVDXE] - ... - !include CryptoPkg/Driver/Bin/CryptoDriver.DXE.inc.fdf - ``` - -### Recommendations - -It is highly recommended to put this logic behind conditionals like so: - -``` fdf -[FV.FVBOOTBLOCK] -!if $(ENABLE_SHARED_CRYPTO) == TRUE - !include CryptoPkg/Driver/Bin/CryptoDriver.BOOTBLOCK.inc.fdf -!endif -``` - -This allows developers on the platform to use their own BaseCryptLib or TlsLib if they want. -Just add a check if it's not defined in your DSC like so. - -``` dsc -!ifndef ENABLE_SHARED_CRYPTO # by default true - ENABLE_SHARED_CRYPTO = TRUE -!endif -``` - -### The DIY way - -If you want to take advantage of the BaseCryptOnProtocol but don't want to use a pre-compiled method, you can compile -it within your platform itself. - -Shown here is for an Intel platform, adjust the architectures as needed. - -``` dsc - -[LibraryClasses.IA32] - BaseCryptLib|CryptoPkg/Library/BaseCryptLibOnProtocolPpi/PeiCryptLib.inf - TlsLib|CryptoPkg/Library/BaseCryptLibOnProtocolPpi/PeiCryptLib.inf - -[LibraryClasses.X64] - BaseCryptLib|CryptoPkg/Library/BaseCryptLibOnProtocolPpi/DxeCryptLib.inf - TlsLib|CryptoPkg/Library/BaseCryptLibOnProtocolPpi/DxeCryptLib.inf - -[LibraryClasses.X64.DXE_SMM_DRIVER] - BaseCryptLib|CryptoPkg/Library/BaseCryptLibOnProtocolPpi/SmmCryptLib.inf - TlsLib|CryptoPkg/Library/BaseCryptLibOnProtocolPpi/SmmCryptLib.inf - -[Components.IA32] - CryptoPkg/Driver/CryptoPei.inf { - - BaseCryptLib|CryptoPkg/Library/BaseCryptLib/PeiCryptLib.inf - TlsLib|CryptoPkg/Library/TlsLibNull/TlsLibNull.inf - - .. All the flavor PCDs here .. - } - -[Components.X64] - CryptoPkg/Driver/CryptoDxe.inf { - - BaseCryptLib|CryptoPkg/Library/BaseCryptLib/BaseCryptLib.inf - TlsLib|CryptoPkg/Library/TlsLib/TlsLib.inf - - .. All the flavor PCDs here .. - } - CryptoPkg/Driver/CryptoSmm.inf { - - BaseCryptLib|CryptoPkg/Library/BaseCryptLib/SmmCryptLib.inf - TlsLib|CryptoPkg/Library/TlsLibNull/TlsLibNull.inf - - .. All the flavor PCDs here .. - } -``` - -The PCDs are long and default to all false. -The flavors are stored as .inc.dsc files at `CryptoPkg\Driver\Packaging`. -An example would be `CryptoPkg\Driver\Packaging\Crypto.pcd.TINY_SHA.inc.dsc` which is a flavor that just has Sha1, -Sha256, and Sha386. - -You'll need to include these components in your FDF as well. - -``` fdf -[FV.FVBOOTBLOCK] - INF CryptoPkg/Driver/CryptoPei.inf -[FV.FVDXE] - INF CryptoPkg/Driver/CryptoSmm.inf - INF CryptoPkg/Driver/CryptoDxe.inf -``` +# Crypto Driver + +This is a potentially prepacked version of the BaseCryptLib and TlsLib, delivered via protocol. + +There are two routes: using the pre-compiled version and compiling it into your platform. + +## Benefits + +But first, why would you care about this? + +It has a few benefits, namely: + +- Smaller Binary sizes +- Easier to service/upgrade +- Transparency on what version of crypto you're using +- Reduced build times (if using pre-compiled version) + +There are different flavors of Crypto available, with different functions supported. +Don't need to use HMAC in your PEI phase? +Select a service level or flavor that doesn't include HMAC in your platform. + +## How include on your platform + +Now there are a few options for you. We'll start with the pre-compiled route. + +### The Pre-compiled (easy) way + +The easy way involves setting a few variables and a few includes. +The hard way is just to do it yourself. + +First the easy way: + +1. Define the service level that you want for each phase of UEFI in the defines section of your DSC. + + ``` dsc + [Defines] + DEFINE PEI_CRYPTO_SERVICES = TINY_SHA + DEFINE DXE_CRYPTO_SERVICES = STANDARD + DEFINE SMM_CRYPTO_SERVICES = STANDARD + DEFINE PEI_CRYPTO_ARCH = IA32 + DEFINE DXE_CRYPTO_ARCH = X64 + DEFINE SMM_CRYPTO_ARCH = X64 + ``` + + The above example is for a standard intel platform, and the service levels or flavors available. + +2. Add the DSC include + + ``` dsc + !include CryptoPkg/Driver/Bin/CryptoDriver.inc.dsc + ``` + + This sets the definitions for BaseCryptLib as well as includes the correct flavor level of the component you + wish to use. + +3. Add the FDF includes to your platform FDF + + Currently, it isn't possible in an FDF to redefine a FV section and have them be combined. + There are two includes: BOOTBLOCK and DXE. + The first includes the PEI phase and is meant to be stuck in your BOOTBLOCK FV. + The second contains the DXE and SMM modules and is meant to be stuck in your FVDXE. + + ``` fdf + [FV.FVBOOTBLOCK] + ... + !include CryptoPkg/Driver/Bin/CryptoDriver.BOOTBLOCK.inc.fdf + ... + + [FV.FVDXE] + ... + !include CryptoPkg/Driver/Bin/CryptoDriver.DXE.inc.fdf + ``` + +### Recommendations + +It is highly recommended to put this logic behind conditionals like so: + +``` fdf +[FV.FVBOOTBLOCK] +!if $(ENABLE_SHARED_CRYPTO) == TRUE + !include CryptoPkg/Driver/Bin/CryptoDriver.BOOTBLOCK.inc.fdf +!endif +``` + +This allows developers on the platform to use their own BaseCryptLib or TlsLib if they want. +Just add a check if it's not defined in your DSC like so. + +``` dsc +!ifndef ENABLE_SHARED_CRYPTO # by default true + ENABLE_SHARED_CRYPTO = TRUE +!endif +``` + +### The DIY way + +If you want to take advantage of the BaseCryptOnProtocol but don't want to use a pre-compiled method, you can compile +it within your platform itself. + +Shown here is for an Intel platform, adjust the architectures as needed. + +``` dsc + +[LibraryClasses.IA32] + BaseCryptLib|CryptoPkg/Library/BaseCryptLibOnProtocolPpi/PeiCryptLib.inf + TlsLib|CryptoPkg/Library/BaseCryptLibOnProtocolPpi/PeiCryptLib.inf + +[LibraryClasses.X64] + BaseCryptLib|CryptoPkg/Library/BaseCryptLibOnProtocolPpi/DxeCryptLib.inf + TlsLib|CryptoPkg/Library/BaseCryptLibOnProtocolPpi/DxeCryptLib.inf + +[LibraryClasses.X64.DXE_SMM_DRIVER] + BaseCryptLib|CryptoPkg/Library/BaseCryptLibOnProtocolPpi/SmmCryptLib.inf + TlsLib|CryptoPkg/Library/BaseCryptLibOnProtocolPpi/SmmCryptLib.inf + +[Components.IA32] + CryptoPkg/Driver/CryptoPei.inf { + + BaseCryptLib|CryptoPkg/Library/BaseCryptLib/PeiCryptLib.inf + TlsLib|CryptoPkg/Library/TlsLibNull/TlsLibNull.inf + + .. All the flavor PCDs here .. + } + +[Components.X64] + CryptoPkg/Driver/CryptoDxe.inf { + + BaseCryptLib|CryptoPkg/Library/BaseCryptLib/BaseCryptLib.inf + TlsLib|CryptoPkg/Library/TlsLib/TlsLib.inf + + .. All the flavor PCDs here .. + } + CryptoPkg/Driver/CryptoSmm.inf { + + BaseCryptLib|CryptoPkg/Library/BaseCryptLib/SmmCryptLib.inf + TlsLib|CryptoPkg/Library/TlsLibNull/TlsLibNull.inf + + .. All the flavor PCDs here .. + } +``` + +The PCDs are long and default to all false. +The flavors are stored as .inc.dsc files at `CryptoPkg\Driver\Packaging`. +An example would be `CryptoPkg\Driver\Packaging\Crypto.pcd.TINY_SHA.inc.dsc` which is a flavor that just has Sha1, +Sha256, and Sha386. + +You'll need to include these components in your FDF as well. + +``` fdf +[FV.FVBOOTBLOCK] + INF CryptoPkg/Driver/CryptoPei.inf +[FV.FVDXE] + INF CryptoPkg/Driver/CryptoSmm.inf + INF CryptoPkg/Driver/CryptoDxe.inf +``` diff --git a/CryptoPkg/Library/BaseCryptLib/BaseCryptLib.inf b/CryptoPkg/Library/BaseCryptLib/BaseCryptLib.inf index d8a9dbb3d9..39395b71b8 100644 --- a/CryptoPkg/Library/BaseCryptLib/BaseCryptLib.inf +++ b/CryptoPkg/Library/BaseCryptLib/BaseCryptLib.inf @@ -30,7 +30,7 @@ [Sources] InternalCryptLib.h - Hash/CryptMd5Null.c ## MS_CHANGE_162948 MSChange - Remove support for deprecated crypto. + Hash/CryptMd5Null.c ## MS_CHANGE_162948 MSChange - Remove support for deprecated crypto. Hash/CryptSha1.c Hash/CryptSha256.c Hash/CryptSha512.c diff --git a/CryptoPkg/Library/BaseCryptLib/PeiCryptLib.inf b/CryptoPkg/Library/BaseCryptLib/PeiCryptLib.inf index dd907deaca..7ae3c55de3 100644 --- a/CryptoPkg/Library/BaseCryptLib/PeiCryptLib.inf +++ b/CryptoPkg/Library/BaseCryptLib/PeiCryptLib.inf @@ -35,7 +35,7 @@ [Sources] InternalCryptLib.h - Hash/CryptMd5Null.c ## MS_CHANGE_162948 MSChange - Remove support for deprecated crypto. + Hash/CryptMd5Null.c ## MS_CHANGE_162948 MSChange - Remove support for deprecated crypto. Hash/CryptSha1.c Hash/CryptSha256.c Hash/CryptSm3.c diff --git a/CryptoPkg/Library/BaseCryptLib/RuntimeCryptLib.inf b/CryptoPkg/Library/BaseCryptLib/RuntimeCryptLib.inf index 9cbbbd6f28..37450ed2e2 100644 --- a/CryptoPkg/Library/BaseCryptLib/RuntimeCryptLib.inf +++ b/CryptoPkg/Library/BaseCryptLib/RuntimeCryptLib.inf @@ -36,7 +36,7 @@ [Sources] InternalCryptLib.h - Hash/CryptMd5Null.c ## MS_CHANGE_162948 MSChange - Remove support for deprecated crypto. + Hash/CryptMd5Null.c ## MS_CHANGE_162948 MSChange - Remove support for deprecated crypto. Hash/CryptSha1.c Hash/CryptSha256.c Hash/CryptSm3.c @@ -49,7 +49,7 @@ Pk/CryptRsaBasic.c Pk/CryptRsaExtNull.c Pk/CryptPkcs1OaepNull.c - Pk/CryptPkcs5Pbkdf2.c ## MU_CHANGE TCBZ2997 + Pk/CryptPkcs5Pbkdf2.c ## MU_CHANGE TCBZ2997 Pk/CryptPkcs7SignNull.c Pk/CryptPkcs7VerifyCommon.c Pk/CryptPkcs7VerifyRuntime.c diff --git a/CryptoPkg/Library/BaseCryptLib/SmmCryptLib.inf b/CryptoPkg/Library/BaseCryptLib/SmmCryptLib.inf index fb3d5bb772..f84290db37 100644 --- a/CryptoPkg/Library/BaseCryptLib/SmmCryptLib.inf +++ b/CryptoPkg/Library/BaseCryptLib/SmmCryptLib.inf @@ -33,7 +33,7 @@ [Sources] InternalCryptLib.h - Hash/CryptMd5.c + Hash/CryptMd5Null.c ## MS_CHANGE_162948 - MSChange - Remove support for deprecated crypto. Hash/CryptSha1.c Hash/CryptSha256.c Hash/CryptSm3.c diff --git a/CryptoPkg/Library/BaseCryptLibOnProtocolPpi/DxeCryptLib.inf b/CryptoPkg/Library/BaseCryptLibOnProtocolPpi/DxeCryptLib.inf index 96dcf4bc18..7cab4e063e 100644 --- a/CryptoPkg/Library/BaseCryptLibOnProtocolPpi/DxeCryptLib.inf +++ b/CryptoPkg/Library/BaseCryptLibOnProtocolPpi/DxeCryptLib.inf @@ -1,178 +1,178 @@ -## @file -# Implements the BaseCryptLib and TlsLib using the services of the EDK II Crypto -# Protocol. -# -# Copyright (C) Microsoft Corporation. All rights reserved. -# Copyright (c) 2020, Hewlett Packard Enterprise Development LP. All rights reserved.
-# Copyright (c) 2022, Loongson Technology Corporation Limited. All rights reserved.
-# SPDX-License-Identifier: BSD-2-Clause-Patent -# -## - -[Defines] - INF_VERSION = 0x0001001B - BASE_NAME = DxeCryptLib - MODULE_UNI_FILE = CryptLib.uni - FILE_GUID = B38CBDA6-8017-4111-8232-9E8328DE82F6 - VERSION_STRING = 1.0 - MODULE_TYPE = DXE_DRIVER - LIBRARY_CLASS = BaseCryptLib | DXE_DRIVER UEFI_DRIVER UEFI_APPLICATION DXE_CORE - LIBRARY_CLASS = TlsLib | DXE_DRIVER UEFI_DRIVER UEFI_APPLICATION - CONSTRUCTOR = DxeCryptLibConstructor - -# -# The following information is for reference only and not required by the build tools. -# -# VALID_ARCHITECTURES = IA32 X64 ARM AARCH64 RISCV64 LOONGARCH64 -# - -[Packages] - MdePkg/MdePkg.dec - CryptoPkg/CryptoPkg.dec - -[LibraryClasses] - BaseLib - DebugLib - UefiBootServicesTableLib - -[Sources] - DxeCryptLib.c - CryptLib.c - -[Protocols] - gEdkiiCryptoProtocolGuid ## CONSUMES - -# MU_CHANGE START -# **************************************************************************** -# AUTOGENERATED BY CryptoPkg\Driver\Packaging\generate_cryptodriver.py -# AUTOGENED AS temp_crypto_pcd.inc.inf -# DO NOT MODIFY -# GENERATED ON: 2022-09-21 13:34:55.465175 - -[Pcd] - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSha1GetContextSize # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSha1Init # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSha1Duplicate # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSha1Update # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSha1Final # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSha1HashAll # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSha256GetContextSize # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSha256Init # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSha256Duplicate # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSha256Update # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSha256Final # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSha256HashAll # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSha384GetContextSize # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSha384Init # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSha384Duplicate # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSha384Update # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSha384Final # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSha384HashAll # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSha512GetContextSize # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSha512Init # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSha512Duplicate # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSha512Update # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSha512Final # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSha512HashAll # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceParallelHash256HashAll # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSm3GetContextSize # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSm3Init # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSm3Duplicate # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSm3Update # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSm3Final # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSm3HashAll # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceHmacSha256New # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceHmacSha256Free # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceHmacSha256SetKey # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceHmacSha256Duplicate # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceHmacSha256Update # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceHmacSha256Final # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceAesGetContextSize # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceAesInit # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceAesCbcEncrypt # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceAesCbcDecrypt # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceRsaNew # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceRsaFree # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceRsaSetKey # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceRsaGetKey # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceRsaGenerateKey # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceRsaCheckKey # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceRsaPkcs1Sign # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceRsaPkcs1Verify # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceRsaPssSign # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceRsaPssVerify # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceRsaGetPrivateKeyFromPem # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceRsaGetPublicKeyFromX509 # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceX509GetSubjectName # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceX509GetCommonName # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceX509GetOrganizationName # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceX509VerifyCert # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceX509ConstructCertificate # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceX509ConstructCertificateStackV # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceX509ConstructCertificateStack # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceX509Free # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceX509StackFree # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceX509GetTBSCert # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServicePkcs5HashPassword # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServicePkcs1v2Encrypt # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServicePkcs7GetSigners # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServicePkcs7FreeSigners # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServicePkcs7GetCertificatesList # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServicePkcs7Sign # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServicePkcs7Verify # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceVerifyEKUsInPkcs7Signature # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServicePkcs7GetAttachedContent # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceAuthenticodeVerify # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceImageTimestampVerify # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceDhNew # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceDhFree # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceDhGenerateParameter # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceDhSetParameter # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceDhGenerateKey # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceDhComputeKey # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceRandomSeed # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceRandomBytes # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceHkdfSha256ExtractAndExpand # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsInitialize # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsCtxFree # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsCtxNew # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsFree # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsNew # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsInHandshake # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsDoHandshake # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsHandleAlert # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsCloseNotify # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsCtrlTrafficOut # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsCtrlTrafficIn # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsRead # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsWrite # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsSetVersion # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsSetConnectionEnd # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsSetCipherList # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsSetCompressionMethod # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsSetVerify # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsSetVerifyHost # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsSetSessionId # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsSetCaCertificate # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsSetHostPublicCert # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsSetHostPrivateKey # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsSetCertRevocationList # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsGetVersion # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsGetConnectionEnd # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsGetCurrentCipher # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsGetCurrentCompressionId # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsGetVerify # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsGetSessionId # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsGetClientRandom # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsGetServerRandom # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsGetKeyMaterial # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsGetCaCertificate # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsGetHostPublicCert # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsGetHostPrivateKey # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsGetCertRevocationList # CONSUMES -# AUTOGEN ENDS -# **************************************************************************** -# MU_CHANGE END - -[Depex] - gEdkiiCryptoProtocolGuid +## @file +# Implements the BaseCryptLib and TlsLib using the services of the EDK II Crypto +# Protocol. +# +# Copyright (C) Microsoft Corporation. All rights reserved. +# Copyright (c) 2020, Hewlett Packard Enterprise Development LP. All rights reserved.
+# Copyright (c) 2022, Loongson Technology Corporation Limited. All rights reserved.
+# SPDX-License-Identifier: BSD-2-Clause-Patent +# +## + +[Defines] + INF_VERSION = 0x0001001B + BASE_NAME = DxeCryptLib + MODULE_UNI_FILE = CryptLib.uni + FILE_GUID = B38CBDA6-8017-4111-8232-9E8328DE82F6 + VERSION_STRING = 1.0 + MODULE_TYPE = DXE_DRIVER + LIBRARY_CLASS = BaseCryptLib | DXE_DRIVER UEFI_DRIVER UEFI_APPLICATION DXE_CORE + LIBRARY_CLASS = TlsLib | DXE_DRIVER UEFI_DRIVER UEFI_APPLICATION + CONSTRUCTOR = DxeCryptLibConstructor + +# +# The following information is for reference only and not required by the build tools. +# +# VALID_ARCHITECTURES = IA32 X64 ARM AARCH64 RISCV64 LOONGARCH64 +# + +[Packages] + MdePkg/MdePkg.dec + CryptoPkg/CryptoPkg.dec + +[LibraryClasses] + BaseLib + DebugLib + UefiBootServicesTableLib + +[Sources] + DxeCryptLib.c + CryptLib.c + +[Protocols] + gEdkiiCryptoProtocolGuid ## CONSUMES + +# MU_CHANGE START +# **************************************************************************** +# AUTOGENERATED BY CryptoPkg\Driver\Packaging\generate_cryptodriver.py +# AUTOGENED AS temp_crypto_pcd.inc.inf +# DO NOT MODIFY +# GENERATED ON: 2022-09-21 13:34:55.465175 + +[Pcd] + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSha1GetContextSize # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSha1Init # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSha1Duplicate # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSha1Update # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSha1Final # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSha1HashAll # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSha256GetContextSize # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSha256Init # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSha256Duplicate # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSha256Update # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSha256Final # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSha256HashAll # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSha384GetContextSize # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSha384Init # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSha384Duplicate # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSha384Update # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSha384Final # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSha384HashAll # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSha512GetContextSize # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSha512Init # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSha512Duplicate # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSha512Update # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSha512Final # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSha512HashAll # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceParallelHash256HashAll # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSm3GetContextSize # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSm3Init # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSm3Duplicate # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSm3Update # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSm3Final # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSm3HashAll # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceHmacSha256New # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceHmacSha256Free # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceHmacSha256SetKey # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceHmacSha256Duplicate # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceHmacSha256Update # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceHmacSha256Final # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceAesGetContextSize # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceAesInit # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceAesCbcEncrypt # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceAesCbcDecrypt # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceRsaNew # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceRsaFree # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceRsaSetKey # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceRsaGetKey # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceRsaGenerateKey # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceRsaCheckKey # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceRsaPkcs1Sign # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceRsaPkcs1Verify # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceRsaPssSign # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceRsaPssVerify # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceRsaGetPrivateKeyFromPem # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceRsaGetPublicKeyFromX509 # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceX509GetSubjectName # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceX509GetCommonName # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceX509GetOrganizationName # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceX509VerifyCert # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceX509ConstructCertificate # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceX509ConstructCertificateStackV # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceX509ConstructCertificateStack # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceX509Free # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceX509StackFree # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceX509GetTBSCert # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServicePkcs5HashPassword # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServicePkcs1v2Encrypt # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServicePkcs7GetSigners # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServicePkcs7FreeSigners # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServicePkcs7GetCertificatesList # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServicePkcs7Sign # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServicePkcs7Verify # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceVerifyEKUsInPkcs7Signature # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServicePkcs7GetAttachedContent # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceAuthenticodeVerify # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceImageTimestampVerify # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceDhNew # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceDhFree # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceDhGenerateParameter # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceDhSetParameter # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceDhGenerateKey # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceDhComputeKey # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceRandomSeed # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceRandomBytes # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceHkdfSha256ExtractAndExpand # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsInitialize # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsCtxFree # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsCtxNew # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsFree # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsNew # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsInHandshake # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsDoHandshake # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsHandleAlert # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsCloseNotify # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsCtrlTrafficOut # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsCtrlTrafficIn # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsRead # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsWrite # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsSetVersion # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsSetConnectionEnd # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsSetCipherList # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsSetCompressionMethod # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsSetVerify # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsSetVerifyHost # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsSetSessionId # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsSetCaCertificate # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsSetHostPublicCert # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsSetHostPrivateKey # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsSetCertRevocationList # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsGetVersion # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsGetConnectionEnd # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsGetCurrentCipher # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsGetCurrentCompressionId # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsGetVerify # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsGetSessionId # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsGetClientRandom # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsGetServerRandom # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsGetKeyMaterial # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsGetCaCertificate # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsGetHostPublicCert # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsGetHostPrivateKey # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsGetCertRevocationList # CONSUMES +# AUTOGEN ENDS +# **************************************************************************** +# MU_CHANGE END + +[Depex] + gEdkiiCryptoProtocolGuid diff --git a/CryptoPkg/Library/BaseCryptLibOnProtocolPpi/PeiCryptLib.inf b/CryptoPkg/Library/BaseCryptLibOnProtocolPpi/PeiCryptLib.inf index 478daa640f..2ff7ef317e 100644 --- a/CryptoPkg/Library/BaseCryptLibOnProtocolPpi/PeiCryptLib.inf +++ b/CryptoPkg/Library/BaseCryptLibOnProtocolPpi/PeiCryptLib.inf @@ -1,177 +1,177 @@ -## @file -# Implements the BaseCryptLib and TlsLib using the services of the EDK II Crypto -# PPI. -# -# Copyright (C) Microsoft Corporation. All rights reserved. -# Copyright (c) 2020, Hewlett Packard Enterprise Development LP. All rights reserved.
-# Copyright (c) 2022, Loongson Technology Corporation Limited. All rights reserved.
-# SPDX-License-Identifier: BSD-2-Clause-Patent -# -## - -[Defines] - INF_VERSION = 0x0001001B - BASE_NAME = PeiCryptLib - MODULE_UNI_FILE = CryptLib.uni - FILE_GUID = 3E8B50C6-F68C-4212-B903-94A10FE02399 - VERSION_STRING = 1.0 - MODULE_TYPE = PEIM - LIBRARY_CLASS = BaseCryptLib | PEIM - LIBRARY_CLASS = TlsLib | PEIM - -# -# The following information is for reference only and not required by the build tools. -# -# VALID_ARCHITECTURES = IA32 X64 ARM AARCH64 RISCV64 LOONGARCH64 -# - -[Packages] - MdePkg/MdePkg.dec - CryptoPkg/CryptoPkg.dec - -[LibraryClasses] - BaseLib - DebugLib - PeiServicesLib - -[Sources] - PeiCryptLib.c - CryptLib.c - -[Ppis] - gEdkiiCryptoPpiGuid ## CONSUMES - -# MU_CHANGE START -# **************************************************************************** -# AUTOGENERATED BY CryptoPkg\Driver\Packaging\generate_cryptodriver.py -# AUTOGENED AS temp_crypto_pcd.inc.inf -# DO NOT MODIFY -# GENERATED ON: 2022-09-21 13:34:55.465175 - -[Pcd] - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSha1GetContextSize # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSha1Init # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSha1Duplicate # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSha1Update # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSha1Final # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSha1HashAll # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSha256GetContextSize # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSha256Init # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSha256Duplicate # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSha256Update # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSha256Final # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSha256HashAll # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSha384GetContextSize # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSha384Init # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSha384Duplicate # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSha384Update # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSha384Final # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSha384HashAll # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSha512GetContextSize # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSha512Init # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSha512Duplicate # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSha512Update # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSha512Final # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSha512HashAll # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceParallelHash256HashAll # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSm3GetContextSize # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSm3Init # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSm3Duplicate # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSm3Update # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSm3Final # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSm3HashAll # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceHmacSha256New # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceHmacSha256Free # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceHmacSha256SetKey # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceHmacSha256Duplicate # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceHmacSha256Update # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceHmacSha256Final # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceAesGetContextSize # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceAesInit # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceAesCbcEncrypt # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceAesCbcDecrypt # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceRsaNew # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceRsaFree # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceRsaSetKey # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceRsaGetKey # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceRsaGenerateKey # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceRsaCheckKey # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceRsaPkcs1Sign # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceRsaPkcs1Verify # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceRsaPssSign # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceRsaPssVerify # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceRsaGetPrivateKeyFromPem # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceRsaGetPublicKeyFromX509 # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceX509GetSubjectName # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceX509GetCommonName # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceX509GetOrganizationName # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceX509VerifyCert # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceX509ConstructCertificate # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceX509ConstructCertificateStackV # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceX509ConstructCertificateStack # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceX509Free # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceX509StackFree # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceX509GetTBSCert # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServicePkcs5HashPassword # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServicePkcs1v2Encrypt # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServicePkcs7GetSigners # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServicePkcs7FreeSigners # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServicePkcs7GetCertificatesList # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServicePkcs7Sign # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServicePkcs7Verify # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceVerifyEKUsInPkcs7Signature # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServicePkcs7GetAttachedContent # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceAuthenticodeVerify # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceImageTimestampVerify # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceDhNew # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceDhFree # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceDhGenerateParameter # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceDhSetParameter # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceDhGenerateKey # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceDhComputeKey # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceRandomSeed # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceRandomBytes # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceHkdfSha256ExtractAndExpand # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsInitialize # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsCtxFree # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsCtxNew # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsFree # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsNew # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsInHandshake # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsDoHandshake # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsHandleAlert # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsCloseNotify # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsCtrlTrafficOut # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsCtrlTrafficIn # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsRead # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsWrite # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsSetVersion # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsSetConnectionEnd # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsSetCipherList # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsSetCompressionMethod # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsSetVerify # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsSetVerifyHost # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsSetSessionId # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsSetCaCertificate # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsSetHostPublicCert # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsSetHostPrivateKey # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsSetCertRevocationList # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsGetVersion # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsGetConnectionEnd # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsGetCurrentCipher # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsGetCurrentCompressionId # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsGetVerify # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsGetSessionId # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsGetClientRandom # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsGetServerRandom # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsGetKeyMaterial # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsGetCaCertificate # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsGetHostPublicCert # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsGetHostPrivateKey # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsGetCertRevocationList # CONSUMES -# AUTOGEN ENDS -# **************************************************************************** -# MU_CHANGE END - -[Depex] - gEdkiiCryptoPpiGuid +## @file +# Implements the BaseCryptLib and TlsLib using the services of the EDK II Crypto +# PPI. +# +# Copyright (C) Microsoft Corporation. All rights reserved. +# Copyright (c) 2020, Hewlett Packard Enterprise Development LP. All rights reserved.
+# Copyright (c) 2022, Loongson Technology Corporation Limited. All rights reserved.
+# SPDX-License-Identifier: BSD-2-Clause-Patent +# +## + +[Defines] + INF_VERSION = 0x0001001B + BASE_NAME = PeiCryptLib + MODULE_UNI_FILE = CryptLib.uni + FILE_GUID = 3E8B50C6-F68C-4212-B903-94A10FE02399 + VERSION_STRING = 1.0 + MODULE_TYPE = PEIM + LIBRARY_CLASS = BaseCryptLib | PEIM + LIBRARY_CLASS = TlsLib | PEIM + +# +# The following information is for reference only and not required by the build tools. +# +# VALID_ARCHITECTURES = IA32 X64 ARM AARCH64 RISCV64 LOONGARCH64 +# + +[Packages] + MdePkg/MdePkg.dec + CryptoPkg/CryptoPkg.dec + +[LibraryClasses] + BaseLib + DebugLib + PeiServicesLib + +[Sources] + PeiCryptLib.c + CryptLib.c + +[Ppis] + gEdkiiCryptoPpiGuid ## CONSUMES + +# MU_CHANGE START +# **************************************************************************** +# AUTOGENERATED BY CryptoPkg\Driver\Packaging\generate_cryptodriver.py +# AUTOGENED AS temp_crypto_pcd.inc.inf +# DO NOT MODIFY +# GENERATED ON: 2022-09-21 13:34:55.465175 + +[Pcd] + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSha1GetContextSize # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSha1Init # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSha1Duplicate # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSha1Update # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSha1Final # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSha1HashAll # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSha256GetContextSize # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSha256Init # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSha256Duplicate # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSha256Update # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSha256Final # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSha256HashAll # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSha384GetContextSize # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSha384Init # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSha384Duplicate # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSha384Update # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSha384Final # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSha384HashAll # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSha512GetContextSize # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSha512Init # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSha512Duplicate # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSha512Update # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSha512Final # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSha512HashAll # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceParallelHash256HashAll # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSm3GetContextSize # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSm3Init # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSm3Duplicate # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSm3Update # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSm3Final # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSm3HashAll # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceHmacSha256New # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceHmacSha256Free # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceHmacSha256SetKey # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceHmacSha256Duplicate # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceHmacSha256Update # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceHmacSha256Final # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceAesGetContextSize # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceAesInit # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceAesCbcEncrypt # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceAesCbcDecrypt # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceRsaNew # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceRsaFree # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceRsaSetKey # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceRsaGetKey # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceRsaGenerateKey # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceRsaCheckKey # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceRsaPkcs1Sign # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceRsaPkcs1Verify # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceRsaPssSign # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceRsaPssVerify # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceRsaGetPrivateKeyFromPem # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceRsaGetPublicKeyFromX509 # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceX509GetSubjectName # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceX509GetCommonName # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceX509GetOrganizationName # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceX509VerifyCert # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceX509ConstructCertificate # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceX509ConstructCertificateStackV # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceX509ConstructCertificateStack # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceX509Free # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceX509StackFree # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceX509GetTBSCert # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServicePkcs5HashPassword # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServicePkcs1v2Encrypt # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServicePkcs7GetSigners # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServicePkcs7FreeSigners # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServicePkcs7GetCertificatesList # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServicePkcs7Sign # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServicePkcs7Verify # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceVerifyEKUsInPkcs7Signature # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServicePkcs7GetAttachedContent # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceAuthenticodeVerify # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceImageTimestampVerify # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceDhNew # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceDhFree # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceDhGenerateParameter # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceDhSetParameter # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceDhGenerateKey # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceDhComputeKey # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceRandomSeed # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceRandomBytes # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceHkdfSha256ExtractAndExpand # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsInitialize # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsCtxFree # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsCtxNew # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsFree # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsNew # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsInHandshake # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsDoHandshake # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsHandleAlert # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsCloseNotify # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsCtrlTrafficOut # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsCtrlTrafficIn # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsRead # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsWrite # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsSetVersion # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsSetConnectionEnd # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsSetCipherList # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsSetCompressionMethod # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsSetVerify # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsSetVerifyHost # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsSetSessionId # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsSetCaCertificate # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsSetHostPublicCert # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsSetHostPrivateKey # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsSetCertRevocationList # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsGetVersion # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsGetConnectionEnd # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsGetCurrentCipher # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsGetCurrentCompressionId # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsGetVerify # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsGetSessionId # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsGetClientRandom # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsGetServerRandom # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsGetKeyMaterial # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsGetCaCertificate # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsGetHostPublicCert # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsGetHostPrivateKey # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsGetCertRevocationList # CONSUMES +# AUTOGEN ENDS +# **************************************************************************** +# MU_CHANGE END + +[Depex] + gEdkiiCryptoPpiGuid diff --git a/CryptoPkg/Library/BaseCryptLibOnProtocolPpi/SmmCryptLib.inf b/CryptoPkg/Library/BaseCryptLibOnProtocolPpi/SmmCryptLib.inf index 4bd7b2e8c5..641593fcae 100644 --- a/CryptoPkg/Library/BaseCryptLibOnProtocolPpi/SmmCryptLib.inf +++ b/CryptoPkg/Library/BaseCryptLibOnProtocolPpi/SmmCryptLib.inf @@ -1,176 +1,176 @@ -## @file -# Implements the BaseCryptLib and TlsLib using the services of the EDK II Crypto -# SMM Protocol. -# -# Copyright (C) Microsoft Corporation. All rights reserved. -# SPDX-License-Identifier: BSD-2-Clause-Patent -# -## - -[Defines] - INF_VERSION = 0x0001001B - BASE_NAME = SmmCryptLib - MODULE_UNI_FILE = CryptLib.uni - FILE_GUID = 5CC6ECC9-E961-46A9-8D5C-6581A060DC0D - VERSION_STRING = 1.0 - MODULE_TYPE = DXE_SMM_DRIVER - LIBRARY_CLASS = BaseCryptLib | DXE_SMM_DRIVER - LIBRARY_CLASS = TlsLib | DXE_SMM_DRIVER - CONSTRUCTOR = SmmCryptLibConstructor - -# -# 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 - SmmServicesTableLib - -[Sources] - SmmCryptLib.c - CryptLib.c - -[Protocols] - gEdkiiSmmCryptoProtocolGuid ## CONSUMES - -[Depex] - gEdkiiSmmCryptoProtocolGuid - -# MU_CHANGE START -# **************************************************************************** -# AUTOGENERATED BY CryptoPkg\Driver\Packaging\generate_cryptodriver.py -# AUTOGENED AS temp_crypto_pcd.inc.inf -# DO NOT MODIFY -# GENERATED ON: 2022-09-21 13:34:55.465175 - -[Pcd] - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSha1GetContextSize # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSha1Init # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSha1Duplicate # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSha1Update # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSha1Final # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSha1HashAll # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSha256GetContextSize # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSha256Init # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSha256Duplicate # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSha256Update # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSha256Final # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSha256HashAll # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSha384GetContextSize # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSha384Init # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSha384Duplicate # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSha384Update # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSha384Final # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSha384HashAll # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSha512GetContextSize # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSha512Init # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSha512Duplicate # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSha512Update # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSha512Final # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSha512HashAll # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceParallelHash256HashAll # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSm3GetContextSize # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSm3Init # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSm3Duplicate # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSm3Update # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSm3Final # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSm3HashAll # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceHmacSha256New # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceHmacSha256Free # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceHmacSha256SetKey # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceHmacSha256Duplicate # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceHmacSha256Update # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceHmacSha256Final # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceAesGetContextSize # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceAesInit # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceAesCbcEncrypt # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceAesCbcDecrypt # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceRsaNew # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceRsaFree # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceRsaSetKey # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceRsaGetKey # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceRsaGenerateKey # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceRsaCheckKey # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceRsaPkcs1Sign # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceRsaPkcs1Verify # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceRsaPssSign # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceRsaPssVerify # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceRsaGetPrivateKeyFromPem # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceRsaGetPublicKeyFromX509 # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceX509GetSubjectName # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceX509GetCommonName # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceX509GetOrganizationName # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceX509VerifyCert # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceX509ConstructCertificate # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceX509ConstructCertificateStackV # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceX509ConstructCertificateStack # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceX509Free # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceX509StackFree # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceX509GetTBSCert # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServicePkcs5HashPassword # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServicePkcs1v2Encrypt # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServicePkcs7GetSigners # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServicePkcs7FreeSigners # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServicePkcs7GetCertificatesList # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServicePkcs7Sign # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServicePkcs7Verify # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceVerifyEKUsInPkcs7Signature # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServicePkcs7GetAttachedContent # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceAuthenticodeVerify # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceImageTimestampVerify # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceDhNew # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceDhFree # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceDhGenerateParameter # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceDhSetParameter # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceDhGenerateKey # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceDhComputeKey # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceRandomSeed # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceRandomBytes # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceHkdfSha256ExtractAndExpand # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsInitialize # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsCtxFree # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsCtxNew # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsFree # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsNew # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsInHandshake # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsDoHandshake # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsHandleAlert # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsCloseNotify # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsCtrlTrafficOut # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsCtrlTrafficIn # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsRead # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsWrite # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsSetVersion # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsSetConnectionEnd # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsSetCipherList # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsSetCompressionMethod # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsSetVerify # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsSetVerifyHost # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsSetSessionId # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsSetCaCertificate # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsSetHostPublicCert # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsSetHostPrivateKey # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsSetCertRevocationList # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsGetVersion # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsGetConnectionEnd # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsGetCurrentCipher # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsGetCurrentCompressionId # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsGetVerify # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsGetSessionId # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsGetClientRandom # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsGetServerRandom # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsGetKeyMaterial # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsGetCaCertificate # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsGetHostPublicCert # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsGetHostPrivateKey # CONSUMES - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsGetCertRevocationList # CONSUMES -# AUTOGEN ENDS -# **************************************************************************** -# MU_CHANGE END +## @file +# Implements the BaseCryptLib and TlsLib using the services of the EDK II Crypto +# SMM Protocol. +# +# Copyright (C) Microsoft Corporation. All rights reserved. +# SPDX-License-Identifier: BSD-2-Clause-Patent +# +## + +[Defines] + INF_VERSION = 0x0001001B + BASE_NAME = SmmCryptLib + MODULE_UNI_FILE = CryptLib.uni + FILE_GUID = 5CC6ECC9-E961-46A9-8D5C-6581A060DC0D + VERSION_STRING = 1.0 + MODULE_TYPE = DXE_SMM_DRIVER + LIBRARY_CLASS = BaseCryptLib | DXE_SMM_DRIVER + LIBRARY_CLASS = TlsLib | DXE_SMM_DRIVER + CONSTRUCTOR = SmmCryptLibConstructor + +# +# 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 + SmmServicesTableLib + +[Sources] + SmmCryptLib.c + CryptLib.c + +[Protocols] + gEdkiiSmmCryptoProtocolGuid ## CONSUMES + +[Depex] + gEdkiiSmmCryptoProtocolGuid + +# MU_CHANGE START +# **************************************************************************** +# AUTOGENERATED BY CryptoPkg\Driver\Packaging\generate_cryptodriver.py +# AUTOGENED AS temp_crypto_pcd.inc.inf +# DO NOT MODIFY +# GENERATED ON: 2022-09-21 13:34:55.465175 + +[Pcd] + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSha1GetContextSize # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSha1Init # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSha1Duplicate # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSha1Update # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSha1Final # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSha1HashAll # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSha256GetContextSize # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSha256Init # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSha256Duplicate # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSha256Update # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSha256Final # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSha256HashAll # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSha384GetContextSize # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSha384Init # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSha384Duplicate # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSha384Update # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSha384Final # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSha384HashAll # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSha512GetContextSize # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSha512Init # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSha512Duplicate # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSha512Update # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSha512Final # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSha512HashAll # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceParallelHash256HashAll # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSm3GetContextSize # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSm3Init # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSm3Duplicate # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSm3Update # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSm3Final # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceSm3HashAll # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceHmacSha256New # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceHmacSha256Free # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceHmacSha256SetKey # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceHmacSha256Duplicate # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceHmacSha256Update # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceHmacSha256Final # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceAesGetContextSize # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceAesInit # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceAesCbcEncrypt # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceAesCbcDecrypt # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceRsaNew # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceRsaFree # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceRsaSetKey # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceRsaGetKey # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceRsaGenerateKey # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceRsaCheckKey # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceRsaPkcs1Sign # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceRsaPkcs1Verify # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceRsaPssSign # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceRsaPssVerify # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceRsaGetPrivateKeyFromPem # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceRsaGetPublicKeyFromX509 # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceX509GetSubjectName # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceX509GetCommonName # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceX509GetOrganizationName # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceX509VerifyCert # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceX509ConstructCertificate # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceX509ConstructCertificateStackV # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceX509ConstructCertificateStack # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceX509Free # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceX509StackFree # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceX509GetTBSCert # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServicePkcs5HashPassword # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServicePkcs1v2Encrypt # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServicePkcs7GetSigners # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServicePkcs7FreeSigners # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServicePkcs7GetCertificatesList # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServicePkcs7Sign # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServicePkcs7Verify # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceVerifyEKUsInPkcs7Signature # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServicePkcs7GetAttachedContent # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceAuthenticodeVerify # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceImageTimestampVerify # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceDhNew # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceDhFree # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceDhGenerateParameter # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceDhSetParameter # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceDhGenerateKey # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceDhComputeKey # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceRandomSeed # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceRandomBytes # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceHkdfSha256ExtractAndExpand # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsInitialize # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsCtxFree # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsCtxNew # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsFree # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsNew # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsInHandshake # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsDoHandshake # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsHandleAlert # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsCloseNotify # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsCtrlTrafficOut # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsCtrlTrafficIn # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsRead # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsWrite # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsSetVersion # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsSetConnectionEnd # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsSetCipherList # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsSetCompressionMethod # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsSetVerify # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsSetVerifyHost # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsSetSessionId # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsSetCaCertificate # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsSetHostPublicCert # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsSetHostPrivateKey # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsSetCertRevocationList # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsGetVersion # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsGetConnectionEnd # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsGetCurrentCipher # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsGetCurrentCompressionId # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsGetVerify # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsGetSessionId # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsGetClientRandom # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsGetServerRandom # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsGetKeyMaterial # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsGetCaCertificate # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsGetHostPublicCert # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsGetHostPrivateKey # CONSUMES + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceTlsGetCertRevocationList # CONSUMES +# AUTOGEN ENDS +# **************************************************************************** +# MU_CHANGE END diff --git a/CryptoPkg/Library/BaseCryptLibOnProtocolPpi/readme.md b/CryptoPkg/Library/BaseCryptLibOnProtocolPpi/readme.md index 731c5893d9..456605eb67 100644 --- a/CryptoPkg/Library/BaseCryptLibOnProtocolPpi/readme.md +++ b/CryptoPkg/Library/BaseCryptLibOnProtocolPpi/readme.md @@ -1,7 +1,7 @@ -# BaseCryptLibOnProtocolPpi - -This is an implementation of BaseCryptLib that uses a protocol. - -This makes binaries smaller, makes servicing easier, and allows crypto to be pre-compiled. - -See CryptoPkg/Driver/readme.md for more information. +# BaseCryptLibOnProtocolPpi + +This is an implementation of BaseCryptLib that uses a protocol. + +This makes binaries smaller, makes servicing easier, and allows crypto to be pre-compiled. + +See CryptoPkg/Driver/readme.md for more information. diff --git a/CryptoPkg/Library/HmacSha1Lib/HmacSha1Lib.inf b/CryptoPkg/Library/HmacSha1Lib/HmacSha1Lib.inf index 9f124d8ebe..aeeb29b112 100644 --- a/CryptoPkg/Library/HmacSha1Lib/HmacSha1Lib.inf +++ b/CryptoPkg/Library/HmacSha1Lib/HmacSha1Lib.inf @@ -1,72 +1,72 @@ -## @file -# Cryptographic Library Instance for DXE_DRIVER. -# -# Caution: This module requires additional review when modified. -# This library will have external input - signature. -# This external input must be validated carefully to avoid security issues such as -# buffer overflow or integer overflow. -# -# Copyright (c) 2009 - 2020, Intel Corporation. All rights reserved.
-# Copyright (c) 2020, Hewlett Packard Enterprise Development LP. All rights reserved.
-# SPDX-License-Identifier: BSD-2-Clause-Patent -# -## - -[Defines] - INF_VERSION = 0x00010005 - BASE_NAME = HmacSha1Lib - MODULE_UNI_FILE = HmacSha1Lib.uni - FILE_GUID = 0c418ebf-7409-4a02-b381-3aae85a89e00 - MODULE_TYPE = DXE_DRIVER - VERSION_STRING = 1.0 - LIBRARY_CLASS = HmacSha1Lib|DXE_DRIVER DXE_CORE UEFI_APPLICATION UEFI_DRIVER - -# -# The following information is for reference only and not required by the build tools. -# -# VALID_ARCHITECTURES = IA32 X64 ARM AARCH64 RISCV64 -# - -[Sources] - CryptHmacSha1.c - # This whole lib is a (hopefully) temporary workaround- this is not best practices - ../BaseCryptLib/SysCall/CrtWrapper.c - ../BaseCryptLib/SysCall/TimerWrapper.c - ../BaseCryptLib/SysCall/BaseMemAllocation.c - - -[Packages] - MdePkg/MdePkg.dec - CryptoPkg/CryptoPkg.dec - -[LibraryClasses] - BaseLib - BaseMemoryLib - MemoryAllocationLib - UefiRuntimeServicesTableLib - DebugLib - OpensslLib - IntrinsicLib - PrintLib - -# -# 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: - # C4090: 'function' : different 'const' qualifiers - # - MSFT:*_*_*_CC_FLAGS = /wd4090 - MSFT:*_*_AARCH64_CC_FLAGS = /U_M_ARM64 /D_M_MS_ARM64 # MU_CHANGE - TCBZ2029 - MSFT:*_*_ARM_CC_FLAGS = /U_M_ARM /D_M_MS_ARM # MU_CHANGE - TCBZ2029 - - # -JCryptoPkg/Include : To disable the use of the system includes provided by RVCT - # --diag_remark=1 : Reduce severity of "#1-D: last line of file ends without a newline" - RVCT:*_*_ARM_CC_FLAGS = -JCryptoPkg/Include --diag_remark=1 - - GCC:*_CLANG35_*_CC_FLAGS = -std=c99 - GCC:*_CLANG38_*_CC_FLAGS = -std=c99 - GCC:*_CLANGPDB_*_CC_FLAGS = -std=c99 -Wno-error=incompatible-pointer-types - - XCODE:*_*_*_CC_FLAGS = -std=c99 +## @file +# Cryptographic Library Instance for DXE_DRIVER. +# +# Caution: This module requires additional review when modified. +# This library will have external input - signature. +# This external input must be validated carefully to avoid security issues such as +# buffer overflow or integer overflow. +# +# Copyright (c) 2009 - 2020, Intel Corporation. All rights reserved.
+# Copyright (c) 2020, Hewlett Packard Enterprise Development LP. All rights reserved.
+# SPDX-License-Identifier: BSD-2-Clause-Patent +# +## + +[Defines] + INF_VERSION = 0x00010005 + BASE_NAME = HmacSha1Lib + MODULE_UNI_FILE = HmacSha1Lib.uni + FILE_GUID = 0c418ebf-7409-4a02-b381-3aae85a89e00 + MODULE_TYPE = DXE_DRIVER + VERSION_STRING = 1.0 + LIBRARY_CLASS = HmacSha1Lib|DXE_DRIVER DXE_CORE UEFI_APPLICATION UEFI_DRIVER + +# +# The following information is for reference only and not required by the build tools. +# +# VALID_ARCHITECTURES = IA32 X64 ARM AARCH64 RISCV64 +# + +[Sources] + CryptHmacSha1.c + # This whole lib is a (hopefully) temporary workaround- this is not best practices + ../BaseCryptLib/SysCall/CrtWrapper.c + ../BaseCryptLib/SysCall/TimerWrapper.c + ../BaseCryptLib/SysCall/BaseMemAllocation.c + + +[Packages] + MdePkg/MdePkg.dec + CryptoPkg/CryptoPkg.dec + +[LibraryClasses] + BaseLib + BaseMemoryLib + MemoryAllocationLib + UefiRuntimeServicesTableLib + DebugLib + OpensslLib + IntrinsicLib + PrintLib + +# +# 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: + # C4090: 'function' : different 'const' qualifiers + # + MSFT:*_*_*_CC_FLAGS = /wd4090 + MSFT:*_*_AARCH64_CC_FLAGS = /U_M_ARM64 /D_M_MS_ARM64 # MU_CHANGE - TCBZ2029 + MSFT:*_*_ARM_CC_FLAGS = /U_M_ARM /D_M_MS_ARM # MU_CHANGE - TCBZ2029 + + # -JCryptoPkg/Include : To disable the use of the system includes provided by RVCT + # --diag_remark=1 : Reduce severity of "#1-D: last line of file ends without a newline" + RVCT:*_*_ARM_CC_FLAGS = -JCryptoPkg/Include --diag_remark=1 + + GCC:*_CLANG35_*_CC_FLAGS = -std=c99 + GCC:*_CLANG38_*_CC_FLAGS = -std=c99 + GCC:*_CLANGPDB_*_CC_FLAGS = -std=c99 -Wno-error=incompatible-pointer-types + + XCODE:*_*_*_CC_FLAGS = -std=c99 diff --git a/CryptoPkg/Library/HmacSha1Lib/HmacSha1Lib.uni b/CryptoPkg/Library/HmacSha1Lib/HmacSha1Lib.uni index 16f79aa962..c55fda2535 100644 --- a/CryptoPkg/Library/HmacSha1Lib/HmacSha1Lib.uni +++ b/CryptoPkg/Library/HmacSha1Lib/HmacSha1Lib.uni @@ -1,19 +1,19 @@ -// /** @file -// Cryptographic Library Instance for DXE_DRIVER. -// -// Caution: This module requires additional review when modified. -// This library will have external input - signature. -// This external input must be validated carefully to avoid security issues such as -// buffer overflow or integer overflow. -// -// Copyright (c) 2009 - 2018, Intel Corporation. All rights reserved.
-// -// SPDX-License-Identifier: BSD-2-Clause-Patent -// -// **/ - - -#string STR_MODULE_ABSTRACT #language en-US "Cryptographic Library for HmacSha1 for DXE_DRIVER" - -#string STR_MODULE_DESCRIPTION #language en-US "Caution: This module requires additional review when modified. This library will have external input - signature. This external input must be validated carefully to avoid security issues such as buffer overflow or integer overflow." - +// /** @file +// Cryptographic Library Instance for DXE_DRIVER. +// +// Caution: This module requires additional review when modified. +// This library will have external input - signature. +// This external input must be validated carefully to avoid security issues such as +// buffer overflow or integer overflow. +// +// Copyright (c) 2009 - 2018, Intel Corporation. All rights reserved.
+// +// SPDX-License-Identifier: BSD-2-Clause-Patent +// +// **/ + + +#string STR_MODULE_ABSTRACT #language en-US "Cryptographic Library for HmacSha1 for DXE_DRIVER" + +#string STR_MODULE_DESCRIPTION #language en-US "Caution: This module requires additional review when modified. This library will have external input - signature. This external input must be validated carefully to avoid security issues such as buffer overflow or integer overflow." + diff --git a/CryptoPkg/Library/HmacSha1Lib/HmacSha1LibNull.inf b/CryptoPkg/Library/HmacSha1Lib/HmacSha1LibNull.inf index 15464403ca..5dd123b9fe 100644 --- a/CryptoPkg/Library/HmacSha1Lib/HmacSha1LibNull.inf +++ b/CryptoPkg/Library/HmacSha1Lib/HmacSha1LibNull.inf @@ -1,62 +1,62 @@ -## @file -# Cryptographic Library Instance for DXE_DRIVER. -# -# Caution: This module requires additional review when modified. -# This library will have external input - signature. -# This external input must be validated carefully to avoid security issues such as -# buffer overflow or integer overflow. -# -# Copyright (c) 2009 - 2020, Intel Corporation. All rights reserved.
-# Copyright (c) 2020, Hewlett Packard Enterprise Development LP. All rights reserved.
-# SPDX-License-Identifier: BSD-2-Clause-Patent -# -## - -[Defines] - INF_VERSION = 0x00010005 - BASE_NAME = HmacSha1Lib - MODULE_UNI_FILE = HmacSha1Lib.uni - FILE_GUID = d11b624a-928e-4962-9799-8b5a223bafaf - MODULE_TYPE = DXE_DRIVER - VERSION_STRING = 1.0 - LIBRARY_CLASS = HmacSha1Lib|DXE_DRIVER DXE_CORE UEFI_APPLICATION UEFI_DRIVER - -# -# The following information is for reference only and not required by the build tools. -# -# VALID_ARCHITECTURES = IA32 X64 ARM AARCH64 RISCV64 -# - -[Sources] - CryptHmacSha1Null.c - -[Packages] - MdePkg/MdePkg.dec - CryptoPkg/CryptoPkg.dec - -[LibraryClasses] - BaseLib - BaseMemoryLib - DebugLib - -# -# 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: - # C4090: 'function' : different 'const' qualifiers - # - MSFT:*_*_*_CC_FLAGS = /wd4090 - MSFT:*_*_AARCH64_CC_FLAGS = /U_M_ARM64 /D_M_MS_ARM64 # MU_CHANGE - TCBZ2029 - MSFT:*_*_ARM_CC_FLAGS = /U_M_ARM /D_M_MS_ARM # MU_CHANGE - TCBZ2029 - - # -JCryptoPkg/Include : To disable the use of the system includes provided by RVCT - # --diag_remark=1 : Reduce severity of "#1-D: last line of file ends without a newline" - RVCT:*_*_ARM_CC_FLAGS = -JCryptoPkg/Include --diag_remark=1 - - GCC:*_CLANG35_*_CC_FLAGS = -std=c99 - GCC:*_CLANG38_*_CC_FLAGS = -std=c99 - GCC:*_CLANGPDB_*_CC_FLAGS = -std=c99 -Wno-error=incompatible-pointer-types - - XCODE:*_*_*_CC_FLAGS = -std=c99 +## @file +# Cryptographic Library Instance for DXE_DRIVER. +# +# Caution: This module requires additional review when modified. +# This library will have external input - signature. +# This external input must be validated carefully to avoid security issues such as +# buffer overflow or integer overflow. +# +# Copyright (c) 2009 - 2020, Intel Corporation. All rights reserved.
+# Copyright (c) 2020, Hewlett Packard Enterprise Development LP. All rights reserved.
+# SPDX-License-Identifier: BSD-2-Clause-Patent +# +## + +[Defines] + INF_VERSION = 0x00010005 + BASE_NAME = HmacSha1Lib + MODULE_UNI_FILE = HmacSha1Lib.uni + FILE_GUID = d11b624a-928e-4962-9799-8b5a223bafaf + MODULE_TYPE = DXE_DRIVER + VERSION_STRING = 1.0 + LIBRARY_CLASS = HmacSha1Lib|DXE_DRIVER DXE_CORE UEFI_APPLICATION UEFI_DRIVER + +# +# The following information is for reference only and not required by the build tools. +# +# VALID_ARCHITECTURES = IA32 X64 ARM AARCH64 RISCV64 +# + +[Sources] + CryptHmacSha1Null.c + +[Packages] + MdePkg/MdePkg.dec + CryptoPkg/CryptoPkg.dec + +[LibraryClasses] + BaseLib + BaseMemoryLib + DebugLib + +# +# 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: + # C4090: 'function' : different 'const' qualifiers + # + MSFT:*_*_*_CC_FLAGS = /wd4090 + MSFT:*_*_AARCH64_CC_FLAGS = /U_M_ARM64 /D_M_MS_ARM64 # MU_CHANGE - TCBZ2029 + MSFT:*_*_ARM_CC_FLAGS = /U_M_ARM /D_M_MS_ARM # MU_CHANGE - TCBZ2029 + + # -JCryptoPkg/Include : To disable the use of the system includes provided by RVCT + # --diag_remark=1 : Reduce severity of "#1-D: last line of file ends without a newline" + RVCT:*_*_ARM_CC_FLAGS = -JCryptoPkg/Include --diag_remark=1 + + GCC:*_CLANG35_*_CC_FLAGS = -std=c99 + GCC:*_CLANG38_*_CC_FLAGS = -std=c99 + GCC:*_CLANGPDB_*_CC_FLAGS = -std=c99 -Wno-error=incompatible-pointer-types + + XCODE:*_*_*_CC_FLAGS = -std=c99 diff --git a/CryptoPkg/Library/IntrinsicLib/IntrinsicLib.inf b/CryptoPkg/Library/IntrinsicLib/IntrinsicLib.inf index 1b2b2111cc..404a8483cd 100644 --- a/CryptoPkg/Library/IntrinsicLib/IntrinsicLib.inf +++ b/CryptoPkg/Library/IntrinsicLib/IntrinsicLib.inf @@ -58,7 +58,7 @@ [LibraryClasses] BaseLib BaseMemoryLib - FltUsedLib # MU_CHANGE + FltUsedLib # MU_CHANGE [BuildOptions] # @@ -76,7 +76,7 @@ MSFT:RELEASE_*_IA32_CC_FLAGS == /nologo /c /WX /GS- /W4 /Gs32768 /D UNICODE /O1b2 /FIAutoGen.h /EHs-c- /GR- /GF MSFT:DEBUG_*_X64_CC_FLAGS == /nologo /c /WX /GS- /X /W4 /Gs32768 /D UNICODE /O1b2s /Gy /FIAutoGen.h /EHs-c- /GR- /GF /Zi /Gm MSFT:RELEASE_*_X64_CC_FLAGS == /nologo /c /WX /GS- /X /W4 /Gs32768 /D UNICODE /O1b2s /Gy /FIAutoGen.h /EHs-c- /GR- /GF - MSFT:DEBUG_*_AARCH64_CC_FLAGS == /nologo /c /WX /GS- /X /W4 /Gs32768 /D UNICODE /O1b2s /Gy /FIAutoGen.h /EHs-c- /GR- /GF /Zi /Gm - MSFT:RELEASE_*_AARCH64_CC_FLAGS == /nologo /c /WX /GS- /X /W4 /Gs32768 /D UNICODE /O1b2s /Gy /FIAutoGen.h /EHs-c- /GR- /GF + MSFT:DEBUG_*_AARCH64_CC_FLAGS == /nologo /c /WX /GS- /X /W4 /Gs32768 /D UNICODE /O1b2s /Gy /FIAutoGen.h /EHs-c- /GR- /GF /Zi /Gm + MSFT:RELEASE_*_AARCH64_CC_FLAGS == /nologo /c /WX /GS- /X /W4 /Gs32768 /D UNICODE /O1b2s /Gy /FIAutoGen.h /EHs-c- /GR- /GF INTEL:*_*_*_CC_FLAGS = /Oi- - MSFT:*_*_*_CC_FLAGS = /Oi- #MU_CHANGE #TCBZ2029 + MSFT:*_*_*_CC_FLAGS = /Oi- #MU_CHANGE #TCBZ2029 diff --git a/CryptoPkg/Test/CryptoPkgHostTest.dsc b/CryptoPkg/Test/CryptoPkgHostTest.dsc index 3942143627..cc11eac324 100644 --- a/CryptoPkg/Test/CryptoPkgHostTest.dsc +++ b/CryptoPkg/Test/CryptoPkgHostTest.dsc @@ -1,35 +1,35 @@ -## @file -# CryptoPkg DSC file used to build host-based unit tests. -# -# Copyright (c) Microsoft Corporation.
-# SPDX-License-Identifier: BSD-2-Clause-Patent -# -## - -[Defines] - PLATFORM_NAME = CryptoPkgHostTest - PLATFORM_GUID = C7F97D6D-54AC-45A9-8197-CC99B20CC7EC - PLATFORM_VERSION = 0.1 - DSC_SPECIFICATION = 0x00010005 - OUTPUT_DIRECTORY = Build/CryptoPkg/HostTest - SUPPORTED_ARCHITECTURES = IA32|X64|AARCH64|ARM - BUILD_TARGETS = NOOPT - SKUID_IDENTIFIER = DEFAULT - -!include UnitTestFrameworkPkg/UnitTestFrameworkPkgHost.dsc.inc - -[LibraryClasses] - OpensslLib|CryptoPkg/Library/OpensslLib/OpensslLib.inf - BaseCryptLib|CryptoPkg/Library/BaseCryptLib/UnitTestHostBaseCryptLib.inf - -[LibraryClasses.AARCH64, LibraryClasses.ARM] - RngLib|MdePkg/Library/BaseRngLibNull/BaseRngLibNull.inf - -[LibraryClasses.X64, LibraryClasses.IA32] - RngLib|MdePkg/Library/BaseRngLib/BaseRngLib.inf - -[Components] - # - # Build HOST_APPLICATION that tests the SampleUnitTest - # - CryptoPkg/Test/UnitTest/Library/BaseCryptLib/TestBaseCryptLibHost.inf +## @file +# CryptoPkg DSC file used to build host-based unit tests. +# +# Copyright (c) Microsoft Corporation.
+# SPDX-License-Identifier: BSD-2-Clause-Patent +# +## + +[Defines] + PLATFORM_NAME = CryptoPkgHostTest + PLATFORM_GUID = C7F97D6D-54AC-45A9-8197-CC99B20CC7EC + PLATFORM_VERSION = 0.1 + DSC_SPECIFICATION = 0x00010005 + OUTPUT_DIRECTORY = Build/CryptoPkg/HostTest + SUPPORTED_ARCHITECTURES = IA32|X64|AARCH64|ARM + BUILD_TARGETS = NOOPT + SKUID_IDENTIFIER = DEFAULT + +!include UnitTestFrameworkPkg/UnitTestFrameworkPkgHost.dsc.inc + +[LibraryClasses] + OpensslLib|CryptoPkg/Library/OpensslLib/OpensslLib.inf + BaseCryptLib|CryptoPkg/Library/BaseCryptLib/UnitTestHostBaseCryptLib.inf + +[LibraryClasses.AARCH64, LibraryClasses.ARM] + RngLib|MdePkg/Library/BaseRngLibNull/BaseRngLibNull.inf + +[LibraryClasses.X64, LibraryClasses.IA32] + RngLib|MdePkg/Library/BaseRngLib/BaseRngLib.inf + +[Components] + # + # Build HOST_APPLICATION that tests the SampleUnitTest + # + CryptoPkg/Test/UnitTest/Library/BaseCryptLib/TestBaseCryptLibHost.inf diff --git a/CryptoPkg/Test/UnitTest/Library/BaseCryptLib/BaseCryptLibUnitTestApp.inf b/CryptoPkg/Test/UnitTest/Library/BaseCryptLib/BaseCryptLibUnitTestApp.inf index fecf94a2e2..4b72b33a2d 100644 --- a/CryptoPkg/Test/UnitTest/Library/BaseCryptLib/BaseCryptLibUnitTestApp.inf +++ b/CryptoPkg/Test/UnitTest/Library/BaseCryptLib/BaseCryptLibUnitTestApp.inf @@ -1,55 +1,55 @@ -## @file -# BaseCryptLib UnitTest built for execution in UEFI Shell. -# -# Copyright (c) Microsoft Corporation.
-# SPDX-License-Identifier: BSD-2-Clause-Patent -## - -[Defines] - INF_VERSION = 0x00010006 - BASE_NAME = BaseCryptLibUnitTestApp - FILE_GUID = ed54ee8c-ef7a-41f2-83d5-0e0d4cd88c21 - MODULE_TYPE = UEFI_APPLICATION - VERSION_STRING = 1.0 - ENTRY_POINT = DxeEntryPoint - -# -# The following information is for reference only and not required by the build tools. -# -# VALID_ARCHITECTURES = IA32 X64 -# - -[Sources] - UnitTestMain.c - BaseCryptLibUnitTests.c - TestBaseCryptLib.h - HashTests.c - HmacTests.c - BlockCipherTests.c - RsaTests.c - RsaPkcs7Tests.c - Pkcs5Pbkdf2Tests.c - AuthenticodeTests.c - TSTests.c - DhTests.c - RandTests.c - Pkcs7EkuTests.c - OaepEncryptTests.c - RsaPssTests.c - HkdfTests.c - AeadAesGcmTests.c - BnTests.c - EcTests.c - X509Tests.c - -[Packages] - MdePkg/MdePkg.dec - CryptoPkg/CryptoPkg.dec - -[LibraryClasses] - UefiApplicationEntryPoint - BaseLib - DebugLib - UnitTestLib - PrintLib - BaseCryptLib +## @file +# BaseCryptLib UnitTest built for execution in UEFI Shell. +# +# Copyright (c) Microsoft Corporation.
+# SPDX-License-Identifier: BSD-2-Clause-Patent +## + +[Defines] + INF_VERSION = 0x00010006 + BASE_NAME = BaseCryptLibUnitTestApp + FILE_GUID = ed54ee8c-ef7a-41f2-83d5-0e0d4cd88c21 + MODULE_TYPE = UEFI_APPLICATION + VERSION_STRING = 1.0 + ENTRY_POINT = DxeEntryPoint + +# +# The following information is for reference only and not required by the build tools. +# +# VALID_ARCHITECTURES = IA32 X64 +# + +[Sources] + UnitTestMain.c + BaseCryptLibUnitTests.c + TestBaseCryptLib.h + HashTests.c + HmacTests.c + BlockCipherTests.c + RsaTests.c + RsaPkcs7Tests.c + Pkcs5Pbkdf2Tests.c + AuthenticodeTests.c + TSTests.c + DhTests.c + RandTests.c + Pkcs7EkuTests.c + OaepEncryptTests.c + RsaPssTests.c + HkdfTests.c + AeadAesGcmTests.c + BnTests.c + EcTests.c + X509Tests.c + +[Packages] + MdePkg/MdePkg.dec + CryptoPkg/CryptoPkg.dec + +[LibraryClasses] + UefiApplicationEntryPoint + BaseLib + DebugLib + UnitTestLib + PrintLib + BaseCryptLib diff --git a/MdeModulePkg/Application/HelloWorld/HelloWorld.ver b/MdeModulePkg/Application/HelloWorld/HelloWorld.ver index df2f410b1d..d817023e80 100644 --- a/MdeModulePkg/Application/HelloWorld/HelloWorld.ver +++ b/MdeModulePkg/Application/HelloWorld/HelloWorld.ver @@ -1,5 +1,5 @@ -{ - "FileVersion" : "1.0.0.0", - "OriginalFilename" : "HelloWorld.efi", - "CompanyName" : "Example Company Name" +{ + "FileVersion" : "1.0.0.0", + "OriginalFilename" : "HelloWorld.efi", + "CompanyName" : "Example Company Name" } \ No newline at end of file diff --git a/MdeModulePkg/Application/SmiHandlerProfileInfo/SmiHandlerProfileAuditTestApp.inf b/MdeModulePkg/Application/SmiHandlerProfileInfo/SmiHandlerProfileAuditTestApp.inf index 3d0962600f..0ef5e6b4b4 100644 --- a/MdeModulePkg/Application/SmiHandlerProfileInfo/SmiHandlerProfileAuditTestApp.inf +++ b/MdeModulePkg/Application/SmiHandlerProfileInfo/SmiHandlerProfileAuditTestApp.inf @@ -1,59 +1,59 @@ -## @file -# Shell application to dump SMI handler profile information. -# -# Note that if the feature is not enabled by setting PcdSmiHandlerProfilePropertyMask, -# the application will not display SMI handler profile information. -# -# Copyright (c) 2017, Intel Corporation. All rights reserved.
-# SPDX-License-Identifier: BSD-2-Clause-Patent -# -## - -[Defines] - INF_VERSION = 0x00010005 - #BASE_NAME = SmiHandlerProfileInfo ## MS_CHANGE - Rename app to be picked up by build scripts. - BASE_NAME = SmiHandlerProfileAuditTestApp - MODULE_UNI_FILE = SmiHandlerProfileInfo.uni - FILE_GUID = 611EA796-8DF8-4BB6-91FE-6540ED70DC66 - MODULE_TYPE = UEFI_APPLICATION - VERSION_STRING = 1.0 - ENTRY_POINT = SmiHandlerProfileInfoEntrypoint - -[Sources] - SmiHandlerProfileInfo.c - -[Packages] - MdePkg/MdePkg.dec - MdeModulePkg/MdeModulePkg.dec - -[LibraryClasses] - UefiApplicationEntryPoint - BaseLib - BaseMemoryLib - MemoryAllocationLib - DebugLib - UefiBootServicesTableLib - UefiRuntimeServicesTableLib - UefiLib - PrintLib - DevicePathLib - DxeServicesLib - -[Protocols] - gEfiSmmCommunicationProtocolGuid ## CONSUMES - gEfiSmmSwDispatch2ProtocolGuid ## SOMETIMES_CONSUMES - gEfiSmmSxDispatch2ProtocolGuid ## SOMETIMES_CONSUMES - gEfiSmmPowerButtonDispatch2ProtocolGuid ## SOMETIMES_CONSUMES - gEfiSmmStandbyButtonDispatch2ProtocolGuid ## SOMETIMES_CONSUMES - gEfiSmmPeriodicTimerDispatch2ProtocolGuid ## SOMETIMES_CONSUMES - gEfiSmmGpiDispatch2ProtocolGuid ## SOMETIMES_CONSUMES - gEfiSmmIoTrapDispatch2ProtocolGuid ## SOMETIMES_CONSUMES - gEfiSmmUsbDispatch2ProtocolGuid ## SOMETIMES_CONSUMES - -[Guids] - gEdkiiPiSmmCommunicationRegionTableGuid ## CONSUMES ## SystemTable - gSmiHandlerProfileGuid ## SOMETIMES_CONSUMES ## GUID # SmiHandlerRegister - -[UserExtensions.TianoCore."ExtraFiles"] - SmiHandlerProfileInfoExtra.uni - +## @file +# Shell application to dump SMI handler profile information. +# +# Note that if the feature is not enabled by setting PcdSmiHandlerProfilePropertyMask, +# the application will not display SMI handler profile information. +# +# Copyright (c) 2017, Intel Corporation. All rights reserved.
+# SPDX-License-Identifier: BSD-2-Clause-Patent +# +## + +[Defines] + INF_VERSION = 0x00010005 + #BASE_NAME = SmiHandlerProfileInfo ## MS_CHANGE - Rename app to be picked up by build scripts. + BASE_NAME = SmiHandlerProfileAuditTestApp + MODULE_UNI_FILE = SmiHandlerProfileInfo.uni + FILE_GUID = 611EA796-8DF8-4BB6-91FE-6540ED70DC66 + MODULE_TYPE = UEFI_APPLICATION + VERSION_STRING = 1.0 + ENTRY_POINT = SmiHandlerProfileInfoEntrypoint + +[Sources] + SmiHandlerProfileInfo.c + +[Packages] + MdePkg/MdePkg.dec + MdeModulePkg/MdeModulePkg.dec + +[LibraryClasses] + UefiApplicationEntryPoint + BaseLib + BaseMemoryLib + MemoryAllocationLib + DebugLib + UefiBootServicesTableLib + UefiRuntimeServicesTableLib + UefiLib + PrintLib + DevicePathLib + DxeServicesLib + +[Protocols] + gEfiSmmCommunicationProtocolGuid ## CONSUMES + gEfiSmmSwDispatch2ProtocolGuid ## SOMETIMES_CONSUMES + gEfiSmmSxDispatch2ProtocolGuid ## SOMETIMES_CONSUMES + gEfiSmmPowerButtonDispatch2ProtocolGuid ## SOMETIMES_CONSUMES + gEfiSmmStandbyButtonDispatch2ProtocolGuid ## SOMETIMES_CONSUMES + gEfiSmmPeriodicTimerDispatch2ProtocolGuid ## SOMETIMES_CONSUMES + gEfiSmmGpiDispatch2ProtocolGuid ## SOMETIMES_CONSUMES + gEfiSmmIoTrapDispatch2ProtocolGuid ## SOMETIMES_CONSUMES + gEfiSmmUsbDispatch2ProtocolGuid ## SOMETIMES_CONSUMES + +[Guids] + gEdkiiPiSmmCommunicationRegionTableGuid ## CONSUMES ## SystemTable + gSmiHandlerProfileGuid ## SOMETIMES_CONSUMES ## GUID # SmiHandlerRegister + +[UserExtensions.TianoCore."ExtraFiles"] + SmiHandlerProfileInfoExtra.uni + diff --git a/MdeModulePkg/Library/BaseExceptionPersistenceLibNull/BaseExceptionPersistenceLibNull.inf b/MdeModulePkg/Library/BaseExceptionPersistenceLibNull/BaseExceptionPersistenceLibNull.inf index 7a9b21f249..d95247967c 100644 --- a/MdeModulePkg/Library/BaseExceptionPersistenceLibNull/BaseExceptionPersistenceLibNull.inf +++ b/MdeModulePkg/Library/BaseExceptionPersistenceLibNull/BaseExceptionPersistenceLibNull.inf @@ -1,26 +1,26 @@ -## @file BaseExceptionPersistenceLibNull.inf -# -# NULL implementation of ExceptionPersistenceLib -# -# Copyright (c) Microsoft Corporation. -# SPDX-License-Identifier: BSD-2-Clause-Patent -## - -[Defines] - INF_VERSION = 0x00010005 - BASE_NAME = BaseExceptionPersistenceLibNull - FILE_GUID = adefa38d-ea8c-4418-beb5-ff9e13ea2260 - MODULE_TYPE = BASE - VERSION_STRING = 1.0 - LIBRARY_CLASS = ExceptionPersistenceLib - -# -# VALID_ARCHITECTURES = IA32 X64 -# - -[Sources] - BaseExceptionPersistenceLibNull.c - -[Packages] - MdePkg/MdePkg.dec - MdeModulePkg/MdeModulePkg.dec +## @file BaseExceptionPersistenceLibNull.inf +# +# NULL implementation of ExceptionPersistenceLib +# +# Copyright (c) Microsoft Corporation. +# SPDX-License-Identifier: BSD-2-Clause-Patent +## + +[Defines] + INF_VERSION = 0x00010005 + BASE_NAME = BaseExceptionPersistenceLibNull + FILE_GUID = adefa38d-ea8c-4418-beb5-ff9e13ea2260 + MODULE_TYPE = BASE + VERSION_STRING = 1.0 + LIBRARY_CLASS = ExceptionPersistenceLib + +# +# VALID_ARCHITECTURES = IA32 X64 +# + +[Sources] + BaseExceptionPersistenceLibNull.c + +[Packages] + MdePkg/MdePkg.dec + MdeModulePkg/MdeModulePkg.dec diff --git a/MdeModulePkg/Library/CapsulePersistLibNull/CapsulePersistLibNull.inf b/MdeModulePkg/Library/CapsulePersistLibNull/CapsulePersistLibNull.inf index 1b3bdc16ea..d9f0aae6a6 100644 --- a/MdeModulePkg/Library/CapsulePersistLibNull/CapsulePersistLibNull.inf +++ b/MdeModulePkg/Library/CapsulePersistLibNull/CapsulePersistLibNull.inf @@ -1,36 +1,36 @@ -## @file CapsulePersistLibNull.inf -# A null implementation of the CapsulePersistLib -# -## -# Copyright (c) Microsoft Corporation. All rights reserved. -# SPDX-License-Identifier: BSD-2-Clause-Patent -# -## - - -[Defines] - INF_VERSION = 0x00010017 - BASE_NAME = CapsulePersistLibNull - FILE_GUID = 96AAE710-21AB-4881-9D92-8AD19479BB36 - VERSION_STRING = 1.0 - MODULE_TYPE = DXE_RUNTIME_DRIVER - LIBRARY_CLASS = CapsulePersistLib - -# -# The following information is for reference only and not required by the build tools. -# -# VALID_ARCHITECTURES = IA32 X64 -# - - -[Sources] - CapsulePersistLibNull.c - - -[Packages] - MdePkg/MdePkg.dec - MdeModulePkg/MdeModulePkg.dec - - -[LibraryClasses] - +## @file CapsulePersistLibNull.inf +# A null implementation of the CapsulePersistLib +# +## +# Copyright (c) Microsoft Corporation. All rights reserved. +# SPDX-License-Identifier: BSD-2-Clause-Patent +# +## + + +[Defines] + INF_VERSION = 0x00010017 + BASE_NAME = CapsulePersistLibNull + FILE_GUID = 96AAE710-21AB-4881-9D92-8AD19479BB36 + VERSION_STRING = 1.0 + MODULE_TYPE = DXE_RUNTIME_DRIVER + LIBRARY_CLASS = CapsulePersistLib + +# +# The following information is for reference only and not required by the build tools. +# +# VALID_ARCHITECTURES = IA32 X64 +# + + +[Sources] + CapsulePersistLibNull.c + + +[Packages] + MdePkg/MdePkg.dec + MdeModulePkg/MdeModulePkg.dec + + +[LibraryClasses] + diff --git a/MdeModulePkg/Library/DeviceStateLib/DeviceStateLib.inf b/MdeModulePkg/Library/DeviceStateLib/DeviceStateLib.inf index 17c6101e76..a85ff14715 100644 --- a/MdeModulePkg/Library/DeviceStateLib/DeviceStateLib.inf +++ b/MdeModulePkg/Library/DeviceStateLib/DeviceStateLib.inf @@ -1,33 +1,33 @@ -## @file -# Library to get and set the device state -# -# Copyright (C) Microsoft Corporation. All rights reserved. -# SPDX-License-Identifier: BSD-2-Clause-Patent -# -# MU_CHANGE: new file -## - - -[Defines] -INF_VERSION = 0x00010017 -BASE_NAME = DeviceStateLib -FILE_GUID = 49F18455-FE0D-4DFC-B88B-BEC283BB46DD -VERSION_STRING = 1.0 -MODULE_TYPE = BASE -LIBRARY_CLASS = DeviceStateLib - -[LibraryClasses] -DebugLib -MemoryAllocationLib -BaseMemoryLib -PcdLib - -[Packages] -MdePkg/MdePkg.dec -MdeModulePkg/MdeModulePkg.dec - -[Sources] -DeviceStateLib.c - -[Pcd] -gEfiMdeModulePkgTokenSpaceGuid.PcdDeviceStateBitmask +## @file +# Library to get and set the device state +# +# Copyright (C) Microsoft Corporation. All rights reserved. +# SPDX-License-Identifier: BSD-2-Clause-Patent +# +# MU_CHANGE: new file +## + + +[Defines] +INF_VERSION = 0x00010017 +BASE_NAME = DeviceStateLib +FILE_GUID = 49F18455-FE0D-4DFC-B88B-BEC283BB46DD +VERSION_STRING = 1.0 +MODULE_TYPE = BASE +LIBRARY_CLASS = DeviceStateLib + +[LibraryClasses] +DebugLib +MemoryAllocationLib +BaseMemoryLib +PcdLib + +[Packages] +MdePkg/MdePkg.dec +MdeModulePkg/MdeModulePkg.dec + +[Sources] +DeviceStateLib.c + +[Pcd] +gEfiMdeModulePkgTokenSpaceGuid.PcdDeviceStateBitmask diff --git a/MdeModulePkg/Library/DeviceStateLib/Readme.md b/MdeModulePkg/Library/DeviceStateLib/Readme.md index fa6ec94696..9b7e9e12ef 100644 --- a/MdeModulePkg/Library/DeviceStateLib/Readme.md +++ b/MdeModulePkg/Library/DeviceStateLib/Readme.md @@ -1,32 +1,32 @@ -# DeviceStateLib - -## About - -The MsCorePkg provides the necessary functions to store platform specific device -states. These device states can then be queried by any element within the boot -environment to enable special code paths. In this library implementation a -bitmask is stored in a PCD to signify what modes are active. - -The default bits in the bitmask are set in DeviceStateLib.h - but each platform -is expected to implement its own header to define the platform specific device -states or to define any of the unused bits: - -* BIT 0: DEVICE_STATE_SECUREBOOT_OFF - UEFI Secure Boot disabled -* BIT 1: DEVICE_STATE_MANUFACTURING_MODE - Device is in an OEM defined - manufacturing mode -* BIT 2: DEVICE_STATE_DEVELOPMENT_BUILD_ENABLED - Device is a development - build. Non-production features might be enabled -* BIT 3: DEVICE_STATE_SOURCE_DEBUG_ENABLED - Source debug mode is enabled - allowing a user to connect and control the device -* BIT 4: DEVICE_STATE_UNDEFINED - Set by the platform -* BIT 5: DEVICE_STATE_UNIT_TEST_MODE - Device has a unit test build. Some - features are disabled to allow for unit tests in UEFI Shell -* BIT 24: DEVICE_STATE_PLATFORM_MODE_0 -* BIT 25: DEVICE_STATE_PLATFORM_MODE_1 -* BIT 26: DEVICE_STATE_PLATFORM_MODE_2 -* BIT 27: DEVICE_STATE_PLATFORM_MODE_3 - -## Copyright - -Copyright (C) Microsoft Corporation. All rights reserved. -SPDX-License-Identifier: BSD-2-Clause-Patent +# DeviceStateLib + +## About + +The MsCorePkg provides the necessary functions to store platform specific device +states. These device states can then be queried by any element within the boot +environment to enable special code paths. In this library implementation a +bitmask is stored in a PCD to signify what modes are active. + +The default bits in the bitmask are set in DeviceStateLib.h - but each platform +is expected to implement its own header to define the platform specific device +states or to define any of the unused bits: + +* BIT 0: DEVICE_STATE_SECUREBOOT_OFF - UEFI Secure Boot disabled +* BIT 1: DEVICE_STATE_MANUFACTURING_MODE - Device is in an OEM defined + manufacturing mode +* BIT 2: DEVICE_STATE_DEVELOPMENT_BUILD_ENABLED - Device is a development + build. Non-production features might be enabled +* BIT 3: DEVICE_STATE_SOURCE_DEBUG_ENABLED - Source debug mode is enabled + allowing a user to connect and control the device +* BIT 4: DEVICE_STATE_UNDEFINED - Set by the platform +* BIT 5: DEVICE_STATE_UNIT_TEST_MODE - Device has a unit test build. Some + features are disabled to allow for unit tests in UEFI Shell +* BIT 24: DEVICE_STATE_PLATFORM_MODE_0 +* BIT 25: DEVICE_STATE_PLATFORM_MODE_1 +* BIT 26: DEVICE_STATE_PLATFORM_MODE_2 +* BIT 27: DEVICE_STATE_PLATFORM_MODE_3 + +## Copyright + +Copyright (C) Microsoft Corporation. All rights reserved. +SPDX-License-Identifier: BSD-2-Clause-Patent diff --git a/MdeModulePkg/Library/MemoryBinOverrideLibNull/MemoryBinOverrideLibNull.inf b/MdeModulePkg/Library/MemoryBinOverrideLibNull/MemoryBinOverrideLibNull.inf index 413fab5284..3b33379d89 100644 --- a/MdeModulePkg/Library/MemoryBinOverrideLibNull/MemoryBinOverrideLibNull.inf +++ b/MdeModulePkg/Library/MemoryBinOverrideLibNull/MemoryBinOverrideLibNull.inf @@ -1,31 +1,31 @@ -## @file -# NULL implementation of the memory bin override lib. -# -# Copyright (c) Microsoft Corporation. All rights reserved. -# SPDX-License-Identifier: BSD-2-Clause-Patent -# -## - -[Defines] - INF_VERSION = 1.27 - BASE_NAME = MemoryOverrideLibNull - FILE_GUID = 368687CE-3189-4C26-A6EB-615B64CAA911 - MODULE_TYPE = DXE_CORE - VERSION_STRING = 1.0 - LIBRARY_CLASS = MemoryBinOverrideLib - -# -# The following information is for reference only and not required by the build tools. -# -# VALID_ARCHITECTURES = IA32 X64 AARCH64 -# - -[Sources] - MemoryBinOverrideLibNull.c - -[Packages] - MdePkg/MdePkg.dec - MdeModulePkg/MdeModulePkg.dec - -[LibraryClasses] - BaseLib +## @file +# NULL implementation of the memory bin override lib. +# +# Copyright (c) Microsoft Corporation. All rights reserved. +# SPDX-License-Identifier: BSD-2-Clause-Patent +# +## + +[Defines] + INF_VERSION = 1.27 + BASE_NAME = MemoryOverrideLibNull + FILE_GUID = 368687CE-3189-4C26-A6EB-615B64CAA911 + MODULE_TYPE = DXE_CORE + VERSION_STRING = 1.0 + LIBRARY_CLASS = MemoryBinOverrideLib + +# +# The following information is for reference only and not required by the build tools. +# +# VALID_ARCHITECTURES = IA32 X64 AARCH64 +# + +[Sources] + MemoryBinOverrideLibNull.c + +[Packages] + MdePkg/MdePkg.dec + MdeModulePkg/MdeModulePkg.dec + +[LibraryClasses] + BaseLib diff --git a/MdeModulePkg/Library/MemoryProtectionHobLib/DxeMemoryProtectionHobLib.inf b/MdeModulePkg/Library/MemoryProtectionHobLib/DxeMemoryProtectionHobLib.inf index 84a2fb3033..41cd928f2c 100644 --- a/MdeModulePkg/Library/MemoryProtectionHobLib/DxeMemoryProtectionHobLib.inf +++ b/MdeModulePkg/Library/MemoryProtectionHobLib/DxeMemoryProtectionHobLib.inf @@ -1,34 +1,34 @@ -## @file -# DXE library instance to support platform-specific global controls for all memory protections. -# -# Copyright (c) Microsoft Corporation. -# SPDX-License-Identifier: BSD-2-Clause-Patent -## - -[Defines] - INF_VERSION = 0x00010005 - BASE_NAME = DxeMemoryProtectionHobLib - FILE_GUID = f497f7de-b9ab-4b9f-807e-89778922542d - MODULE_TYPE = UEFI_DRIVER - VERSION_STRING = 1.0 - LIBRARY_CLASS = DxeMemoryProtectionHobLib|DXE_DRIVER DXE_CORE UEFI_APPLICATION - CONSTRUCTOR = DxeMemoryProtectionHobLibConstructor - -# -# VALID_ARCHITECTURES = IA32 X64 AARCH64 -# - -[Sources] - DxeMemoryProtectionHobLib.c - -[Packages] - MdePkg/MdePkg.dec - MdeModulePkg/MdeModulePkg.dec - -[LibraryClasses] - HobLib - DebugLib - BaseMemoryLib - -[Guids] +## @file +# DXE library instance to support platform-specific global controls for all memory protections. +# +# Copyright (c) Microsoft Corporation. +# SPDX-License-Identifier: BSD-2-Clause-Patent +## + +[Defines] + INF_VERSION = 0x00010005 + BASE_NAME = DxeMemoryProtectionHobLib + FILE_GUID = f497f7de-b9ab-4b9f-807e-89778922542d + MODULE_TYPE = UEFI_DRIVER + VERSION_STRING = 1.0 + LIBRARY_CLASS = DxeMemoryProtectionHobLib|DXE_DRIVER DXE_CORE UEFI_APPLICATION + CONSTRUCTOR = DxeMemoryProtectionHobLibConstructor + +# +# VALID_ARCHITECTURES = IA32 X64 AARCH64 +# + +[Sources] + DxeMemoryProtectionHobLib.c + +[Packages] + MdePkg/MdePkg.dec + MdeModulePkg/MdeModulePkg.dec + +[LibraryClasses] + HobLib + DebugLib + BaseMemoryLib + +[Guids] gDxeMemoryProtectionSettingsGuid \ No newline at end of file diff --git a/MdeModulePkg/Library/MemoryProtectionHobLib/SmmMemoryProtectionHobLib.inf b/MdeModulePkg/Library/MemoryProtectionHobLib/SmmMemoryProtectionHobLib.inf index 0dcf1e1e39..50631f8bdf 100644 --- a/MdeModulePkg/Library/MemoryProtectionHobLib/SmmMemoryProtectionHobLib.inf +++ b/MdeModulePkg/Library/MemoryProtectionHobLib/SmmMemoryProtectionHobLib.inf @@ -1,35 +1,35 @@ -## @file -# SMM library instance to support platform-specific global controls for all memory protections. -# -# Copyright (c) Microsoft Corporation. -# SPDX-License-Identifier: BSD-2-Clause-Patent -## - -[Defines] - INF_VERSION = 0x00010005 - BASE_NAME = SmmMemoryProtectionHobLib - FILE_GUID = dc9666f4-917f-400d-8026-2b3beeeff195 - MODULE_TYPE = DXE_SMM_DRIVER - VERSION_STRING = 1.0 - LIBRARY_CLASS = MmMemoryProtectionHobLib|SMM_CORE DXE_SMM_DRIVER - CONSTRUCTOR = SmmMemoryProtectionHobLibConstructor - -# -# VALID_ARCHITECTURES = IA32 X64 -# - -[Sources] - MmCommonMemoryProtectionHobLib.c - SmmMemoryProtectionHobLib.c - -[Packages] - MdePkg/MdePkg.dec - MdeModulePkg/MdeModulePkg.dec - -[LibraryClasses] - HobLib - DebugLib - BaseMemoryLib - -[Guids] +## @file +# SMM library instance to support platform-specific global controls for all memory protections. +# +# Copyright (c) Microsoft Corporation. +# SPDX-License-Identifier: BSD-2-Clause-Patent +## + +[Defines] + INF_VERSION = 0x00010005 + BASE_NAME = SmmMemoryProtectionHobLib + FILE_GUID = dc9666f4-917f-400d-8026-2b3beeeff195 + MODULE_TYPE = DXE_SMM_DRIVER + VERSION_STRING = 1.0 + LIBRARY_CLASS = MmMemoryProtectionHobLib|SMM_CORE DXE_SMM_DRIVER + CONSTRUCTOR = SmmMemoryProtectionHobLibConstructor + +# +# VALID_ARCHITECTURES = IA32 X64 +# + +[Sources] + MmCommonMemoryProtectionHobLib.c + SmmMemoryProtectionHobLib.c + +[Packages] + MdePkg/MdePkg.dec + MdeModulePkg/MdeModulePkg.dec + +[LibraryClasses] + HobLib + DebugLib + BaseMemoryLib + +[Guids] gMmMemoryProtectionSettingsGuid \ No newline at end of file diff --git a/MdeModulePkg/Library/MemoryProtectionHobLib/StandaloneMmMemoryProtectionHobLib.inf b/MdeModulePkg/Library/MemoryProtectionHobLib/StandaloneMmMemoryProtectionHobLib.inf index e293dfc55a..e8ae531795 100644 --- a/MdeModulePkg/Library/MemoryProtectionHobLib/StandaloneMmMemoryProtectionHobLib.inf +++ b/MdeModulePkg/Library/MemoryProtectionHobLib/StandaloneMmMemoryProtectionHobLib.inf @@ -1,36 +1,36 @@ -## @file -# SMM library instance to support platform-specific global controls for all memory protections. -# -# Copyright (c) Microsoft Corporation. -# SPDX-License-Identifier: BSD-2-Clause-Patent -## - -[Defines] - INF_VERSION = 0x00010005 - BASE_NAME = StandaloneMmMemoryProtectionHobLib - FILE_GUID = C0A0D9C4-A249-483A-86EA-D73146D397B3 - MODULE_TYPE = MM_CORE_STANDALONE - PI_SPECIFICATION_VERSION = 0x00010032 - VERSION_STRING = 1.0 - LIBRARY_CLASS = MmMemoryProtectionHobLib|MM_CORE_STANDALONE MM_STANDALONE - CONSTRUCTOR = StandaloneMmMemoryProtectionHobLibConstructor - -# -# VALID_ARCHITECTURES = IA32 X64 -# - -[Sources] - MmCommonMemoryProtectionHobLib.c - StandaloneMmMemoryProtectionHobLib.c - -[Packages] - MdePkg/MdePkg.dec - MdeModulePkg/MdeModulePkg.dec - -[LibraryClasses] - HobLib - DebugLib - BaseMemoryLib - -[Guids] +## @file +# SMM library instance to support platform-specific global controls for all memory protections. +# +# Copyright (c) Microsoft Corporation. +# SPDX-License-Identifier: BSD-2-Clause-Patent +## + +[Defines] + INF_VERSION = 0x00010005 + BASE_NAME = StandaloneMmMemoryProtectionHobLib + FILE_GUID = C0A0D9C4-A249-483A-86EA-D73146D397B3 + MODULE_TYPE = MM_CORE_STANDALONE + PI_SPECIFICATION_VERSION = 0x00010032 + VERSION_STRING = 1.0 + LIBRARY_CLASS = MmMemoryProtectionHobLib|MM_CORE_STANDALONE MM_STANDALONE + CONSTRUCTOR = StandaloneMmMemoryProtectionHobLibConstructor + +# +# VALID_ARCHITECTURES = IA32 X64 +# + +[Sources] + MmCommonMemoryProtectionHobLib.c + StandaloneMmMemoryProtectionHobLib.c + +[Packages] + MdePkg/MdePkg.dec + MdeModulePkg/MdeModulePkg.dec + +[LibraryClasses] + HobLib + DebugLib + BaseMemoryLib + +[Guids] gMmMemoryProtectionSettingsGuid \ No newline at end of file diff --git a/MdeModulePkg/Library/MemoryProtectionHobLibNull/DxeMemoryProtectionHobLibNull.inf b/MdeModulePkg/Library/MemoryProtectionHobLibNull/DxeMemoryProtectionHobLibNull.inf index 463e6a8c5d..6a3166a23b 100644 --- a/MdeModulePkg/Library/MemoryProtectionHobLibNull/DxeMemoryProtectionHobLibNull.inf +++ b/MdeModulePkg/Library/MemoryProtectionHobLibNull/DxeMemoryProtectionHobLibNull.inf @@ -1,25 +1,25 @@ -## @file -# NULL library which defines gDxeMps -# -# Copyright (c) Microsoft Corporation. -# SPDX-License-Identifier: BSD-2-Clause-Patent -## - -[Defines] - INF_VERSION = 0x00010005 - BASE_NAME = DxeMemoryProtectionHobLibNull - FILE_GUID = a35c1dc1-0769-421b-a8bc-9db69fae4334 - MODULE_TYPE = BASE - VERSION_STRING = 1.0 - LIBRARY_CLASS = DxeMemoryProtectionHobLib - -# -# VALID_ARCHITECTURES = IA32 X64 AARCH64 -# - -[Sources] - DxeMemoryProtectionHobLibNull.c - -[Packages] - MdePkg/MdePkg.dec - MdeModulePkg/MdeModulePkg.dec +## @file +# NULL library which defines gDxeMps +# +# Copyright (c) Microsoft Corporation. +# SPDX-License-Identifier: BSD-2-Clause-Patent +## + +[Defines] + INF_VERSION = 0x00010005 + BASE_NAME = DxeMemoryProtectionHobLibNull + FILE_GUID = a35c1dc1-0769-421b-a8bc-9db69fae4334 + MODULE_TYPE = BASE + VERSION_STRING = 1.0 + LIBRARY_CLASS = DxeMemoryProtectionHobLib + +# +# VALID_ARCHITECTURES = IA32 X64 AARCH64 +# + +[Sources] + DxeMemoryProtectionHobLibNull.c + +[Packages] + MdePkg/MdePkg.dec + MdeModulePkg/MdeModulePkg.dec diff --git a/MdeModulePkg/Library/MemoryProtectionHobLibNull/MmMemoryProtectionHobLibNull.inf b/MdeModulePkg/Library/MemoryProtectionHobLibNull/MmMemoryProtectionHobLibNull.inf index 19bc3d05e3..61f50921ee 100644 --- a/MdeModulePkg/Library/MemoryProtectionHobLibNull/MmMemoryProtectionHobLibNull.inf +++ b/MdeModulePkg/Library/MemoryProtectionHobLibNull/MmMemoryProtectionHobLibNull.inf @@ -1,26 +1,26 @@ -## @file -# NULL library which defines gMmMps -# -# Copyright (c) Microsoft Corporation. -# SPDX-License-Identifier: BSD-2-Clause-Patent -## - -[Defines] - INF_VERSION = 0x00010005 - BASE_NAME = MmMemoryProtectionHobLibNull - FILE_GUID = 4e3f6fd9-4ab5-4911-b80b-009d3338b4b2 - MODULE_TYPE = BASE - VERSION_STRING = 1.0 - LIBRARY_CLASS = MmMemoryProtectionHobLib - -# -# VALID_ARCHITECTURES = IA32 X64 AARCH64 -# - -[Sources] - MmMemoryProtectionHobLibNull.c - -[Packages] - MdePkg/MdePkg.dec - MdeModulePkg/MdeModulePkg.dec - +## @file +# NULL library which defines gMmMps +# +# Copyright (c) Microsoft Corporation. +# SPDX-License-Identifier: BSD-2-Clause-Patent +## + +[Defines] + INF_VERSION = 0x00010005 + BASE_NAME = MmMemoryProtectionHobLibNull + FILE_GUID = 4e3f6fd9-4ab5-4911-b80b-009d3338b4b2 + MODULE_TYPE = BASE + VERSION_STRING = 1.0 + LIBRARY_CLASS = MmMemoryProtectionHobLib + +# +# VALID_ARCHITECTURES = IA32 X64 AARCH64 +# + +[Sources] + MmMemoryProtectionHobLibNull.c + +[Packages] + MdePkg/MdePkg.dec + MdeModulePkg/MdeModulePkg.dec + diff --git a/MdeModulePkg/Library/MemoryTypeInfoSecVarCheckLib/MemoryTypeInfoSecVarCheckLib.inf b/MdeModulePkg/Library/MemoryTypeInfoSecVarCheckLib/MemoryTypeInfoSecVarCheckLib.inf index 89d97b858e..bb99ce7c18 100644 --- a/MdeModulePkg/Library/MemoryTypeInfoSecVarCheckLib/MemoryTypeInfoSecVarCheckLib.inf +++ b/MdeModulePkg/Library/MemoryTypeInfoSecVarCheckLib/MemoryTypeInfoSecVarCheckLib.inf @@ -1,45 +1,45 @@ -## @file -# NULL class library to register var check handler and variable property set for MemoryTypeInformation variable. -# -# Copyright (c) 2018, Intel Corporation. All rights reserved.
-# Copyright (C) Microsoft Corporation -# SPDX-License-Identifier: BSD-2-Clause-Patent -# -## - -# MU_CHANGE TCBZ1086 [WHOLE FILE] - Mitigate potential system brick due to uefi MemoryTypeInformation var changes - -[Defines] - INF_VERSION = 0x00010005 - BASE_NAME = MemoryTypeInfoSecVarCheckLib - FILE_GUID = C69D75E8-E39F-4F79-9D74-50B8C759D09B - MODULE_TYPE = BASE - VERSION_STRING = 1.0 - LIBRARY_CLASS = MemoryTypeInfoSecVarCheckLib|DXE_RUNTIME_DRIVER DXE_SMM_DRIVER MM_STANDALONE - CONSTRUCTOR = MemoryTypeInfoSecVarCheckLibConstructor - -# -# The following information is for reference only and not required by the build tools. -# -# VALID_ARCHITECTURES = IA32 X64 -# - -[Sources] - MemoryTypeInfoSecVarCheckLib.c - -[Packages] - MdePkg/MdePkg.dec - MdeModulePkg/MdeModulePkg.dec - -[LibraryClasses] - BaseLib - BaseMemoryLib - DebugLib - VarCheckLib - SafeIntLib - -[Guids] - gEfiMemoryTypeInformationGuid ## CONSUMES ## Variable:L"MemoryTypeInformation" - -[Pcd] - gEfiMdeModulePkgTokenSpaceGuid.PcdMaxMemoryTypeInfoPages ## CONSUMES +## @file +# NULL class library to register var check handler and variable property set for MemoryTypeInformation variable. +# +# Copyright (c) 2018, Intel Corporation. All rights reserved.
+# Copyright (C) Microsoft Corporation +# SPDX-License-Identifier: BSD-2-Clause-Patent +# +## + +# MU_CHANGE TCBZ1086 [WHOLE FILE] - Mitigate potential system brick due to uefi MemoryTypeInformation var changes + +[Defines] + INF_VERSION = 0x00010005 + BASE_NAME = MemoryTypeInfoSecVarCheckLib + FILE_GUID = C69D75E8-E39F-4F79-9D74-50B8C759D09B + MODULE_TYPE = BASE + VERSION_STRING = 1.0 + LIBRARY_CLASS = MemoryTypeInfoSecVarCheckLib|DXE_RUNTIME_DRIVER DXE_SMM_DRIVER MM_STANDALONE + CONSTRUCTOR = MemoryTypeInfoSecVarCheckLibConstructor + +# +# The following information is for reference only and not required by the build tools. +# +# VALID_ARCHITECTURES = IA32 X64 +# + +[Sources] + MemoryTypeInfoSecVarCheckLib.c + +[Packages] + MdePkg/MdePkg.dec + MdeModulePkg/MdeModulePkg.dec + +[LibraryClasses] + BaseLib + BaseMemoryLib + DebugLib + VarCheckLib + SafeIntLib + +[Guids] + gEfiMemoryTypeInformationGuid ## CONSUMES ## Variable:L"MemoryTypeInformation" + +[Pcd] + gEfiMdeModulePkgTokenSpaceGuid.PcdMaxMemoryTypeInfoPages ## CONSUMES diff --git a/MdeModulePkg/Library/MemoryTypeInformationChangeLibNull/MemoryTypeInformationChangeLibNull.inf b/MdeModulePkg/Library/MemoryTypeInformationChangeLibNull/MemoryTypeInformationChangeLibNull.inf index 188287afcb..c0abbfe17c 100644 --- a/MdeModulePkg/Library/MemoryTypeInformationChangeLibNull/MemoryTypeInformationChangeLibNull.inf +++ b/MdeModulePkg/Library/MemoryTypeInformationChangeLibNull/MemoryTypeInformationChangeLibNull.inf @@ -1,29 +1,29 @@ -## @file MemoryTypeInformationChangeLibNull.inf -# Null library, returns success. -## -# Copyright (c) Microsoft Corporation. All rights reserved. -# SPDX-License-Identifier: BSD-2-Clause-Patent -## - -# MU_CHANGE NEW FILE - -[Defines] - INF_VERSION = 0x00010017 - BASE_NAME = MemoryTypeInformationChangeLibNull - FILE_GUID = eb4cc801-4301-43ba-979a-d4153c55f43c - VERSION_STRING = 1.0 - MODULE_TYPE = BASE - LIBRARY_CLASS = MemoryTypeInformationChangeLib - - -[Sources] - MemoryTypeInformationChangeLibNull.c - - -[Packages] - MdePkg/MdePkg.dec - MdeModulePkg/MdeModulePkg.dec - - -[LibraryClasses] - BaseLib +## @file MemoryTypeInformationChangeLibNull.inf +# Null library, returns success. +## +# Copyright (c) Microsoft Corporation. All rights reserved. +# SPDX-License-Identifier: BSD-2-Clause-Patent +## + +# MU_CHANGE NEW FILE + +[Defines] + INF_VERSION = 0x00010017 + BASE_NAME = MemoryTypeInformationChangeLibNull + FILE_GUID = eb4cc801-4301-43ba-979a-d4153c55f43c + VERSION_STRING = 1.0 + MODULE_TYPE = BASE + LIBRARY_CLASS = MemoryTypeInformationChangeLib + + +[Sources] + MemoryTypeInformationChangeLibNull.c + + +[Packages] + MdePkg/MdePkg.dec + MdeModulePkg/MdeModulePkg.dec + + +[LibraryClasses] + BaseLib diff --git a/MdeModulePkg/Library/ParallelLzmaCustomDecompressLib/ParallelLzmaCustomDecompressLib.inf b/MdeModulePkg/Library/ParallelLzmaCustomDecompressLib/ParallelLzmaCustomDecompressLib.inf index 12da826360..6ff2bc5bf0 100644 --- a/MdeModulePkg/Library/ParallelLzmaCustomDecompressLib/ParallelLzmaCustomDecompressLib.inf +++ b/MdeModulePkg/Library/ParallelLzmaCustomDecompressLib/ParallelLzmaCustomDecompressLib.inf @@ -1,40 +1,40 @@ -## @file -# ParallelLzmaCustomDecompressLib produces the Parallel LZMA custom decompression algorithm. -# -# This relies on the standard LzmaCustomDecompress lib to do the work and expects to be -# linked against it with a NULL| library instance. -# -## - -[Defines] - INF_VERSION = 1.27 - BASE_NAME = ParallelLzmaDecompressLib - FILE_GUID = 16979EFB-EC84-4390-BC4E-923B69B02CDA - MODULE_TYPE = BASE - VERSION_STRING = 1.0 - LIBRARY_CLASS = NULL - CONSTRUCTOR = ParallelLzmaDecompressLibConstructor - -# -# The following information is for reference only and not required by the build tools. -# -# VALID_ARCHITECTURES = IA32 X64 AARCH64 ARM -# - -[Sources] - ParallelLzmaDecompress.c - -[Packages] - MdePkg/MdePkg.dec - MdeModulePkg/MdeModulePkg.dec - -[Guids] - gParallelLzmaCustomDecompressGuid ## PRODUCES # specifies LZMA custom decompress algorithm. - gParallelLzmaCustomDecompressHobGuid ## CONSUMES - -[LibraryClasses] - BaseLib - BaseMemoryLib - DebugLib - ExtractGuidedSectionLib - HobLib +## @file +# ParallelLzmaCustomDecompressLib produces the Parallel LZMA custom decompression algorithm. +# +# This relies on the standard LzmaCustomDecompress lib to do the work and expects to be +# linked against it with a NULL| library instance. +# +## + +[Defines] + INF_VERSION = 1.27 + BASE_NAME = ParallelLzmaDecompressLib + FILE_GUID = 16979EFB-EC84-4390-BC4E-923B69B02CDA + MODULE_TYPE = BASE + VERSION_STRING = 1.0 + LIBRARY_CLASS = NULL + CONSTRUCTOR = ParallelLzmaDecompressLibConstructor + +# +# The following information is for reference only and not required by the build tools. +# +# VALID_ARCHITECTURES = IA32 X64 AARCH64 ARM +# + +[Sources] + ParallelLzmaDecompress.c + +[Packages] + MdePkg/MdePkg.dec + MdeModulePkg/MdeModulePkg.dec + +[Guids] + gParallelLzmaCustomDecompressGuid ## PRODUCES # specifies LZMA custom decompress algorithm. + gParallelLzmaCustomDecompressHobGuid ## CONSUMES + +[LibraryClasses] + BaseLib + BaseMemoryLib + DebugLib + ExtractGuidedSectionLib + HobLib diff --git a/MdeModulePkg/Library/SecurityLockAuditDebugMessageLib/SecurityLockAuditDebugMessageLib.inf b/MdeModulePkg/Library/SecurityLockAuditDebugMessageLib/SecurityLockAuditDebugMessageLib.inf index fdf71dea9d..27b29e0aa6 100644 --- a/MdeModulePkg/Library/SecurityLockAuditDebugMessageLib/SecurityLockAuditDebugMessageLib.inf +++ b/MdeModulePkg/Library/SecurityLockAuditDebugMessageLib/SecurityLockAuditDebugMessageLib.inf @@ -1,28 +1,28 @@ -## -# -# Library that implements logging and reporting for security locks -# Using DebugLib -# -# -# Copyright (c) Microsoft Corporation. All rights reserved. -# SPDX-License-Identifier: BSD-2-Clause-Patent -## - -[Defines] - INF_VERSION = 0x00010005 - BASE_NAME = SecurityLockAuditDebugMessageLib - FILE_GUID = 459d0456-d6be-458e-9cc8-e9b21745f9aa - MODULE_TYPE = BASE - VERSION_STRING = 1.0 - LIBRARY_CLASS = SecurityLockAuditLib - -[Sources.common] - SecurityLockAuditDebugMessageLib.c - -[Packages] - MdePkg/MdePkg.dec - MdeModulePkg/MdeModulePkg.dec - -[LibraryClasses] - BaseLib - DebugLib +## +# +# Library that implements logging and reporting for security locks +# Using DebugLib +# +# +# Copyright (c) Microsoft Corporation. All rights reserved. +# SPDX-License-Identifier: BSD-2-Clause-Patent +## + +[Defines] + INF_VERSION = 0x00010005 + BASE_NAME = SecurityLockAuditDebugMessageLib + FILE_GUID = 459d0456-d6be-458e-9cc8-e9b21745f9aa + MODULE_TYPE = BASE + VERSION_STRING = 1.0 + LIBRARY_CLASS = SecurityLockAuditLib + +[Sources.common] + SecurityLockAuditDebugMessageLib.c + +[Packages] + MdePkg/MdePkg.dec + MdeModulePkg/MdeModulePkg.dec + +[LibraryClasses] + BaseLib + DebugLib diff --git a/MdeModulePkg/Library/SecurityLockAuditLibNull/SecurityLockAuditLibNull.inf b/MdeModulePkg/Library/SecurityLockAuditLibNull/SecurityLockAuditLibNull.inf index cc07c7db4b..b8e691b096 100644 --- a/MdeModulePkg/Library/SecurityLockAuditLibNull/SecurityLockAuditLibNull.inf +++ b/MdeModulePkg/Library/SecurityLockAuditLibNull/SecurityLockAuditLibNull.inf @@ -1,26 +1,26 @@ -## -# -# Null library for security lock logging that does nothing but meet compile requirements -# -# -# Copyright (c) Microsoft Corporation. All rights reserved. -# SPDX-License-Identifier: BSD-2-Clause-Patent -## - -[Defines] - INF_VERSION = 0x00010005 - BASE_NAME = SecurityLockAuditLibNull - FILE_GUID = 1d333a6a-90a7-45cb-9897-0a172ee35066 - MODULE_TYPE = BASE - VERSION_STRING = 1.0 - LIBRARY_CLASS = SecurityLockAuditLib - -[Sources.common] - SecurityLockAuditLibNull.c - -[Packages] - MdePkg/MdePkg.dec - MdeModulePkg/MdeModulePkg.dec - -[LibraryClasses] +## +# +# Null library for security lock logging that does nothing but meet compile requirements +# +# +# Copyright (c) Microsoft Corporation. All rights reserved. +# SPDX-License-Identifier: BSD-2-Clause-Patent +## + +[Defines] + INF_VERSION = 0x00010005 + BASE_NAME = SecurityLockAuditLibNull + FILE_GUID = 1d333a6a-90a7-45cb-9897-0a172ee35066 + MODULE_TYPE = BASE + VERSION_STRING = 1.0 + LIBRARY_CLASS = SecurityLockAuditLib + +[Sources.common] + SecurityLockAuditLibNull.c + +[Packages] + MdePkg/MdePkg.dec + MdeModulePkg/MdeModulePkg.dec + +[LibraryClasses] BaseLib \ No newline at end of file diff --git a/MdeModulePkg/Library/VarCheckPolicyLib/VarCheckPolicyLibVariableDxe.inf b/MdeModulePkg/Library/VarCheckPolicyLib/VarCheckPolicyLibVariableDxe.inf index 828273e112..e5e315ff0d 100644 --- a/MdeModulePkg/Library/VarCheckPolicyLib/VarCheckPolicyLibVariableDxe.inf +++ b/MdeModulePkg/Library/VarCheckPolicyLib/VarCheckPolicyLibVariableDxe.inf @@ -1,31 +1,31 @@ -## @file VarCheckPolicyLib.inf -# This is an instance of a VarCheck lib that leverages the business logic behind -# the VariablePolicy code to make its decisions. -# -# Copyright (c) Microsoft Corporation. -# SPDX-License-Identifier: BSD-2-Clause-Patent -## - -[Defines] - INF_VERSION = 0x00010005 - BASE_NAME = VarCheckPolicyLibVariableDxe - FILE_GUID = C17DF9DB-A744-4011-A796-4EDA2ED97C2F - MODULE_TYPE = DXE_RUNTIME_DRIVER - VERSION_STRING = 1.0 - LIBRARY_CLASS = NULL|DXE_RUNTIME_DRIVER - CONSTRUCTOR = VarCheckPolicyLibConstructor - - -[Sources] - VarCheckPolicyLibVariableDxe.c - - -[Packages] - MdePkg/MdePkg.dec - MdeModulePkg/MdeModulePkg.dec - - -[LibraryClasses] - DebugLib - VarCheckLib - VariablePolicyLib +## @file VarCheckPolicyLib.inf +# This is an instance of a VarCheck lib that leverages the business logic behind +# the VariablePolicy code to make its decisions. +# +# Copyright (c) Microsoft Corporation. +# SPDX-License-Identifier: BSD-2-Clause-Patent +## + +[Defines] + INF_VERSION = 0x00010005 + BASE_NAME = VarCheckPolicyLibVariableDxe + FILE_GUID = C17DF9DB-A744-4011-A796-4EDA2ED97C2F + MODULE_TYPE = DXE_RUNTIME_DRIVER + VERSION_STRING = 1.0 + LIBRARY_CLASS = NULL|DXE_RUNTIME_DRIVER + CONSTRUCTOR = VarCheckPolicyLibConstructor + + +[Sources] + VarCheckPolicyLibVariableDxe.c + + +[Packages] + MdePkg/MdePkg.dec + MdeModulePkg/MdeModulePkg.dec + + +[LibraryClasses] + DebugLib + VarCheckLib + VariablePolicyLib diff --git a/MdeModulePkg/Library/VariablePolicyLib/VariablePolicyUnitTest/VariablePolicyUnitTest.inf b/MdeModulePkg/Library/VariablePolicyLib/VariablePolicyUnitTest/VariablePolicyUnitTest.inf index 10b1256abb..06489f21d6 100644 --- a/MdeModulePkg/Library/VariablePolicyLib/VariablePolicyUnitTest/VariablePolicyUnitTest.inf +++ b/MdeModulePkg/Library/VariablePolicyLib/VariablePolicyUnitTest/VariablePolicyUnitTest.inf @@ -1,45 +1,45 @@ -## @file VariablePolicyUnitTest.inf -# UnitTest for... -# Business logic for Variable Policy enforcement. -# -# Copyright (c) Microsoft Corporation. -# SPDX-License-Identifier: BSD-2-Clause-Patent -## - - -[Defines] - INF_VERSION = 0x00010006 - BASE_NAME = VariablePolicyUnitTest - FILE_GUID = 1200A2E4-D756-418C-9768-528C2D181A98 - MODULE_TYPE = HOST_APPLICATION - VERSION_STRING = 1.0 - -# -# The following information is for reference only and not required by the build tools. -# -# VALID_ARCHITECTURES = IA32 X64 ARM AARCH64 -# - -[Sources] - VariablePolicyUnitTest.c - - -[Packages] - MdePkg/MdePkg.dec - MdeModulePkg/MdeModulePkg.dec - UnitTestFrameworkPkg/UnitTestFrameworkPkg.dec - - -[LibraryClasses] - BaseLib - DebugLib - UnitTestLib - PrintLib - VariablePolicyLib - BaseMemoryLib - MemoryAllocationLib - - -[BuildOptions] - MSFT:NOOPT_*_*_CC_FLAGS = -DINTERNAL_UNIT_TEST - GCC:NOOPT_*_*_CC_FLAGS = -DINTERNAL_UNIT_TEST +## @file VariablePolicyUnitTest.inf +# UnitTest for... +# Business logic for Variable Policy enforcement. +# +# Copyright (c) Microsoft Corporation. +# SPDX-License-Identifier: BSD-2-Clause-Patent +## + + +[Defines] + INF_VERSION = 0x00010006 + BASE_NAME = VariablePolicyUnitTest + FILE_GUID = 1200A2E4-D756-418C-9768-528C2D181A98 + MODULE_TYPE = HOST_APPLICATION + VERSION_STRING = 1.0 + +# +# The following information is for reference only and not required by the build tools. +# +# VALID_ARCHITECTURES = IA32 X64 ARM AARCH64 +# + +[Sources] + VariablePolicyUnitTest.c + + +[Packages] + MdePkg/MdePkg.dec + MdeModulePkg/MdeModulePkg.dec + UnitTestFrameworkPkg/UnitTestFrameworkPkg.dec + + +[LibraryClasses] + BaseLib + DebugLib + UnitTestLib + PrintLib + VariablePolicyLib + BaseMemoryLib + MemoryAllocationLib + + +[BuildOptions] + MSFT:NOOPT_*_*_CC_FLAGS = -DINTERNAL_UNIT_TEST + GCC:NOOPT_*_*_CC_FLAGS = -DINTERNAL_UNIT_TEST diff --git a/MdeModulePkg/Test/MdeModulePkgHostTest.dsc b/MdeModulePkg/Test/MdeModulePkgHostTest.dsc index 9cbc62b37c..7e2e08aa54 100644 --- a/MdeModulePkg/Test/MdeModulePkgHostTest.dsc +++ b/MdeModulePkg/Test/MdeModulePkgHostTest.dsc @@ -126,13 +126,13 @@ } # MU_CHANGE [END] - MdeModulePkg/Library/UefiSortLib/GoogleTest/UefiSortLibGoogleTest.inf { - - UefiSortLib|MdeModulePkg/Library/UefiSortLib/UefiSortLib.inf - DevicePathLib|MdePkg/Library/UefiDevicePathLib/UefiDevicePathLib.inf - } - - # - # Build HOST_APPLICATION Libraries - # - MdeModulePkg/Test/Mock/Library/GoogleTest/MockPciHostBridgeLib/MockPciHostBridgeLib.inf + MdeModulePkg/Library/UefiSortLib/GoogleTest/UefiSortLibGoogleTest.inf { + + UefiSortLib|MdeModulePkg/Library/UefiSortLib/UefiSortLib.inf + DevicePathLib|MdePkg/Library/UefiDevicePathLib/UefiDevicePathLib.inf + } + + # + # Build HOST_APPLICATION Libraries + # + MdeModulePkg/Test/Mock/Library/GoogleTest/MockPciHostBridgeLib/MockPciHostBridgeLib.inf diff --git a/MdeModulePkg/Test/ShellTest/VariablePolicyFuncTestApp/Readme.md b/MdeModulePkg/Test/ShellTest/VariablePolicyFuncTestApp/Readme.md index b13e7d131d..6b5096f0b8 100644 --- a/MdeModulePkg/Test/ShellTest/VariablePolicyFuncTestApp/Readme.md +++ b/MdeModulePkg/Test/ShellTest/VariablePolicyFuncTestApp/Readme.md @@ -1,67 +1,67 @@ -# Variable Policy Unit Tests - -## 🔹 Copyright - -Copyright (C) Microsoft Corporation. All rights reserved. -SPDX-License-Identifier: BSD-2-Clause-Patent - -## About This Test - -This test verifies functionality of the Variable Policy Protocol by registering various variable policies and exercising -them, as well as tests locking the policy, disabling it, and dumping the policy entries. - -Only policies that are created as a part of this test will be tested. - -1. Try getting test context, if empty then get VP protocol, confirm that VP is not disabled by calling IsVariablePolicyEnabled. - Log VP revision. -2. "No lock" policies: - * check minsize enforcement - * check maxsize enforcement - * check musthave attr enforcement - * check canthave attr enforcement - * check one of the above with empty string policy i.e. name wildcard - * check another one of the above with a "#" containing policy string - * check policy prioritization by having a namespace-wide policy, a policy with a # wildcard, - and a one-var specific policy and testing which one is enforced -3. "Lock now" policies (means if the var doesn't exist, it won't be created; if one exists, it - can't be updated): - * test a policy for an already existing variable, verify we can't write into that variable - * create a policy for a non-existing variable and attempt to register such var -4. "Lock on create" policies (means the var can still be created, but no updates later, existing - vars can't be updated): - * create a var, lock it with LockOnCreate, attempt to update its contents - * create LockOnCreate VP, attempt to create var with invalid size, then invalid attr, then create - valid var, attempt to update its contents -5. "Lock on var state" policies (means the var protected by this policy can't be created or updated - once the trigger is set) - * create VP, trigger lock with a valid var, attempt to create a locked var, then modify the - trigger var, create locked var - * create VP, create targeted var, modify it, trigger lock, attempt to modify var - * create VP, trigger lock with invalid (larger than one byte) var, see if VPE allows creation - of the locked var (it should allow) - * create VP, set locking var with wrong value, see if VPE allows creation of the locked var (should allow) -6. Attempt registering invalid policy entries - * invalid required and banned attributes - * large min size - let's say 2GB - * max size equal to 0 - * invalid policy type -7. Exercise dumping policy. No need to check the validity of the dump blob. -8. Test registering a policy with a random version. -9. Lock VPE, make sure old policies are enforced, new ones can't be registered. - * Register a LockOnCreate policy - * Lock VPE - * Test locking it again. - * Verify one of the prior policies is enforced - * Make sure we can create variables even if those are protected by LockOnCreate policy, after locking the VPE - * Attempt to register new policies - * Make sure can't disable VPE - * Cleanup: save context and reboot -10. Disable variable policy and try some things - * Locate Variable Policy Protocol - * Make sure VP is enabled - * Register a policy - * Disable VPE - * Call IsVariablePolicyEnabled to confirm it's disabled. - * Make sure can't lock policy - * Make sure the policy from a is no longer enforced - * Final cleanup: delete vars that were created in some earlier test suites +# Variable Policy Unit Tests + +## 🔹 Copyright + +Copyright (C) Microsoft Corporation. All rights reserved. +SPDX-License-Identifier: BSD-2-Clause-Patent + +## About This Test + +This test verifies functionality of the Variable Policy Protocol by registering various variable policies and exercising +them, as well as tests locking the policy, disabling it, and dumping the policy entries. + +Only policies that are created as a part of this test will be tested. + +1. Try getting test context, if empty then get VP protocol, confirm that VP is not disabled by calling IsVariablePolicyEnabled. + Log VP revision. +2. "No lock" policies: + * check minsize enforcement + * check maxsize enforcement + * check musthave attr enforcement + * check canthave attr enforcement + * check one of the above with empty string policy i.e. name wildcard + * check another one of the above with a "#" containing policy string + * check policy prioritization by having a namespace-wide policy, a policy with a # wildcard, + and a one-var specific policy and testing which one is enforced +3. "Lock now" policies (means if the var doesn't exist, it won't be created; if one exists, it + can't be updated): + * test a policy for an already existing variable, verify we can't write into that variable + * create a policy for a non-existing variable and attempt to register such var +4. "Lock on create" policies (means the var can still be created, but no updates later, existing + vars can't be updated): + * create a var, lock it with LockOnCreate, attempt to update its contents + * create LockOnCreate VP, attempt to create var with invalid size, then invalid attr, then create + valid var, attempt to update its contents +5. "Lock on var state" policies (means the var protected by this policy can't be created or updated + once the trigger is set) + * create VP, trigger lock with a valid var, attempt to create a locked var, then modify the + trigger var, create locked var + * create VP, create targeted var, modify it, trigger lock, attempt to modify var + * create VP, trigger lock with invalid (larger than one byte) var, see if VPE allows creation + of the locked var (it should allow) + * create VP, set locking var with wrong value, see if VPE allows creation of the locked var (should allow) +6. Attempt registering invalid policy entries + * invalid required and banned attributes + * large min size - let's say 2GB + * max size equal to 0 + * invalid policy type +7. Exercise dumping policy. No need to check the validity of the dump blob. +8. Test registering a policy with a random version. +9. Lock VPE, make sure old policies are enforced, new ones can't be registered. + * Register a LockOnCreate policy + * Lock VPE + * Test locking it again. + * Verify one of the prior policies is enforced + * Make sure we can create variables even if those are protected by LockOnCreate policy, after locking the VPE + * Attempt to register new policies + * Make sure can't disable VPE + * Cleanup: save context and reboot +10. Disable variable policy and try some things + * Locate Variable Policy Protocol + * Make sure VP is enabled + * Register a policy + * Disable VPE + * Call IsVariablePolicyEnabled to confirm it's disabled. + * Make sure can't lock policy + * Make sure the policy from a is no longer enforced + * Final cleanup: delete vars that were created in some earlier test suites diff --git a/MdeModulePkg/Test/ShellTest/VariablePolicyFuncTestApp/VariablePolicyFuncTestApp.inf b/MdeModulePkg/Test/ShellTest/VariablePolicyFuncTestApp/VariablePolicyFuncTestApp.inf index 85edafdf42..7f605a2b99 100644 --- a/MdeModulePkg/Test/ShellTest/VariablePolicyFuncTestApp/VariablePolicyFuncTestApp.inf +++ b/MdeModulePkg/Test/ShellTest/VariablePolicyFuncTestApp/VariablePolicyFuncTestApp.inf @@ -1,48 +1,48 @@ -## @file -# Uefi Shell based Application that unit tests the Variable Policy Protocol -# -# Copyright (c) Microsoft Corporation. -# SPDX-License-Identifier: BSD-2-Clause-Patent -## - -[Defines] - INF_VERSION = 0x00010005 - BASE_NAME = VariablePolicyFuncTestApp - FILE_GUID = B653C4C3-3FCC-4B6C-8051-5F692AEAECBA - MODULE_TYPE = UEFI_APPLICATION - VERSION_STRING = 1.0 - ENTRY_POINT = UefiMain - -# -# The following information is for reference only and not required by the build tools. -# -# VALID_ARCHITECTURES = X64 AARCH64 -# - -[Sources] - VariablePolicyFuncTestApp.c - VariablePolicyFuncTestAppData.c - VariablePolicyFuncTestInternal.h - -[Packages] - MdePkg/MdePkg.dec - MdeModulePkg/MdeModulePkg.dec - UnitTestFrameworkPkg/UnitTestFrameworkPkg.dec - -[LibraryClasses] - UefiApplicationEntryPoint - BaseLib - BaseMemoryLib - UnitTestLib - UnitTestBootLib - PrintLib - UefiBootServicesTableLib - UefiRuntimeServicesTableLib - MemoryAllocationLib - VariablePolicyHelperLib - -[Guids] - gEfiCertPkcs7Guid - -[Protocols] - gEdkiiVariablePolicyProtocolGuid +## @file +# Uefi Shell based Application that unit tests the Variable Policy Protocol +# +# Copyright (c) Microsoft Corporation. +# SPDX-License-Identifier: BSD-2-Clause-Patent +## + +[Defines] + INF_VERSION = 0x00010005 + BASE_NAME = VariablePolicyFuncTestApp + FILE_GUID = B653C4C3-3FCC-4B6C-8051-5F692AEAECBA + MODULE_TYPE = UEFI_APPLICATION + VERSION_STRING = 1.0 + ENTRY_POINT = UefiMain + +# +# The following information is for reference only and not required by the build tools. +# +# VALID_ARCHITECTURES = X64 AARCH64 +# + +[Sources] + VariablePolicyFuncTestApp.c + VariablePolicyFuncTestAppData.c + VariablePolicyFuncTestInternal.h + +[Packages] + MdePkg/MdePkg.dec + MdeModulePkg/MdeModulePkg.dec + UnitTestFrameworkPkg/UnitTestFrameworkPkg.dec + +[LibraryClasses] + UefiApplicationEntryPoint + BaseLib + BaseMemoryLib + UnitTestLib + UnitTestBootLib + PrintLib + UefiBootServicesTableLib + UefiRuntimeServicesTableLib + MemoryAllocationLib + VariablePolicyHelperLib + +[Guids] + gEfiCertPkcs7Guid + +[Protocols] + gEdkiiVariablePolicyProtocolGuid diff --git a/MdeModulePkg/Universal/Variable/RuntimeDxe/RuntimeDxeUnitTest/VariableRuntimeDxeUnitTest.inf b/MdeModulePkg/Universal/Variable/RuntimeDxe/RuntimeDxeUnitTest/VariableRuntimeDxeUnitTest.inf index eef404240c..e711eb5d07 100644 --- a/MdeModulePkg/Universal/Variable/RuntimeDxe/RuntimeDxeUnitTest/VariableRuntimeDxeUnitTest.inf +++ b/MdeModulePkg/Universal/Variable/RuntimeDxe/RuntimeDxeUnitTest/VariableRuntimeDxeUnitTest.inf @@ -1,157 +1,157 @@ -## @file VariableRuntimeDxeUnitTest.inf -# Host-based unit test for the VariableRuntimeDxe driver. Will -# use mocks for all external interfaces. -# -# Copyright (c) Microsoft Corporation. -# SPDX-License-Identifier: BSD-2-Clause-Patent -## - - -[Defines] - INF_VERSION = 0x00010017 - BASE_NAME = VariableRuntimeDxeUnitTest - FILE_GUID = E85B8F09-1BA3-4C36-B871-61D40F1C466F - VERSION_STRING = 1.0 - MODULE_TYPE = HOST_APPLICATION - -# -# The following information is for reference only and not required by the build tools. -# -# VALID_ARCHITECTURES = IA32 X64 -# - - -[Sources] - # Test Harness - SctShim.c - SctShim.h - TestData.c - VariableRuntimeDxeUnitTest.c - VariableRuntimeDxeUnitTest.h - VariableTestDataHelpers.c - BlackBoxTest/Guid.c - BlackBoxTest/Guid.h - BlackBoxTest/VariableServicesBBTestConformance.c - BlackBoxTest/VariableServicesBBTestFunction.c - BlackBoxTest/VariableServicesBBTestMain.h - BlackBoxTest/VariableServicesBBTestStress.c - SctInclude/StandardTestLibrary.h - SctInclude/TestLoggingLibrary.h - - # Files Under Test - ../Measurement.c - ../PrivilegePolymorphic.h - ../Reclaim.c - ../SpeculationBarrierDxe.c - ../TcgMorLockDxe.c - ../Variable.c - ../Variable.h - ../VariableExLib.c - ../VariableNonVolatile.c - ../VariableNonVolatile.h - ../VariableParsing.c - ../VariableParsing.h - ../VariableRuntimeCache.c - ../VariableRuntimeCache.h - - -[Packages] - MdePkg/MdePkg.dec - MdeModulePkg/MdeModulePkg.dec - - -[LibraryClasses] - UnitTestLib - MemoryAllocationLib - BaseLib - SynchronizationLib - UefiLib - UefiBootServicesTableLib - BaseMemoryLib - DebugLib - UefiRuntimeLib - DxeServicesTableLib - PcdLib - TpmMeasurementLib - AuthVariableLib - VarCheckLib - VariablePolicyLib - VariablePolicyHelperLib - VariableFlashInfoLib - PrintLib - - -[Protocols] - gEdkiiVariablePolicyProtocolGuid ## CONSUMES - - -[Guids] - gVariableFlashInfoHobGuid - gEfiHardwareErrorVariableGuid - - ## SOMETIMES_CONSUMES ## GUID # Signature of Variable store header - ## SOMETIMES_PRODUCES ## GUID # Signature of Variable store header - ## SOMETIMES_CONSUMES ## HOB - ## SOMETIMES_PRODUCES ## SystemTable - gEfiAuthenticatedVariableGuid - - ## SOMETIMES_CONSUMES ## GUID # Signature of Variable store header - ## SOMETIMES_PRODUCES ## GUID # Signature of Variable store header - ## SOMETIMES_CONSUMES ## HOB - ## SOMETIMES_PRODUCES ## SystemTable - gEfiVariableGuid - - ## SOMETIMES_CONSUMES ## Variable:L"PlatformLang" - ## SOMETIMES_PRODUCES ## Variable:L"PlatformLang" - ## SOMETIMES_CONSUMES ## Variable:L"Lang" - ## SOMETIMES_PRODUCES ## Variable:L"Lang" - ## SOMETIMES_CONSUMES ## Variable:L"PK" - ## SOMETIMES_CONSUMES ## Variable:L"KEK" - ## SOMETIMES_CONSUMES ## Variable:L"SecureBoot" - gEfiGlobalVariableGuid - - gEfiMemoryOverwriteControlDataGuid ## SOMETIMES_CONSUMES ## Variable:L"MemoryOverwriteRequestControl" - gEfiMemoryOverwriteRequestControlLockGuid ## SOMETIMES_PRODUCES ## Variable:L"MemoryOverwriteRequestControlLock" - - gEfiEventVirtualAddressChangeGuid ## CONSUMES ## Event - gEfiSystemNvDataFvGuid ## CONSUMES ## GUID - gEfiEndOfDxeEventGroupGuid ## CONSUMES ## Event - gEdkiiFaultTolerantWriteGuid ## SOMETIMES_CONSUMES ## HOB - - ## SOMETIMES_CONSUMES ## Variable:L"VarErrorFlag" - ## SOMETIMES_PRODUCES ## Variable:L"VarErrorFlag" - gEdkiiVarErrorFlagGuid - - ## SOMETIMES_CONSUMES ## Variable:L"db" - ## SOMETIMES_CONSUMES ## Variable:L"dbx" - ## SOMETIMES_CONSUMES ## Variable:L"dbt" - gEfiImageSecurityDatabaseGuid - - -[Pcd] - gEfiMdeModulePkgTokenSpaceGuid.PcdFlashNvStorageVariableSize ## CONSUMES - gEfiMdeModulePkgTokenSpaceGuid.PcdFlashNvStorageVariableBase ## SOMETIMES_CONSUMES - gEfiMdeModulePkgTokenSpaceGuid.PcdFlashNvStorageVariableBase64 ## CONSUMES - gEfiMdeModulePkgTokenSpaceGuid.PcdMaxVariableSize ## CONSUMES - gEfiMdeModulePkgTokenSpaceGuid.PcdMaxAuthVariableSize ## CONSUMES - gEfiMdeModulePkgTokenSpaceGuid.PcdMaxVolatileVariableSize ## CONSUMES - gEfiMdeModulePkgTokenSpaceGuid.PcdMaxHardwareErrorVariableSize ## CONSUMES - gEfiMdeModulePkgTokenSpaceGuid.PcdVariableStoreSize ## CONSUMES - gEfiMdeModulePkgTokenSpaceGuid.PcdHwErrStorageSize ## CONSUMES - gEfiMdeModulePkgTokenSpaceGuid.PcdMaxUserNvVariableSpaceSize ## CONSUMES - gEfiMdeModulePkgTokenSpaceGuid.PcdBoottimeReservedNvVariableSpaceSize ## CONSUMES - gEfiMdeModulePkgTokenSpaceGuid.PcdReclaimVariableSpaceAtEndOfDxe ## CONSUMES - gEfiMdeModulePkgTokenSpaceGuid.PcdEmuVariableNvModeEnable ## SOMETIMES_CONSUMES - gEfiMdeModulePkgTokenSpaceGuid.PcdEmuVariableNvStoreReserved ## SOMETIMES_CONSUMES - - -[FeaturePcd] - gEfiMdeModulePkgTokenSpaceGuid.PcdVariableCollectStatistics ## CONSUMES # statistic the information of variable. - gEfiMdePkgTokenSpaceGuid.PcdUefiVariableDefaultLangDeprecate ## CONSUMES # Auto update PlatformLang/Lang - - - -[BuildOptions] - # NOTE: For some reason the MSABI VA_ARGS funcs are causing a SegFault in Linux - GCC:NOOPT_*_*_CC_FLAGS = -include Uefi.h -DNO_MSABI_VA_FUNCS - MSFT:NOOPT_*_*_CC_FLAGS = /FIUefi.h +## @file VariableRuntimeDxeUnitTest.inf +# Host-based unit test for the VariableRuntimeDxe driver. Will +# use mocks for all external interfaces. +# +# Copyright (c) Microsoft Corporation. +# SPDX-License-Identifier: BSD-2-Clause-Patent +## + + +[Defines] + INF_VERSION = 0x00010017 + BASE_NAME = VariableRuntimeDxeUnitTest + FILE_GUID = E85B8F09-1BA3-4C36-B871-61D40F1C466F + VERSION_STRING = 1.0 + MODULE_TYPE = HOST_APPLICATION + +# +# The following information is for reference only and not required by the build tools. +# +# VALID_ARCHITECTURES = IA32 X64 +# + + +[Sources] + # Test Harness + SctShim.c + SctShim.h + TestData.c + VariableRuntimeDxeUnitTest.c + VariableRuntimeDxeUnitTest.h + VariableTestDataHelpers.c + BlackBoxTest/Guid.c + BlackBoxTest/Guid.h + BlackBoxTest/VariableServicesBBTestConformance.c + BlackBoxTest/VariableServicesBBTestFunction.c + BlackBoxTest/VariableServicesBBTestMain.h + BlackBoxTest/VariableServicesBBTestStress.c + SctInclude/StandardTestLibrary.h + SctInclude/TestLoggingLibrary.h + + # Files Under Test + ../Measurement.c + ../PrivilegePolymorphic.h + ../Reclaim.c + ../SpeculationBarrierDxe.c + ../TcgMorLockDxe.c + ../Variable.c + ../Variable.h + ../VariableExLib.c + ../VariableNonVolatile.c + ../VariableNonVolatile.h + ../VariableParsing.c + ../VariableParsing.h + ../VariableRuntimeCache.c + ../VariableRuntimeCache.h + + +[Packages] + MdePkg/MdePkg.dec + MdeModulePkg/MdeModulePkg.dec + + +[LibraryClasses] + UnitTestLib + MemoryAllocationLib + BaseLib + SynchronizationLib + UefiLib + UefiBootServicesTableLib + BaseMemoryLib + DebugLib + UefiRuntimeLib + DxeServicesTableLib + PcdLib + TpmMeasurementLib + AuthVariableLib + VarCheckLib + VariablePolicyLib + VariablePolicyHelperLib + VariableFlashInfoLib + PrintLib + + +[Protocols] + gEdkiiVariablePolicyProtocolGuid ## CONSUMES + + +[Guids] + gVariableFlashInfoHobGuid + gEfiHardwareErrorVariableGuid + + ## SOMETIMES_CONSUMES ## GUID # Signature of Variable store header + ## SOMETIMES_PRODUCES ## GUID # Signature of Variable store header + ## SOMETIMES_CONSUMES ## HOB + ## SOMETIMES_PRODUCES ## SystemTable + gEfiAuthenticatedVariableGuid + + ## SOMETIMES_CONSUMES ## GUID # Signature of Variable store header + ## SOMETIMES_PRODUCES ## GUID # Signature of Variable store header + ## SOMETIMES_CONSUMES ## HOB + ## SOMETIMES_PRODUCES ## SystemTable + gEfiVariableGuid + + ## SOMETIMES_CONSUMES ## Variable:L"PlatformLang" + ## SOMETIMES_PRODUCES ## Variable:L"PlatformLang" + ## SOMETIMES_CONSUMES ## Variable:L"Lang" + ## SOMETIMES_PRODUCES ## Variable:L"Lang" + ## SOMETIMES_CONSUMES ## Variable:L"PK" + ## SOMETIMES_CONSUMES ## Variable:L"KEK" + ## SOMETIMES_CONSUMES ## Variable:L"SecureBoot" + gEfiGlobalVariableGuid + + gEfiMemoryOverwriteControlDataGuid ## SOMETIMES_CONSUMES ## Variable:L"MemoryOverwriteRequestControl" + gEfiMemoryOverwriteRequestControlLockGuid ## SOMETIMES_PRODUCES ## Variable:L"MemoryOverwriteRequestControlLock" + + gEfiEventVirtualAddressChangeGuid ## CONSUMES ## Event + gEfiSystemNvDataFvGuid ## CONSUMES ## GUID + gEfiEndOfDxeEventGroupGuid ## CONSUMES ## Event + gEdkiiFaultTolerantWriteGuid ## SOMETIMES_CONSUMES ## HOB + + ## SOMETIMES_CONSUMES ## Variable:L"VarErrorFlag" + ## SOMETIMES_PRODUCES ## Variable:L"VarErrorFlag" + gEdkiiVarErrorFlagGuid + + ## SOMETIMES_CONSUMES ## Variable:L"db" + ## SOMETIMES_CONSUMES ## Variable:L"dbx" + ## SOMETIMES_CONSUMES ## Variable:L"dbt" + gEfiImageSecurityDatabaseGuid + + +[Pcd] + gEfiMdeModulePkgTokenSpaceGuid.PcdFlashNvStorageVariableSize ## CONSUMES + gEfiMdeModulePkgTokenSpaceGuid.PcdFlashNvStorageVariableBase ## SOMETIMES_CONSUMES + gEfiMdeModulePkgTokenSpaceGuid.PcdFlashNvStorageVariableBase64 ## CONSUMES + gEfiMdeModulePkgTokenSpaceGuid.PcdMaxVariableSize ## CONSUMES + gEfiMdeModulePkgTokenSpaceGuid.PcdMaxAuthVariableSize ## CONSUMES + gEfiMdeModulePkgTokenSpaceGuid.PcdMaxVolatileVariableSize ## CONSUMES + gEfiMdeModulePkgTokenSpaceGuid.PcdMaxHardwareErrorVariableSize ## CONSUMES + gEfiMdeModulePkgTokenSpaceGuid.PcdVariableStoreSize ## CONSUMES + gEfiMdeModulePkgTokenSpaceGuid.PcdHwErrStorageSize ## CONSUMES + gEfiMdeModulePkgTokenSpaceGuid.PcdMaxUserNvVariableSpaceSize ## CONSUMES + gEfiMdeModulePkgTokenSpaceGuid.PcdBoottimeReservedNvVariableSpaceSize ## CONSUMES + gEfiMdeModulePkgTokenSpaceGuid.PcdReclaimVariableSpaceAtEndOfDxe ## CONSUMES + gEfiMdeModulePkgTokenSpaceGuid.PcdEmuVariableNvModeEnable ## SOMETIMES_CONSUMES + gEfiMdeModulePkgTokenSpaceGuid.PcdEmuVariableNvStoreReserved ## SOMETIMES_CONSUMES + + +[FeaturePcd] + gEfiMdeModulePkgTokenSpaceGuid.PcdVariableCollectStatistics ## CONSUMES # statistic the information of variable. + gEfiMdePkgTokenSpaceGuid.PcdUefiVariableDefaultLangDeprecate ## CONSUMES # Auto update PlatformLang/Lang + + + +[BuildOptions] + # NOTE: For some reason the MSABI VA_ARGS funcs are causing a SegFault in Linux + GCC:NOOPT_*_*_CC_FLAGS = -include Uefi.h -DNO_MSABI_VA_FUNCS + MSFT:NOOPT_*_*_CC_FLAGS = /FIUefi.h diff --git a/MdePkg/Library/BaseBinSecurityLibNull/BaseBinSecurityLibNull.inf b/MdePkg/Library/BaseBinSecurityLibNull/BaseBinSecurityLibNull.inf index 91ac8a14c6..8a6ad4b7ff 100644 --- a/MdePkg/Library/BaseBinSecurityLibNull/BaseBinSecurityLibNull.inf +++ b/MdePkg/Library/BaseBinSecurityLibNull/BaseBinSecurityLibNull.inf @@ -1,24 +1,24 @@ -## @file BaseBinSecurityLibNull.inf -# -# MS_CHANGE_? -# -## -# Copyright (c) Microsoft Corporation. All rights reserved. -# SPDX-License-Identifier: BSD-2-Clause-Patent -## - - -[Defines] - INF_VERSION = 0x00010005 - BASE_NAME = BaseBinSecurityLibNull - FILE_GUID = f6ef2763-ca3b-4c6f-a931-2a48de3ce352 - MODULE_TYPE = BASE - VERSION_STRING = 1.0 - LIBRARY_CLASS = BaseBinSecurityLib - -[Sources] - BaseBinSecurityLibNull.c - -[Packages] - MdePkg/MdePkg.dec - +## @file BaseBinSecurityLibNull.inf +# +# MS_CHANGE_? +# +## +# Copyright (c) Microsoft Corporation. All rights reserved. +# SPDX-License-Identifier: BSD-2-Clause-Patent +## + + +[Defines] + INF_VERSION = 0x00010005 + BASE_NAME = BaseBinSecurityLibNull + FILE_GUID = f6ef2763-ca3b-4c6f-a931-2a48de3ce352 + MODULE_TYPE = BASE + VERSION_STRING = 1.0 + LIBRARY_CLASS = BaseBinSecurityLib + +[Sources] + BaseBinSecurityLibNull.c + +[Packages] + MdePkg/MdePkg.dec + diff --git a/MdePkg/Library/BaseBinSecurityLibRng/BaseBinSecurityLibRng.inf b/MdePkg/Library/BaseBinSecurityLibRng/BaseBinSecurityLibRng.inf index 7890d84e70..9a8d3baa01 100644 --- a/MdePkg/Library/BaseBinSecurityLibRng/BaseBinSecurityLibRng.inf +++ b/MdePkg/Library/BaseBinSecurityLibRng/BaseBinSecurityLibRng.inf @@ -1,38 +1,38 @@ -## @file BaseBinSecurityLibRng.inf -# -# MS_CHANGE_? -# -## -# Copyright (c) Microsoft Corporation. All rights reserved. -# SPDX-License-Identifier: BSD-2-Clause-Patent -## - - -[Defines] - INF_VERSION = 0x00010005 - BASE_NAME = BaseBinSecurityLibRng - FILE_GUID = 495b10c8-7148-4b62-92b0-7cf4551df83d - MODULE_TYPE = BASE - VERSION_STRING = 1.0 - LIBRARY_CLASS = BaseBinSecurityLib - -[Sources] - BaseBinSecurityLibRng.c - -[Sources.X64] - X64/report_rangecheckfailure.asm - X64/GSHandlerCheck.asm - X64/security_check_cookie.asm - -[Packages] - MdePkg/MdePkg.dec - -[LibraryClasses] - BaseMemoryLib - DebugLib - BaseLib - RngLib - PcdLib - -[FixedPcd] - gEfiMdePkgTokenSpaceGuid.PcdStackCookieExceptionVector +## @file BaseBinSecurityLibRng.inf +# +# MS_CHANGE_? +# +## +# Copyright (c) Microsoft Corporation. All rights reserved. +# SPDX-License-Identifier: BSD-2-Clause-Patent +## + + +[Defines] + INF_VERSION = 0x00010005 + BASE_NAME = BaseBinSecurityLibRng + FILE_GUID = 495b10c8-7148-4b62-92b0-7cf4551df83d + MODULE_TYPE = BASE + VERSION_STRING = 1.0 + LIBRARY_CLASS = BaseBinSecurityLib + +[Sources] + BaseBinSecurityLibRng.c + +[Sources.X64] + X64/report_rangecheckfailure.asm + X64/GSHandlerCheck.asm + X64/security_check_cookie.asm + +[Packages] + MdePkg/MdePkg.dec + +[LibraryClasses] + BaseMemoryLib + DebugLib + BaseLib + RngLib + PcdLib + +[FixedPcd] + gEfiMdePkgTokenSpaceGuid.PcdStackCookieExceptionVector diff --git a/MdePkg/Library/BaseBinSecurityLibRng/X64/GSHandlerCheck.asm b/MdePkg/Library/BaseBinSecurityLibRng/X64/GSHandlerCheck.asm index d16c9eaf0e..bd1de566f4 100644 --- a/MdePkg/Library/BaseBinSecurityLibRng/X64/GSHandlerCheck.asm +++ b/MdePkg/Library/BaseBinSecurityLibRng/X64/GSHandlerCheck.asm @@ -1,18 +1,18 @@ -;------------------------------------------------------------------------------ -; GSHandlerCheck.asm -; MS_CHANGE_? -;------------------------------------------------------------------------------ - .code - -;------------------------------------------------------------------------------ -; VOID -; EFIAPI -; __GSHandlerCheck (VOID); -;------------------------------------------------------------------------------ -__GSHandlerCheck PROC PUBLIC - ret ; this GS handler is for checking the stack cookie during SEH or - ; EH exceptions since UEFI doesn't support these we can just do - ; nothing here -__GSHandlerCheck ENDP - +;------------------------------------------------------------------------------ +; GSHandlerCheck.asm +; MS_CHANGE_? +;------------------------------------------------------------------------------ + .code + +;------------------------------------------------------------------------------ +; VOID +; EFIAPI +; __GSHandlerCheck (VOID); +;------------------------------------------------------------------------------ +__GSHandlerCheck PROC PUBLIC + ret ; this GS handler is for checking the stack cookie during SEH or + ; EH exceptions since UEFI doesn't support these we can just do + ; nothing here +__GSHandlerCheck ENDP + END \ No newline at end of file diff --git a/MdePkg/Library/BaseBinSecurityLibRng/X64/report_rangecheckfailure.asm b/MdePkg/Library/BaseBinSecurityLibRng/X64/report_rangecheckfailure.asm index 0032594ec6..2546ba75a5 100644 --- a/MdePkg/Library/BaseBinSecurityLibRng/X64/report_rangecheckfailure.asm +++ b/MdePkg/Library/BaseBinSecurityLibRng/X64/report_rangecheckfailure.asm @@ -1,18 +1,18 @@ -;------------------------------------------------------------------------------ -; report_rangecheckfailure.asm -; MS_CHANGE_? -;------------------------------------------------------------------------------ - .code - -;------------------------------------------------------------------------------ -; VOID -; EFIAPI -; __report_rangecheckfailure (VOID); -;------------------------------------------------------------------------------ - -__report_rangecheckfailure PROC PUBLIC - int 3 - ret -__report_rangecheckfailure ENDP - - END +;------------------------------------------------------------------------------ +; report_rangecheckfailure.asm +; MS_CHANGE_? +;------------------------------------------------------------------------------ + .code + +;------------------------------------------------------------------------------ +; VOID +; EFIAPI +; __report_rangecheckfailure (VOID); +;------------------------------------------------------------------------------ + +__report_rangecheckfailure PROC PUBLIC + int 3 + ret +__report_rangecheckfailure ENDP + + END diff --git a/MdePkg/Library/BaseBinSecurityLibRng/X64/security_check_cookie.asm b/MdePkg/Library/BaseBinSecurityLibRng/X64/security_check_cookie.asm index 51be0f0761..cbc2cbeb0b 100644 --- a/MdePkg/Library/BaseBinSecurityLibRng/X64/security_check_cookie.asm +++ b/MdePkg/Library/BaseBinSecurityLibRng/X64/security_check_cookie.asm @@ -1,24 +1,24 @@ -;------------------------------------------------------------------------------ -; security_check_cookie.asm -; MS_CHANGE_? -;------------------------------------------------------------------------------ - EXTRN __security_cookie:QWORD - .code - -;------------------------------------------------------------------------------ -; VOID -; EFIAPI -; __security_check_cookie ( -; IN UINTN CheckValue); -;------------------------------------------------------------------------------ -__security_check_cookie PROC PUBLIC - cmp rcx, __security_cookie - jne __security_check_cookie_Failure - ret - -__security_check_cookie_Failure: - int FixedPcdGet8 (PcdStackCookieExceptionVector) - ret -__security_check_cookie ENDP - - END +;------------------------------------------------------------------------------ +; security_check_cookie.asm +; MS_CHANGE_? +;------------------------------------------------------------------------------ + EXTRN __security_cookie:QWORD + .code + +;------------------------------------------------------------------------------ +; VOID +; EFIAPI +; __security_check_cookie ( +; IN UINTN CheckValue); +;------------------------------------------------------------------------------ +__security_check_cookie PROC PUBLIC + cmp rcx, __security_cookie + jne __security_check_cookie_Failure + ret + +__security_check_cookie_Failure: + int FixedPcdGet8 (PcdStackCookieExceptionVector) + ret +__security_check_cookie ENDP + + END diff --git a/MdePkg/Library/BaseLib/AArch64/CpuBreakAssert.S b/MdePkg/Library/BaseLib/AArch64/CpuBreakAssert.S index 23d75dcfd0..3fb17e8a48 100644 --- a/MdePkg/Library/BaseLib/AArch64/CpuBreakAssert.S +++ b/MdePkg/Library/BaseLib/AArch64/CpuBreakAssert.S @@ -1,28 +1,28 @@ -# @file CpuBreakAssert.S -# -# CpuBreakAssert function for AArch64. -# -# Copyright (c) Microsoft Corporation. All rights reserved. -# SPDX-License-Identifier: BSD-2-Clause-Patent -# - -.text -.p2align 2 -GCC_ASM_EXPORT(CpuBreakAssert) - -#/** -# Generates a debugger assertion break on the CPU. -# -# This does a special break into the debugger such that the debugger knows -# that the code running has hit an assertion, not a generic breakpoint. -# -#**/ -#VOID -#EFIAPI -#CpuBreakAssert ( -# VOID -# ); -# -ASM_PFX(CpuBreakAssert): - brk 0xf001 - ret +# @file CpuBreakAssert.S +# +# CpuBreakAssert function for AArch64. +# +# Copyright (c) Microsoft Corporation. All rights reserved. +# SPDX-License-Identifier: BSD-2-Clause-Patent +# + +.text +.p2align 2 +GCC_ASM_EXPORT(CpuBreakAssert) + +#/** +# Generates a debugger assertion break on the CPU. +# +# This does a special break into the debugger such that the debugger knows +# that the code running has hit an assertion, not a generic breakpoint. +# +#**/ +#VOID +#EFIAPI +#CpuBreakAssert ( +# VOID +# ); +# +ASM_PFX(CpuBreakAssert): + brk 0xf001 + ret diff --git a/MdePkg/Library/BaseMmuLibNull/BaseMmuLibNull.inf b/MdePkg/Library/BaseMmuLibNull/BaseMmuLibNull.inf index 64b2282b2e..75e521931c 100644 --- a/MdePkg/Library/BaseMmuLibNull/BaseMmuLibNull.inf +++ b/MdePkg/Library/BaseMmuLibNull/BaseMmuLibNull.inf @@ -1,29 +1,29 @@ -## @file -# This lib abstracts some of the MMU accesses currently hardcoded against -# an Arm lib. It's likely that this will need to be refactored at some point. -# -## -# Copyright (c) Microsoft Corporation. -# SPDX-License-Identifier: BSD-2-Clause-Patent -## - - -[Defines] - INF_VERSION = 0x00010017 - BASE_NAME = BaseMmuLibNull - FILE_GUID = 97196A48-00C0-4487-802A-CC5540583EEB - VERSION_STRING = 1.0 - MODULE_TYPE = BASE - LIBRARY_CLASS = MmuLib - - -[Sources] - BaseMmuLibNull.c - - -[LibraryClasses] - DebugLib - - -[Packages] - MdePkg/MdePkg.dec +## @file +# This lib abstracts some of the MMU accesses currently hardcoded against +# an Arm lib. It's likely that this will need to be refactored at some point. +# +## +# Copyright (c) Microsoft Corporation. +# SPDX-License-Identifier: BSD-2-Clause-Patent +## + + +[Defines] + INF_VERSION = 0x00010017 + BASE_NAME = BaseMmuLibNull + FILE_GUID = 97196A48-00C0-4487-802A-CC5540583EEB + VERSION_STRING = 1.0 + MODULE_TYPE = BASE + LIBRARY_CLASS = MmuLib + + +[Sources] + BaseMmuLibNull.c + + +[LibraryClasses] + DebugLib + + +[Packages] + MdePkg/MdePkg.dec diff --git a/MdePkg/Library/CompilerIntrinsicsLib/ArmCompilerIntrinsicsLib.inf b/MdePkg/Library/CompilerIntrinsicsLib/ArmCompilerIntrinsicsLib.inf index 8e00557f93..fb941274d6 100644 --- a/MdePkg/Library/CompilerIntrinsicsLib/ArmCompilerIntrinsicsLib.inf +++ b/MdePkg/Library/CompilerIntrinsicsLib/ArmCompilerIntrinsicsLib.inf @@ -1,78 +1,78 @@ -#/** @file -# Base Library implementation. -# -# Copyright (c) 2009, Apple Inc. All rights reserved.
-# Copyright (c) 2011-2013, ARM Limited. All rights reserved. -# -# SPDX-License-Identifier: BSD-2-Clause-Patent -# -# -#**/ - -[Defines] - INF_VERSION = 0x00010005 - BASE_NAME = CompilerIntrinsicsLib - FILE_GUID = 855274FA-3575-4C20-9709-C031DC5589FA - MODULE_TYPE = BASE - VERSION_STRING = 1.0 - LIBRARY_CLASS = CompilerIntrinsicsLib - -[Sources] - - memcpy.c | GCC - memset.c | GCC - - memcpy_ms.c | MSFT - memset_ms.c | MSFT - memcmp_ms.c | MSFT - memmove_ms.c | MSFT - -[Sources.ARM] - - Arm/ashrdi3.S | GCC - Arm/ashldi3.S | GCC - Arm/div.S | GCC - Arm/divdi3.S | GCC - Arm/divsi3.S | GCC - Arm/lshrdi3.S | GCC - Arm/memmove.S | GCC - Arm/modsi3.S | GCC - Arm/moddi3.S | GCC - Arm/muldi3.S | GCC - Arm/mullu.S | GCC - Arm/udivsi3.S | GCC - Arm/umodsi3.S | GCC - Arm/udivdi3.S | GCC - Arm/umoddi3.S | GCC - Arm/udivmoddi4.S | GCC - Arm/clzsi2.S | GCC - Arm/ctzsi2.S | GCC - Arm/ucmpdi2.S | GCC - Arm/switch8.S | GCC - Arm/switchu8.S | GCC - Arm/switch16.S | GCC - Arm/switch32.S | GCC - Arm/sourcery.S | GCC - Arm/uldiv.S | GCC - Arm/ldivmod.S | GCC - Arm/lasr.S | GCC - Arm/llsr.S | GCC - Arm/llsl.S | GCC - Arm/uread.S | GCC - Arm/uwrite.S | GCC - - Arm/div.asm | MSFT - Arm/uldiv.asm | MSFT - Arm/ldivmod.asm | MSFT - Arm/llsr.asm | MSFT - -[Sources.AARCH64] - AArch64/Atomics.S | GCC - -[Packages] - MdePkg/MdePkg.dec - #ArmPkg/ArmPkg.dec - -[BuildOptions] - MSFT:*_*_*_CC_FLAGS = /GL- - MSFT:*_*_ARM_ASM_FLAGS = /oldit +#/** @file +# Base Library implementation. +# +# Copyright (c) 2009, Apple Inc. All rights reserved.
+# Copyright (c) 2011-2013, ARM Limited. All rights reserved. +# +# SPDX-License-Identifier: BSD-2-Clause-Patent +# +# +#**/ + +[Defines] + INF_VERSION = 0x00010005 + BASE_NAME = CompilerIntrinsicsLib + FILE_GUID = 855274FA-3575-4C20-9709-C031DC5589FA + MODULE_TYPE = BASE + VERSION_STRING = 1.0 + LIBRARY_CLASS = CompilerIntrinsicsLib + +[Sources] + + memcpy.c | GCC + memset.c | GCC + + memcpy_ms.c | MSFT + memset_ms.c | MSFT + memcmp_ms.c | MSFT + memmove_ms.c | MSFT + +[Sources.ARM] + + Arm/ashrdi3.S | GCC + Arm/ashldi3.S | GCC + Arm/div.S | GCC + Arm/divdi3.S | GCC + Arm/divsi3.S | GCC + Arm/lshrdi3.S | GCC + Arm/memmove.S | GCC + Arm/modsi3.S | GCC + Arm/moddi3.S | GCC + Arm/muldi3.S | GCC + Arm/mullu.S | GCC + Arm/udivsi3.S | GCC + Arm/umodsi3.S | GCC + Arm/udivdi3.S | GCC + Arm/umoddi3.S | GCC + Arm/udivmoddi4.S | GCC + Arm/clzsi2.S | GCC + Arm/ctzsi2.S | GCC + Arm/ucmpdi2.S | GCC + Arm/switch8.S | GCC + Arm/switchu8.S | GCC + Arm/switch16.S | GCC + Arm/switch32.S | GCC + Arm/sourcery.S | GCC + Arm/uldiv.S | GCC + Arm/ldivmod.S | GCC + Arm/lasr.S | GCC + Arm/llsr.S | GCC + Arm/llsl.S | GCC + Arm/uread.S | GCC + Arm/uwrite.S | GCC + + Arm/div.asm | MSFT + Arm/uldiv.asm | MSFT + Arm/ldivmod.asm | MSFT + Arm/llsr.asm | MSFT + +[Sources.AARCH64] + AArch64/Atomics.S | GCC + +[Packages] + MdePkg/MdePkg.dec + #ArmPkg/ArmPkg.dec + +[BuildOptions] + MSFT:*_*_*_CC_FLAGS = /GL- + MSFT:*_*_ARM_ASM_FLAGS = /oldit diff --git a/MdePkg/Library/FltUsedLib/FltUsedLib.inf b/MdePkg/Library/FltUsedLib/FltUsedLib.inf index 2a0cf28358..dba91aed5d 100644 --- a/MdePkg/Library/FltUsedLib/FltUsedLib.inf +++ b/MdePkg/Library/FltUsedLib/FltUsedLib.inf @@ -1,41 +1,41 @@ -## @file -# Lib to include if using floats -# -# Copyright (C) Microsoft Corporation. All rights reserved.. -# SPDX-License-Identifier: BSD-2-Clause-Patent -## - -[Defines] - INF_VERSION = 0x00010005 - BASE_NAME = FltUsedLib - FILE_GUID = C004F180-9FE2-4D2B-8318-BADC2A231774 - MODULE_TYPE = BASE - VERSION_STRING = 1.0 - LIBRARY_CLASS = FltUsedLib - -# -# The following information is for reference only and not required by the build tools. -# -# VALID_ARCHITECTURES = IA32 X64 AARCH64 -# - -[Sources] - FltUsedLib.c - -[Packages] - MdePkg/MdePkg.dec - -[LibraryClasses] - -[Guids] - -[Protocols] - -[BuildOptions] - # Disable GL due to linker error LNK1237 - # https://docs.microsoft.com/en-us/cpp/error-messages/tool-errors/linker-tools-error-lnk1237?view=vs-2017 - MSFT:*_*_*_CC_FLAGS = /GL- - -[Depex] - TRUE - +## @file +# Lib to include if using floats +# +# Copyright (C) Microsoft Corporation. All rights reserved.. +# SPDX-License-Identifier: BSD-2-Clause-Patent +## + +[Defines] + INF_VERSION = 0x00010005 + BASE_NAME = FltUsedLib + FILE_GUID = C004F180-9FE2-4D2B-8318-BADC2A231774 + MODULE_TYPE = BASE + VERSION_STRING = 1.0 + LIBRARY_CLASS = FltUsedLib + +# +# The following information is for reference only and not required by the build tools. +# +# VALID_ARCHITECTURES = IA32 X64 AARCH64 +# + +[Sources] + FltUsedLib.c + +[Packages] + MdePkg/MdePkg.dec + +[LibraryClasses] + +[Guids] + +[Protocols] + +[BuildOptions] + # Disable GL due to linker error LNK1237 + # https://docs.microsoft.com/en-us/cpp/error-messages/tool-errors/linker-tools-error-lnk1237?view=vs-2017 + MSFT:*_*_*_CC_FLAGS = /GL- + +[Depex] + TRUE + diff --git a/MdePkg/Library/FltUsedLib/Readme.md b/MdePkg/Library/FltUsedLib/Readme.md index aa2053f6d8..df0133ccf1 100644 --- a/MdePkg/Library/FltUsedLib/Readme.md +++ b/MdePkg/Library/FltUsedLib/Readme.md @@ -1,15 +1,15 @@ -# FltUsedLib - -This library provides a global (fltused) that needs to be defined anywhere floating point operations are used. -The C compiler produces the _fltused symbol by default, this is just to satisfy the linker. - -## Using - -To use FltUsedLib, just include it in the INF of the module that uses floating point. - -```inf -[LibraryClasses] - BaseLib - BaseMemoryLib - FltUsedLib -``` +# FltUsedLib + +This library provides a global (fltused) that needs to be defined anywhere floating point operations are used. +The C compiler produces the _fltused symbol by default, this is just to satisfy the linker. + +## Using + +To use FltUsedLib, just include it in the INF of the module that uses floating point. + +```inf +[LibraryClasses] + BaseLib + BaseMemoryLib + FltUsedLib +``` diff --git a/MdePkg/Library/VsIntrinsicLib/IA32/llmul.asm b/MdePkg/Library/VsIntrinsicLib/IA32/llmul.asm index 190392da1b..8d3143cf84 100644 --- a/MdePkg/Library/VsIntrinsicLib/IA32/llmul.asm +++ b/MdePkg/Library/VsIntrinsicLib/IA32/llmul.asm @@ -1,98 +1,98 @@ -;*** -;llmul.asm - long multiply routine -; -; Copyright (c) Microsoft Corporation. All rights reserved. -; SPDX-License-Identifier: BSD-2-Clause-Patent -; -;Purpose: -; Defines long multiply routine -; Both signed and unsigned routines are the same, since multiply's -; work out the same in 2's complement -; creates the following routine: -; __allmul -; -;Original Implemenation: MSVC 14.12.25827 -; -;******************************************************************************* - .686 - .model flat,C - .code - - -;*** -;llmul - long multiply routine -; -;Purpose: -; Does a long multiply (same for signed/unsigned) -; Parameters are not changed. -; -;Entry: -; Parameters are passed on the stack: -; 1st pushed: multiplier (QWORD) -; 2nd pushed: multiplicand (QWORD) -; -;Exit: -; EDX:EAX - product of multiplier and multiplicand -; NOTE: parameters are removed from the stack -; -;Uses: -; ECX -; -;Exceptions: -; -;******************************************************************************* -_allmul PROC NEAR - -A EQU [esp + 4] ; stack address of a -B EQU [esp + 12] ; stack address of b - -HIGH_PART EQU [4] ; -LOW_PART EQU [0] - -; -; AHI, BHI : upper 32 bits of A and B -; ALO, BLO : lower 32 bits of A and B -; -; ALO * BLO -; ALO * BHI -; + BLO * AHI -; --------------------- -; - - mov eax,HIGH_PART(A) - mov ecx,HIGH_PART(B) - or ecx,eax ;test for both high dwords zero. - mov ecx,LOW_PART(B) - jnz short hard ;both are zero, just mult ALO and BLO - - mov eax,LOW_PART(A) - mul ecx - - ret 16 ; callee restores the stack - -hard: - push ebx - -; must redefine A and B since esp has been altered - -A2 EQU [esp + 8] ; stack address of a -B2 EQU [esp + 16] ; stack address of b - - mul ecx ;eax has AHI, ecx has BLO, so AHI * BLO - mov ebx,eax ;save result - - mov eax,LOW_PART(A2) - mul dword ptr HIGH_PART(B2) ;ALO * BHI - add ebx,eax ;ebx = ((ALO * BHI) + (AHI * BLO)) - - mov eax,LOW_PART(A2);ecx = BLO - mul ecx ;so edx:eax = ALO*BLO - add edx,ebx ;now edx has all the LO*HI stuff - - pop ebx - - ret 16 ; callee restores the stack - -_allmul ENDP - - end +;*** +;llmul.asm - long multiply routine +; +; Copyright (c) Microsoft Corporation. All rights reserved. +; SPDX-License-Identifier: BSD-2-Clause-Patent +; +;Purpose: +; Defines long multiply routine +; Both signed and unsigned routines are the same, since multiply's +; work out the same in 2's complement +; creates the following routine: +; __allmul +; +;Original Implemenation: MSVC 14.12.25827 +; +;******************************************************************************* + .686 + .model flat,C + .code + + +;*** +;llmul - long multiply routine +; +;Purpose: +; Does a long multiply (same for signed/unsigned) +; Parameters are not changed. +; +;Entry: +; Parameters are passed on the stack: +; 1st pushed: multiplier (QWORD) +; 2nd pushed: multiplicand (QWORD) +; +;Exit: +; EDX:EAX - product of multiplier and multiplicand +; NOTE: parameters are removed from the stack +; +;Uses: +; ECX +; +;Exceptions: +; +;******************************************************************************* +_allmul PROC NEAR + +A EQU [esp + 4] ; stack address of a +B EQU [esp + 12] ; stack address of b + +HIGH_PART EQU [4] ; +LOW_PART EQU [0] + +; +; AHI, BHI : upper 32 bits of A and B +; ALO, BLO : lower 32 bits of A and B +; +; ALO * BLO +; ALO * BHI +; + BLO * AHI +; --------------------- +; + + mov eax,HIGH_PART(A) + mov ecx,HIGH_PART(B) + or ecx,eax ;test for both high dwords zero. + mov ecx,LOW_PART(B) + jnz short hard ;both are zero, just mult ALO and BLO + + mov eax,LOW_PART(A) + mul ecx + + ret 16 ; callee restores the stack + +hard: + push ebx + +; must redefine A and B since esp has been altered + +A2 EQU [esp + 8] ; stack address of a +B2 EQU [esp + 16] ; stack address of b + + mul ecx ;eax has AHI, ecx has BLO, so AHI * BLO + mov ebx,eax ;save result + + mov eax,LOW_PART(A2) + mul dword ptr HIGH_PART(B2) ;ALO * BHI + add ebx,eax ;ebx = ((ALO * BHI) + (AHI * BLO)) + + mov eax,LOW_PART(A2);ecx = BLO + mul ecx ;so edx:eax = ALO*BLO + add edx,ebx ;now edx has all the LO*HI stuff + + pop ebx + + ret 16 ; callee restores the stack + +_allmul ENDP + + end diff --git a/MdePkg/Library/VsIntrinsicLib/VsIntrinsicLib.inf b/MdePkg/Library/VsIntrinsicLib/VsIntrinsicLib.inf index d2a8db898c..fc99e1a734 100644 --- a/MdePkg/Library/VsIntrinsicLib/VsIntrinsicLib.inf +++ b/MdePkg/Library/VsIntrinsicLib/VsIntrinsicLib.inf @@ -1,37 +1,37 @@ -## @file -# Visual Studio 2017 C compiler intrinsic Library implementation. -# -# Since the C compiler does very aggressive full program optimizations there are cases -# where some small number of compiler inserted functions can not be avoided. -# To handle that case this NULL library can be injected into all 32bit modules -# so that the link time dependency is met and the modules compile. -# -# The routines are based on src delivered with the visual studio product. it is -# critical that calling convention, stack usage, register usage, etc is in line -# with what the compiler expects as there is no way to influence the behaviors -# for compiler inserted functions. -# -# Copyright (c) Microsoft Corporation. All rights reserved. -# SPDX-License-Identifier: BSD-2-Clause-Patent -## - -[Defines] - INF_VERSION = 0x00010005 - BASE_NAME = VsIntrinsicLib - MODULE_UNI_FILE = VsIntrinsicLib.uni - FILE_GUID = ed449fc0-3265-40ed-91b8-435b8df0aa5f - MODULE_TYPE = BASE - VERSION_STRING = 1.0 - LIBRARY_CLASS = NULL - -# -# VALID_ARCHITECTURES = IA32 -# - -[Sources] - -[Sources.Ia32] - IA32/llmul.asm - -[Packages] - MdePkg/MdePkg.dec +## @file +# Visual Studio 2017 C compiler intrinsic Library implementation. +# +# Since the C compiler does very aggressive full program optimizations there are cases +# where some small number of compiler inserted functions can not be avoided. +# To handle that case this NULL library can be injected into all 32bit modules +# so that the link time dependency is met and the modules compile. +# +# The routines are based on src delivered with the visual studio product. it is +# critical that calling convention, stack usage, register usage, etc is in line +# with what the compiler expects as there is no way to influence the behaviors +# for compiler inserted functions. +# +# Copyright (c) Microsoft Corporation. All rights reserved. +# SPDX-License-Identifier: BSD-2-Clause-Patent +## + +[Defines] + INF_VERSION = 0x00010005 + BASE_NAME = VsIntrinsicLib + MODULE_UNI_FILE = VsIntrinsicLib.uni + FILE_GUID = ed449fc0-3265-40ed-91b8-435b8df0aa5f + MODULE_TYPE = BASE + VERSION_STRING = 1.0 + LIBRARY_CLASS = NULL + +# +# VALID_ARCHITECTURES = IA32 +# + +[Sources] + +[Sources.Ia32] + IA32/llmul.asm + +[Packages] + MdePkg/MdePkg.dec diff --git a/MdePkg/Library/VsIntrinsicLib/VsIntrinsicLib.uni b/MdePkg/Library/VsIntrinsicLib/VsIntrinsicLib.uni index c4513808fd..59e624b4f4 100644 --- a/MdePkg/Library/VsIntrinsicLib/VsIntrinsicLib.uni +++ b/MdePkg/Library/VsIntrinsicLib/VsIntrinsicLib.uni @@ -1,17 +1,17 @@ -// /** @file -// VsIntrinsic Library implementation. -// -// VsIntrinsic Library implementation. -// -// -// -//Copyright (c) Microsoft Corporation. All rights reserved. -//SPDX-License-Identifier: BSD-2-Clause-Patent -// -//**/ - - -#string STR_MODULE_ABSTRACT #language en-US "VsIntrinsic Library implementation" - -#string STR_MODULE_DESCRIPTION #language en-US "VsIntrinsic Library implementation" - +// /** @file +// VsIntrinsic Library implementation. +// +// VsIntrinsic Library implementation. +// +// +// +//Copyright (c) Microsoft Corporation. All rights reserved. +//SPDX-License-Identifier: BSD-2-Clause-Patent +// +//**/ + + +#string STR_MODULE_ABSTRACT #language en-US "VsIntrinsic Library implementation" + +#string STR_MODULE_DESCRIPTION #language en-US "VsIntrinsic Library implementation" + diff --git a/MdePkg/Test/Library/RngLibHostTestLfsr/RngLibHostTestLfsr.inf b/MdePkg/Test/Library/RngLibHostTestLfsr/RngLibHostTestLfsr.inf index 03228bbfc3..18d9bf17fd 100644 --- a/MdePkg/Test/Library/RngLibHostTestLfsr/RngLibHostTestLfsr.inf +++ b/MdePkg/Test/Library/RngLibHostTestLfsr/RngLibHostTestLfsr.inf @@ -1,25 +1,25 @@ -## @file -# A minimal implementation of RngLib that supports host based testing -# with a simple LFSR: -# https://en.wikipedia.org/wiki/Linear-feedback_shift_register -# -# Copyright (c) Microsoft Corporation. -# SPDX-License-Identifier: BSD-2-Clause-Patent -## - - -[Defines] - INF_VERSION = 0x00010017 - BASE_NAME = RngLibHostTestLfsr - FILE_GUID = E96C1E06-1052-4967-9FF2-F3E07EE02D8B - VERSION_STRING = 1.0 - MODULE_TYPE = HOST_APPLICATION - LIBRARY_CLASS = RngLib|HOST_APPLICATION - - -[Sources] - RngLibHostTestLfsr.c - - -[Packages] - MdePkg/MdePkg.dec +## @file +# A minimal implementation of RngLib that supports host based testing +# with a simple LFSR: +# https://en.wikipedia.org/wiki/Linear-feedback_shift_register +# +# Copyright (c) Microsoft Corporation. +# SPDX-License-Identifier: BSD-2-Clause-Patent +## + + +[Defines] + INF_VERSION = 0x00010017 + BASE_NAME = RngLibHostTestLfsr + FILE_GUID = E96C1E06-1052-4967-9FF2-F3E07EE02D8B + VERSION_STRING = 1.0 + MODULE_TYPE = HOST_APPLICATION + LIBRARY_CLASS = RngLib|HOST_APPLICATION + + +[Sources] + RngLibHostTestLfsr.c + + +[Packages] + MdePkg/MdePkg.dec diff --git a/MdePkg/Test/Library/StubUefiLib/StubUefiLib.inf b/MdePkg/Test/Library/StubUefiLib/StubUefiLib.inf index 487a502b53..c6d83c1496 100644 --- a/MdePkg/Test/Library/StubUefiLib/StubUefiLib.inf +++ b/MdePkg/Test/Library/StubUefiLib/StubUefiLib.inf @@ -1,37 +1,37 @@ -## @file -# Mock instance of UEFI Library. -# -# The UEFI Library provides functions and macros that simplify the development of -# UEFI Drivers and UEFI Applications. These functions and macros help manage EFI -# events, build simple locks utilizing EFI Task Priority Levels (TPLs), install -# EFI Driver Model related protocols, manage Unicode string tables for UEFI Drivers, -# and print messages on the console output and standard error devices. -# -# Copyright (c) Microsoft Corporation. -# SPDX-License-Identifier: BSD-2-Clause-Patent -## - -[Defines] - INF_VERSION = 0x00010005 - BASE_NAME = StubUefiLib - FILE_GUID = 2834A68A-7201-4931-B953-53EA5E45AA14 - MODULE_TYPE = HOST_APPLICATION - VERSION_STRING = 1.0 - LIBRARY_CLASS = UefiLib|HOST_APPLICATION - - -# -# VALID_ARCHITECTURES = IA32 X64 EBC -# - -[Sources] - StubUefiLib.c - - -[Packages] - MdePkg/MdePkg.dec - UnitTestFrameworkPkg/UnitTestFrameworkPkg.dec - - -[LibraryClasses] - DebugLib +## @file +# Mock instance of UEFI Library. +# +# The UEFI Library provides functions and macros that simplify the development of +# UEFI Drivers and UEFI Applications. These functions and macros help manage EFI +# events, build simple locks utilizing EFI Task Priority Levels (TPLs), install +# EFI Driver Model related protocols, manage Unicode string tables for UEFI Drivers, +# and print messages on the console output and standard error devices. +# +# Copyright (c) Microsoft Corporation. +# SPDX-License-Identifier: BSD-2-Clause-Patent +## + +[Defines] + INF_VERSION = 0x00010005 + BASE_NAME = StubUefiLib + FILE_GUID = 2834A68A-7201-4931-B953-53EA5E45AA14 + MODULE_TYPE = HOST_APPLICATION + VERSION_STRING = 1.0 + LIBRARY_CLASS = UefiLib|HOST_APPLICATION + + +# +# VALID_ARCHITECTURES = IA32 X64 EBC +# + +[Sources] + StubUefiLib.c + + +[Packages] + MdePkg/MdePkg.dec + UnitTestFrameworkPkg/UnitTestFrameworkPkg.dec + + +[LibraryClasses] + DebugLib diff --git a/MdePkg/Test/ShellTest/MemoryAttributeProtocolFuncTestApp/MemoryAttributeProtocolFuncTestApp.inf b/MdePkg/Test/ShellTest/MemoryAttributeProtocolFuncTestApp/MemoryAttributeProtocolFuncTestApp.inf index 181e5ffaad..7f808cde83 100644 --- a/MdePkg/Test/ShellTest/MemoryAttributeProtocolFuncTestApp/MemoryAttributeProtocolFuncTestApp.inf +++ b/MdePkg/Test/ShellTest/MemoryAttributeProtocolFuncTestApp/MemoryAttributeProtocolFuncTestApp.inf @@ -1,40 +1,40 @@ -## @file -# TCBZ3519 -# Uefi Shell based Application that unit tests the Memory Attribute Protocol. -# -# Copyright (c) Microsoft Corporation. -# SPDX-License-Identifier: BSD-2-Clause-Patent -## - -[Defines] - INF_VERSION = 0x00010005 - BASE_NAME = MemoryAttributeProtocolFuncTestApp - FILE_GUID = bb7f9547-68db-4bf0-a247-c022c6146df3 - MODULE_TYPE = UEFI_APPLICATION - VERSION_STRING = 1.0 - ENTRY_POINT = UefiMain - -[Sources] - MemoryAttributeProtocolFuncTestApp.c - MemoryAttributeProtocolFuncTestApp.h - -[Sources.X64] - X64/PageSplitTest.c - -[Sources.IA32, Sources.AARCH64] - PageSplitTest.c - -[Packages] - MdePkg/MdePkg.dec - UnitTestFrameworkPkg/UnitTestFrameworkPkg.dec - -[LibraryClasses] - UefiApplicationEntryPoint - UnitTestLib - UefiBootServicesTableLib - DebugLib - -[Guids] - -[Protocols] - gEfiMemoryAttributeProtocolGuid +## @file +# TCBZ3519 +# Uefi Shell based Application that unit tests the Memory Attribute Protocol. +# +# Copyright (c) Microsoft Corporation. +# SPDX-License-Identifier: BSD-2-Clause-Patent +## + +[Defines] + INF_VERSION = 0x00010005 + BASE_NAME = MemoryAttributeProtocolFuncTestApp + FILE_GUID = bb7f9547-68db-4bf0-a247-c022c6146df3 + MODULE_TYPE = UEFI_APPLICATION + VERSION_STRING = 1.0 + ENTRY_POINT = UefiMain + +[Sources] + MemoryAttributeProtocolFuncTestApp.c + MemoryAttributeProtocolFuncTestApp.h + +[Sources.X64] + X64/PageSplitTest.c + +[Sources.IA32, Sources.AARCH64] + PageSplitTest.c + +[Packages] + MdePkg/MdePkg.dec + UnitTestFrameworkPkg/UnitTestFrameworkPkg.dec + +[LibraryClasses] + UefiApplicationEntryPoint + UnitTestLib + UefiBootServicesTableLib + DebugLib + +[Guids] + +[Protocols] + gEfiMemoryAttributeProtocolGuid diff --git a/MdePkg/Test/ShellTest/MemoryAttributeProtocolFuncTestApp/Readme.md b/MdePkg/Test/ShellTest/MemoryAttributeProtocolFuncTestApp/Readme.md index 3cea67e2c8..43bbc3a8f9 100644 --- a/MdePkg/Test/ShellTest/MemoryAttributeProtocolFuncTestApp/Readme.md +++ b/MdePkg/Test/ShellTest/MemoryAttributeProtocolFuncTestApp/Readme.md @@ -1,19 +1,19 @@ -# Memory Attribute Protocol UEFI shell functional Test - -## 🔹 Copyright - -Copyright (C) Microsoft Corporation. All rights reserved. -SPDX-License-Identifier: BSD-2-Clause-Patent - -## Attribution - -This test is a modified version of . - -## About This Test - -Tests does basic verification of the Memory Attribute Protocol - -* Make sure protocol exists -* Basic "good path" usage of Get/Clear/Set functions -* Get Attributes of a newly allocated EfiLoaderCode buffer -* Verify Attributes of running code (this test code) +# Memory Attribute Protocol UEFI shell functional Test + +## 🔹 Copyright + +Copyright (C) Microsoft Corporation. All rights reserved. +SPDX-License-Identifier: BSD-2-Clause-Patent + +## Attribution + +This test is a modified version of . + +## About This Test + +Tests does basic verification of the Memory Attribute Protocol + +* Make sure protocol exists +* Basic "good path" usage of Get/Clear/Set functions +* Get Attributes of a newly allocated EfiLoaderCode buffer +* Verify Attributes of running code (this test code) diff --git a/MdePkg/Test/UnitTest/Library/BaseLib/BaseLibUnitTestApp.inf b/MdePkg/Test/UnitTest/Library/BaseLib/BaseLibUnitTestApp.inf index bbf72e834c..c7b3674fe5 100644 --- a/MdePkg/Test/UnitTest/Library/BaseLib/BaseLibUnitTestApp.inf +++ b/MdePkg/Test/UnitTest/Library/BaseLib/BaseLibUnitTestApp.inf @@ -1,33 +1,33 @@ -## @file -# Unit tests of Base64 conversion APIs in BaseLib that are run from UEFI Shell. -# -# Copyright (C) Microsoft Corporation. -# SPDX-License-Identifier: BSD-2-Clause-Patent -## - -[Defines] - INF_VERSION = 0x00010006 - BASE_NAME = BaseLibUnitTestApp - FILE_GUID = df5a6fed-8786-4a9d-9d02-eab39497b4a1 - MODULE_TYPE = UEFI_APPLICATION - VERSION_STRING = 1.0 - ENTRY_POINT = BaseLibUnitTestAppEntry - -# -# The following information is for reference only and not required by the build tools. -# -# VALID_ARCHITECTURES = IA32 X64 -# - -[Sources] - Base64UnitTest.c - -[Packages] - MdePkg/MdePkg.dec - -[LibraryClasses] - BaseLib - BaseMemoryLib - UefiApplicationEntryPoint - DebugLib - UnitTestLib +## @file +# Unit tests of Base64 conversion APIs in BaseLib that are run from UEFI Shell. +# +# Copyright (C) Microsoft Corporation. +# SPDX-License-Identifier: BSD-2-Clause-Patent +## + +[Defines] + INF_VERSION = 0x00010006 + BASE_NAME = BaseLibUnitTestApp + FILE_GUID = df5a6fed-8786-4a9d-9d02-eab39497b4a1 + MODULE_TYPE = UEFI_APPLICATION + VERSION_STRING = 1.0 + ENTRY_POINT = BaseLibUnitTestAppEntry + +# +# The following information is for reference only and not required by the build tools. +# +# VALID_ARCHITECTURES = IA32 X64 +# + +[Sources] + Base64UnitTest.c + +[Packages] + MdePkg/MdePkg.dec + +[LibraryClasses] + BaseLib + BaseMemoryLib + UefiApplicationEntryPoint + DebugLib + UnitTestLib diff --git a/MdePkg/Test/UnitTest/Library/BaseSafeIntLib/TestBaseSafeIntLibTestApp.inf b/MdePkg/Test/UnitTest/Library/BaseSafeIntLib/TestBaseSafeIntLibTestApp.inf index 6eff6b2efa..2b054cc964 100644 --- a/MdePkg/Test/UnitTest/Library/BaseSafeIntLib/TestBaseSafeIntLibTestApp.inf +++ b/MdePkg/Test/UnitTest/Library/BaseSafeIntLib/TestBaseSafeIntLibTestApp.inf @@ -1,42 +1,42 @@ -## @file -# UEFI Shell based Application that Unit Tests the SafeIntLib -# -# Copyright (c) Microsoft Corporation.
-# Copyright (c) 2019 - 2020, Intel Corporation. All rights reserved.
-# SPDX-License-Identifier: BSD-2-Clause-Patent -## - -[Defines] - INF_VERSION = 0x00010005 - BASE_NAME = TestBaseSafeIntLibTestApp - MODULE_UNI_FILE = TestBaseSafeIntLib.uni - FILE_GUID = 1F91B73E-5B6A-4317-80E8-E7C36A3C7AF4 - MODULE_TYPE = UEFI_APPLICATION - VERSION_STRING = 1.0 - ENTRY_POINT = DxeEntryPoint - -# -# The following information is for reference only and not required by the build tools. -# -# VALID_ARCHITECTURES = IA32 X64 -# - -[Sources] - TestBaseSafeIntLib.c - TestBaseSafeIntLib.h - -[Sources.Ia32, Sources.ARM] - SafeIntLibUintnIntnUnitTests32.c - -[Sources.X64, Sources.AARCH64] - SafeIntLibUintnIntnUnitTests64.c - -[Packages] - MdePkg/MdePkg.dec - -[LibraryClasses] - UefiApplicationEntryPoint - BaseLib - DebugLib - SafeIntLib - UnitTestLib +## @file +# UEFI Shell based Application that Unit Tests the SafeIntLib +# +# Copyright (c) Microsoft Corporation.
+# Copyright (c) 2019 - 2020, Intel Corporation. All rights reserved.
+# SPDX-License-Identifier: BSD-2-Clause-Patent +## + +[Defines] + INF_VERSION = 0x00010005 + BASE_NAME = TestBaseSafeIntLibTestApp + MODULE_UNI_FILE = TestBaseSafeIntLib.uni + FILE_GUID = 1F91B73E-5B6A-4317-80E8-E7C36A3C7AF4 + MODULE_TYPE = UEFI_APPLICATION + VERSION_STRING = 1.0 + ENTRY_POINT = DxeEntryPoint + +# +# The following information is for reference only and not required by the build tools. +# +# VALID_ARCHITECTURES = IA32 X64 +# + +[Sources] + TestBaseSafeIntLib.c + TestBaseSafeIntLib.h + +[Sources.Ia32, Sources.ARM] + SafeIntLibUintnIntnUnitTests32.c + +[Sources.X64, Sources.AARCH64] + SafeIntLibUintnIntnUnitTests64.c + +[Packages] + MdePkg/MdePkg.dec + +[LibraryClasses] + UefiApplicationEntryPoint + BaseLib + DebugLib + SafeIntLib + UnitTestLib diff --git a/NetworkPkg/SharedNetworking/Dhcp6Dxe.DEBUG.inf b/NetworkPkg/SharedNetworking/Dhcp6Dxe.DEBUG.inf index b5a09b9ec5..b7da2fc83f 100644 --- a/NetworkPkg/SharedNetworking/Dhcp6Dxe.DEBUG.inf +++ b/NetworkPkg/SharedNetworking/Dhcp6Dxe.DEBUG.inf @@ -1,65 +1,65 @@ -## @file -# Client-side DHCPv6 services. -# -# This driver produces EFI DHCPv6 Protocol which is used to get IPv6 addresses -# and other configuration parameters from DHCPv6 servers. -# -# (C) Copyright 2015 Hewlett-Packard Development Company, L.P.
-# Copyright (c) 2009 - 2018, Intel Corporation. All rights reserved.
-# -# This program and the accompanying materials -# are licensed and made available under the terms and conditions of the BSD License -# which accompanies this distribution. The full text of the license may be found at -# http://opensource.org/licenses/bsd-license.php. -# -# THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS, -# WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED. -# -## - -[Defines] - INF_VERSION = 0x0001001B - BASE_NAME = SharedDhcp6DxeDebug - FILE_GUID = 894D279B-A37B-42C1-A5AA-72F57367039C - MODULE_TYPE = UEFI_DRIVER - VERSION_STRING = 1.0 - ENTRY_POINT = Dhcp6DriverEntryPoint - UNLOAD_IMAGE = NetLibDefaultUnload - MODULE_UNI_FILE = Dhcp6Dxe.uni - -# -# VALID_ARCHITECTURES = IA32 X64# - - -[Binaries.X64] - PE32|Mu-SharedNetworking_extdep/DEBUG/X64/Dhcp6Dxe.efi|DEBUG - -[Binaries.IA32] - PE32|Mu-SharedNetworking_extdep/DEBUG/IA32/Dhcp6Dxe.efi|DEBUG - -[Binaries.AARCH64] - PE32|Mu-SharedNetworking_extdep/DEBUG/AARCH64/Dhcp6Dxe.efi|DEBUG - -[Packages] - MdePkg/MdePkg.dec - MdeModulePkg/MdeModulePkg.dec - NetworkPkg/NetworkPkg.dec - -[Protocols] - gEfiUdp6ServiceBindingProtocolGuid ## TO_START - gEfiUdp6ProtocolGuid ## TO_START - gEfiDhcp6ServiceBindingProtocolGuid ## BY_START - gEfiDhcp6ProtocolGuid ## BY_START - gEfiIp6ConfigProtocolGuid ## TO_START - -[Guids] - gZeroGuid ## SOMETIMES_CONSUMES ## GUID - -[Pcd] - gEfiNetworkPkgTokenSpaceGuid.PcdDhcp6UidType ## SOMETIMES_CONSUMES - -[UserExtensions.TianoCore."ExtraFiles"] - Dhcp6DxeExtra.uni - -[Depex] - TRUE +## @file +# Client-side DHCPv6 services. +# +# This driver produces EFI DHCPv6 Protocol which is used to get IPv6 addresses +# and other configuration parameters from DHCPv6 servers. +# +# (C) Copyright 2015 Hewlett-Packard Development Company, L.P.
+# Copyright (c) 2009 - 2018, Intel Corporation. All rights reserved.
+# +# This program and the accompanying materials +# are licensed and made available under the terms and conditions of the BSD License +# which accompanies this distribution. The full text of the license may be found at +# http://opensource.org/licenses/bsd-license.php. +# +# THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS, +# WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED. +# +## + +[Defines] + INF_VERSION = 0x0001001B + BASE_NAME = SharedDhcp6DxeDebug + FILE_GUID = 894D279B-A37B-42C1-A5AA-72F57367039C + MODULE_TYPE = UEFI_DRIVER + VERSION_STRING = 1.0 + ENTRY_POINT = Dhcp6DriverEntryPoint + UNLOAD_IMAGE = NetLibDefaultUnload + MODULE_UNI_FILE = Dhcp6Dxe.uni + +# +# VALID_ARCHITECTURES = IA32 X64# + + +[Binaries.X64] + PE32|Mu-SharedNetworking_extdep/DEBUG/X64/Dhcp6Dxe.efi|DEBUG + +[Binaries.IA32] + PE32|Mu-SharedNetworking_extdep/DEBUG/IA32/Dhcp6Dxe.efi|DEBUG + +[Binaries.AARCH64] + PE32|Mu-SharedNetworking_extdep/DEBUG/AARCH64/Dhcp6Dxe.efi|DEBUG + +[Packages] + MdePkg/MdePkg.dec + MdeModulePkg/MdeModulePkg.dec + NetworkPkg/NetworkPkg.dec + +[Protocols] + gEfiUdp6ServiceBindingProtocolGuid ## TO_START + gEfiUdp6ProtocolGuid ## TO_START + gEfiDhcp6ServiceBindingProtocolGuid ## BY_START + gEfiDhcp6ProtocolGuid ## BY_START + gEfiIp6ConfigProtocolGuid ## TO_START + +[Guids] + gZeroGuid ## SOMETIMES_CONSUMES ## GUID + +[Pcd] + gEfiNetworkPkgTokenSpaceGuid.PcdDhcp6UidType ## SOMETIMES_CONSUMES + +[UserExtensions.TianoCore."ExtraFiles"] + Dhcp6DxeExtra.uni + +[Depex] + TRUE diff --git a/NetworkPkg/SharedNetworking/Dhcp6Dxe.RELEASE.inf b/NetworkPkg/SharedNetworking/Dhcp6Dxe.RELEASE.inf index 7ac1cfda4f..3371603478 100644 --- a/NetworkPkg/SharedNetworking/Dhcp6Dxe.RELEASE.inf +++ b/NetworkPkg/SharedNetworking/Dhcp6Dxe.RELEASE.inf @@ -1,65 +1,65 @@ -## @file -# Client-side DHCPv6 services. -# -# This driver produces EFI DHCPv6 Protocol which is used to get IPv6 addresses -# and other configuration parameters from DHCPv6 servers. -# -# (C) Copyright 2015 Hewlett-Packard Development Company, L.P.
-# Copyright (c) 2009 - 2018, Intel Corporation. All rights reserved.
-# -# This program and the accompanying materials -# are licensed and made available under the terms and conditions of the BSD License -# which accompanies this distribution. The full text of the license may be found at -# http://opensource.org/licenses/bsd-license.php. -# -# THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS, -# WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED. -# -## - -[Defines] - INF_VERSION = 0x0001001B - BASE_NAME = SharedDhcp6DxeRelease - FILE_GUID = FDD67628-D08F-4DDE-98AC-CCF15A979945 - MODULE_TYPE = UEFI_DRIVER - VERSION_STRING = 1.0 - ENTRY_POINT = Dhcp6DriverEntryPoint - UNLOAD_IMAGE = NetLibDefaultUnload - MODULE_UNI_FILE = Dhcp6Dxe.uni - -# -# VALID_ARCHITECTURES = IA32 X64# - - -[Binaries.X64] - PE32|Mu-SharedNetworking_extdep/RELEASE/X64/Dhcp6Dxe.efi|RELEASE - -[Binaries.IA32] - PE32|Mu-SharedNetworking_extdep/RELEASE/IA32/Dhcp6Dxe.efi|RELEASE - -[Binaries.AARCH64] - PE32|Mu-SharedNetworking_extdep/RELEASE/AARCH64/Dhcp6Dxe.efi|RELEASE - -[Packages] - MdePkg/MdePkg.dec - MdeModulePkg/MdeModulePkg.dec - NetworkPkg/NetworkPkg.dec - -[Protocols] - gEfiUdp6ServiceBindingProtocolGuid ## TO_START - gEfiUdp6ProtocolGuid ## TO_START - gEfiDhcp6ServiceBindingProtocolGuid ## BY_START - gEfiDhcp6ProtocolGuid ## BY_START - gEfiIp6ConfigProtocolGuid ## TO_START - -[Guids] - gZeroGuid ## SOMETIMES_CONSUMES ## GUID - -[Pcd] - gEfiNetworkPkgTokenSpaceGuid.PcdDhcp6UidType ## SOMETIMES_CONSUMES - -[UserExtensions.TianoCore."ExtraFiles"] - Dhcp6DxeExtra.uni - -[Depex] - TRUE +## @file +# Client-side DHCPv6 services. +# +# This driver produces EFI DHCPv6 Protocol which is used to get IPv6 addresses +# and other configuration parameters from DHCPv6 servers. +# +# (C) Copyright 2015 Hewlett-Packard Development Company, L.P.
+# Copyright (c) 2009 - 2018, Intel Corporation. All rights reserved.
+# +# This program and the accompanying materials +# are licensed and made available under the terms and conditions of the BSD License +# which accompanies this distribution. The full text of the license may be found at +# http://opensource.org/licenses/bsd-license.php. +# +# THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS, +# WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED. +# +## + +[Defines] + INF_VERSION = 0x0001001B + BASE_NAME = SharedDhcp6DxeRelease + FILE_GUID = FDD67628-D08F-4DDE-98AC-CCF15A979945 + MODULE_TYPE = UEFI_DRIVER + VERSION_STRING = 1.0 + ENTRY_POINT = Dhcp6DriverEntryPoint + UNLOAD_IMAGE = NetLibDefaultUnload + MODULE_UNI_FILE = Dhcp6Dxe.uni + +# +# VALID_ARCHITECTURES = IA32 X64# + + +[Binaries.X64] + PE32|Mu-SharedNetworking_extdep/RELEASE/X64/Dhcp6Dxe.efi|RELEASE + +[Binaries.IA32] + PE32|Mu-SharedNetworking_extdep/RELEASE/IA32/Dhcp6Dxe.efi|RELEASE + +[Binaries.AARCH64] + PE32|Mu-SharedNetworking_extdep/RELEASE/AARCH64/Dhcp6Dxe.efi|RELEASE + +[Packages] + MdePkg/MdePkg.dec + MdeModulePkg/MdeModulePkg.dec + NetworkPkg/NetworkPkg.dec + +[Protocols] + gEfiUdp6ServiceBindingProtocolGuid ## TO_START + gEfiUdp6ProtocolGuid ## TO_START + gEfiDhcp6ServiceBindingProtocolGuid ## BY_START + gEfiDhcp6ProtocolGuid ## BY_START + gEfiIp6ConfigProtocolGuid ## TO_START + +[Guids] + gZeroGuid ## SOMETIMES_CONSUMES ## GUID + +[Pcd] + gEfiNetworkPkgTokenSpaceGuid.PcdDhcp6UidType ## SOMETIMES_CONSUMES + +[UserExtensions.TianoCore."ExtraFiles"] + Dhcp6DxeExtra.uni + +[Depex] + TRUE diff --git a/NetworkPkg/SharedNetworking/DnsDxe.DEBUG.inf b/NetworkPkg/SharedNetworking/DnsDxe.DEBUG.inf index 04a5b1acee..13dfe11540 100644 --- a/NetworkPkg/SharedNetworking/DnsDxe.DEBUG.inf +++ b/NetworkPkg/SharedNetworking/DnsDxe.DEBUG.inf @@ -1,65 +1,65 @@ -## @file -# Implementation of EFI_DNS4_PROTOCOL and EFI_DNS6_PROTOCOL interfaces. -# -# Copyright (c) 2015 - 2018, Intel Corporation. All rights reserved.
-# -# This program and the accompanying materials -# are licensed and made available under the terms and conditions of the BSD License -# which accompanies this distribution. The full text of the license may be found at -# http://opensource.org/licenses/bsd-license.php -# -# THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS, -# WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED. -# -# -## - -[Defines] - INF_VERSION = 0x0001001B - BASE_NAME = SharedDnsDxeDebug - FILE_GUID = 5C25C9E0-2391-43AF-9BDF-28118027F20B - MODULE_TYPE = UEFI_DRIVER - VERSION_STRING = 1.0 - ENTRY_POINT = DnsDriverEntryPoint - UNLOAD_IMAGE = DnsUnload - -# -# VALID_ARCHITECTURES = IA32 X64# - - -[Binaries.X64] - PE32|Mu-SharedNetworking_extdep/DEBUG/X64/DnsDxe.efi|DEBUG - -[Binaries.IA32] - PE32|Mu-SharedNetworking_extdep/DEBUG/IA32/DnsDxe.efi|DEBUG - -[Binaries.AARCH64] - PE32|Mu-SharedNetworking_extdep/DEBUG/AARCH64/DnsDxe.efi|DEBUG - -[Packages] - MdePkg/MdePkg.dec - MdeModulePkg/MdeModulePkg.dec - -[Protocols] - gEfiDns4ServiceBindingProtocolGuid ## BY_START - gEfiDns4ProtocolGuid ## BY_START - gEfiUdp4ServiceBindingProtocolGuid ## TO_START - gEfiUdp4ProtocolGuid ## TO_START - gEfiDhcp4ServiceBindingProtocolGuid ## SOMETIMES_CONSUMES - gEfiDhcp4ProtocolGuid ## SOMETIMES_CONSUMES - gEfiIp4Config2ProtocolGuid ## SOMETIMES_CONSUMES - gEfiManagedNetworkServiceBindingProtocolGuid ## SOMETIMES_CONSUMES - gEfiManagedNetworkProtocolGuid ## SOMETIMES_CONSUMES - - gEfiDns6ServiceBindingProtocolGuid ## BY_START - gEfiDns6ProtocolGuid ## BY_START - gEfiUdp6ServiceBindingProtocolGuid ## TO_START - gEfiUdp6ProtocolGuid ## TO_START - gEfiDhcp6ServiceBindingProtocolGuid ## SOMETIMES_CONSUMES - gEfiDhcp6ProtocolGuid ## SOMETIMES_CONSUMES - -[UserExtensions.TianoCore."ExtraFiles"] - DnsDxeExtra.uni - -[Depex] - TRUE +## @file +# Implementation of EFI_DNS4_PROTOCOL and EFI_DNS6_PROTOCOL interfaces. +# +# Copyright (c) 2015 - 2018, Intel Corporation. All rights reserved.
+# +# This program and the accompanying materials +# are licensed and made available under the terms and conditions of the BSD License +# which accompanies this distribution. The full text of the license may be found at +# http://opensource.org/licenses/bsd-license.php +# +# THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS, +# WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED. +# +# +## + +[Defines] + INF_VERSION = 0x0001001B + BASE_NAME = SharedDnsDxeDebug + FILE_GUID = 5C25C9E0-2391-43AF-9BDF-28118027F20B + MODULE_TYPE = UEFI_DRIVER + VERSION_STRING = 1.0 + ENTRY_POINT = DnsDriverEntryPoint + UNLOAD_IMAGE = DnsUnload + +# +# VALID_ARCHITECTURES = IA32 X64# + + +[Binaries.X64] + PE32|Mu-SharedNetworking_extdep/DEBUG/X64/DnsDxe.efi|DEBUG + +[Binaries.IA32] + PE32|Mu-SharedNetworking_extdep/DEBUG/IA32/DnsDxe.efi|DEBUG + +[Binaries.AARCH64] + PE32|Mu-SharedNetworking_extdep/DEBUG/AARCH64/DnsDxe.efi|DEBUG + +[Packages] + MdePkg/MdePkg.dec + MdeModulePkg/MdeModulePkg.dec + +[Protocols] + gEfiDns4ServiceBindingProtocolGuid ## BY_START + gEfiDns4ProtocolGuid ## BY_START + gEfiUdp4ServiceBindingProtocolGuid ## TO_START + gEfiUdp4ProtocolGuid ## TO_START + gEfiDhcp4ServiceBindingProtocolGuid ## SOMETIMES_CONSUMES + gEfiDhcp4ProtocolGuid ## SOMETIMES_CONSUMES + gEfiIp4Config2ProtocolGuid ## SOMETIMES_CONSUMES + gEfiManagedNetworkServiceBindingProtocolGuid ## SOMETIMES_CONSUMES + gEfiManagedNetworkProtocolGuid ## SOMETIMES_CONSUMES + + gEfiDns6ServiceBindingProtocolGuid ## BY_START + gEfiDns6ProtocolGuid ## BY_START + gEfiUdp6ServiceBindingProtocolGuid ## TO_START + gEfiUdp6ProtocolGuid ## TO_START + gEfiDhcp6ServiceBindingProtocolGuid ## SOMETIMES_CONSUMES + gEfiDhcp6ProtocolGuid ## SOMETIMES_CONSUMES + +[UserExtensions.TianoCore."ExtraFiles"] + DnsDxeExtra.uni + +[Depex] + TRUE diff --git a/NetworkPkg/SharedNetworking/DnsDxe.RELEASE.inf b/NetworkPkg/SharedNetworking/DnsDxe.RELEASE.inf index 5916c27877..6c50d4762e 100644 --- a/NetworkPkg/SharedNetworking/DnsDxe.RELEASE.inf +++ b/NetworkPkg/SharedNetworking/DnsDxe.RELEASE.inf @@ -1,63 +1,63 @@ -## @file -# Implementation of EFI_DNS4_PROTOCOL and EFI_DNS6_PROTOCOL interfaces. -# -# Copyright (c) 2015 - 2018, Intel Corporation. All rights reserved.
-# -# This program and the accompanying materials -# are licensed and made available under the terms and conditions of the BSD License -# which accompanies this distribution. The full text of the license may be found at -# http://opensource.org/licenses/bsd-license.php -# -# THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS, -# WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED. -# -# -## - -[Defines] - INF_VERSION = 0x0001001B - BASE_NAME = SharedDnsDxeRelease - FILE_GUID = 17811353-D084-4F83-A4E1-443F3139EAA7 - MODULE_TYPE = UEFI_DRIVER - VERSION_STRING = 1.0 - ENTRY_POINT = DnsDriverEntryPoint - UNLOAD_IMAGE = DnsUnload - MODULE_UNI_FILE = DnsDxe.uni - -# -# VALID_ARCHITECTURES = IA32 X64# - - -[Binaries.X64] - PE32|Mu-SharedNetworking_extdep/RELEASE/X64/DnsDxe.efi|RELEASE - -[Binaries.IA32] - PE32|Mu-SharedNetworking_extdep/RELEASE/IA32/DnsDxe.efi|RELEASE - -[Binaries.AARCH64] - PE32|Mu-SharedNetworking_extdep/RELEASE/AARCH64/DnsDxe.efi|RELEASE - -[Packages] - MdePkg/MdePkg.dec - MdeModulePkg/MdeModulePkg.dec - -[Protocols] - gEfiDns4ServiceBindingProtocolGuid ## BY_START - gEfiDns4ProtocolGuid ## BY_START - gEfiUdp4ServiceBindingProtocolGuid ## TO_START - gEfiUdp4ProtocolGuid ## TO_START - gEfiDhcp4ServiceBindingProtocolGuid ## SOMETIMES_CONSUMES - gEfiDhcp4ProtocolGuid ## SOMETIMES_CONSUMES - gEfiIp4Config2ProtocolGuid ## SOMETIMES_CONSUMES - gEfiManagedNetworkServiceBindingProtocolGuid ## SOMETIMES_CONSUMES - gEfiManagedNetworkProtocolGuid ## SOMETIMES_CONSUMES - - gEfiDns6ServiceBindingProtocolGuid ## BY_START - gEfiDns6ProtocolGuid ## BY_START - gEfiUdp6ServiceBindingProtocolGuid ## TO_START - gEfiUdp6ProtocolGuid ## TO_START - gEfiDhcp6ServiceBindingProtocolGuid ## SOMETIMES_CONSUMES - gEfiDhcp6ProtocolGuid ## SOMETIMES_CONSUMES - -[UserExtensions.TianoCore."ExtraFiles"] - DnsDxeExtra.uni +## @file +# Implementation of EFI_DNS4_PROTOCOL and EFI_DNS6_PROTOCOL interfaces. +# +# Copyright (c) 2015 - 2018, Intel Corporation. All rights reserved.
+# +# This program and the accompanying materials +# are licensed and made available under the terms and conditions of the BSD License +# which accompanies this distribution. The full text of the license may be found at +# http://opensource.org/licenses/bsd-license.php +# +# THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS, +# WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED. +# +# +## + +[Defines] + INF_VERSION = 0x0001001B + BASE_NAME = SharedDnsDxeRelease + FILE_GUID = 17811353-D084-4F83-A4E1-443F3139EAA7 + MODULE_TYPE = UEFI_DRIVER + VERSION_STRING = 1.0 + ENTRY_POINT = DnsDriverEntryPoint + UNLOAD_IMAGE = DnsUnload + MODULE_UNI_FILE = DnsDxe.uni + +# +# VALID_ARCHITECTURES = IA32 X64# + + +[Binaries.X64] + PE32|Mu-SharedNetworking_extdep/RELEASE/X64/DnsDxe.efi|RELEASE + +[Binaries.IA32] + PE32|Mu-SharedNetworking_extdep/RELEASE/IA32/DnsDxe.efi|RELEASE + +[Binaries.AARCH64] + PE32|Mu-SharedNetworking_extdep/RELEASE/AARCH64/DnsDxe.efi|RELEASE + +[Packages] + MdePkg/MdePkg.dec + MdeModulePkg/MdeModulePkg.dec + +[Protocols] + gEfiDns4ServiceBindingProtocolGuid ## BY_START + gEfiDns4ProtocolGuid ## BY_START + gEfiUdp4ServiceBindingProtocolGuid ## TO_START + gEfiUdp4ProtocolGuid ## TO_START + gEfiDhcp4ServiceBindingProtocolGuid ## SOMETIMES_CONSUMES + gEfiDhcp4ProtocolGuid ## SOMETIMES_CONSUMES + gEfiIp4Config2ProtocolGuid ## SOMETIMES_CONSUMES + gEfiManagedNetworkServiceBindingProtocolGuid ## SOMETIMES_CONSUMES + gEfiManagedNetworkProtocolGuid ## SOMETIMES_CONSUMES + + gEfiDns6ServiceBindingProtocolGuid ## BY_START + gEfiDns6ProtocolGuid ## BY_START + gEfiUdp6ServiceBindingProtocolGuid ## TO_START + gEfiUdp6ProtocolGuid ## TO_START + gEfiDhcp6ServiceBindingProtocolGuid ## SOMETIMES_CONSUMES + gEfiDhcp6ProtocolGuid ## SOMETIMES_CONSUMES + +[UserExtensions.TianoCore."ExtraFiles"] + DnsDxeExtra.uni diff --git a/NetworkPkg/SharedNetworking/DriverBuilder.py b/NetworkPkg/SharedNetworking/DriverBuilder.py index e50138d914..0028d98ea2 100644 --- a/NetworkPkg/SharedNetworking/DriverBuilder.py +++ b/NetworkPkg/SharedNetworking/DriverBuilder.py @@ -1,159 +1,159 @@ -# @file Edk2BinaryBuild.py -# This module contains code that supports building of binary files -# This is the main entry for the build and test process of binary builds -## -# Copyright (c) Microsoft Corporation -# -# SPDX-License-Identifier: BSD-2-Clause-Patent -## -import os -import sys -import logging -from edk2toolext.environment import plugin_manager -from edk2toolext.environment.plugintypes.uefi_helper_plugin import HelperFunctions -from edk2toolext.edk2_invocable import Edk2Invocable -from edk2toolext.environment import self_describing_environment -from edk2toolext.environment import shell_environment -from edk2toolext.environment.uefi_build import UefiBuilder -from edk2toolext import edk2_logging -# import pkg_resources -import DriverBuilder # this is a little weird - - -class BinaryBuildSettingsManager(): - ''' Platform settings will be accessed through this implementation. ''' - - def GetActiveScopes(self): - ''' get scope ''' - raise NotImplementedError() - - def GetWorkspaceRoot(self): - ''' get WorkspacePath ''' - raise NotImplementedError() - - def GetPackagesPath(self): - pass - - def GetConfigurations(self): - ''' - Gets the next configuration of this run - This is a generator pattern - use yield - ''' - raise NotImplementedError() - - def PreFirstBuildHook(self): - ''' Called after the before the first build ''' - return 0 - - def PostFinalBuildHook(self, ret): - ''' Called after the final build with the summed return code ''' - return 0 - - def PostBuildHook(self, ret): - ''' Called after each build with the return code ''' - return 0 - - def PreBuildHook(self): - ''' Called before each build ''' - return 0 - - def GetName(self): - ''' Get the name of the repo, platform, or product being build by CI ''' - raise NotImplementedError() - - def AddCommandLineOptions(self, parserObj): - ''' Implement in subclass to add command line options to the argparser ''' - pass - - def RetrieveCommandLineOptions(self, args): - ''' Implement in subclass to retrieve command line options from the argparser ''' - pass - - -class Edk2BinaryBuild(Edk2Invocable): - def GetLoggingLevel(self, loggerType): - ''' Get the logging level for a given type - base == lowest logging level supported - con == Screen logging - txt == plain text file logging - md == markdown file logging - ''' - if(loggerType == "con") and not self.Verbose: - return logging.WARNING - return logging.DEBUG - - def AddCommandLineOptions(self, parser): - pass - - def RetrieveCommandLineOptions(self, args): - ''' Retrieve command line options from the argparser ''' - pass - - def GetSettingsClass(self): - return BinaryBuildSettingsManager - - def GetLoggingFileName(self, loggerType): - return "BINARY_BUILDLOG" - - def Go(self): - ret = 0 - env = shell_environment.GetBuildVars() - env.SetValue("PRODUCT_NAME", - self.PlatformSettings.GetName(), "Platform Hardcoded") - env.SetValue("BLD_*_BUILDID_STRING", "201905", "Current Version") - env.SetValue("BUILDREPORTING", "TRUE", "Platform Hardcoded") - env.SetValue("BUILDREPORT_TYPES", - 'PCD DEPEX LIBRARY BUILD_FLAGS', "Platform Hardcoded") - - # make sure python_command is set - python_command = sys.executable - if " "in python_command: - python_command = '"' + python_command + '"' - shell_environment.GetEnvironment().set_shell_var("PYTHON_COMMAND", python_command) - - # Run pre build hook - ret += self.PlatformSettings.PreFirstBuildHook() - ws = self.GetWorkspaceRoot() - pp = self.PlatformSettings.GetModulePkgsPath() - # run each configuration - ret = 0 - try: - for config in self.PlatformSettings.GetConfigurations(): - pre_ret = self.PlatformSettings.PreBuildHook() # run pre build hook - if pre_ret != 0: - ret = pre_ret - raise RuntimeError("We failed in prebuild hook") - edk2_logging.log_progress(f"--Running next configuration--") - logging.info(config) - shell_environment.CheckpointBuildVars() # checkpoint our config - env = shell_environment.GetBuildVars() - # go through the config and apply to environement - for key in config: - env.SetValue(key, config[key], "provided by configuration") - # make sure to set this after in case the config did - env.SetValue("TOOL_CHAIN_TAG", "VS2017", "provided by builder") - platformBuilder = UefiBuilder() # create our builder - build_ret = platformBuilder.Go(ws, pp, self.helper, self.plugin_manager) - # we always want to run the post build hook - post_ret = self.PlatformSettings.PostBuildHook(ret) - if build_ret != 0: - ret = build_ret - raise RuntimeError("We failed in build") - if post_ret != 0: - ret = post_ret - raise RuntimeError("We failed in postbuild hook") - shell_environment.RevertBuildVars() - except RuntimeError: - pass - finally: - # make sure to do our final build hook - self.PlatformSettings.PostFinalBuildHook(ret) - return ret - - -def main(): - Edk2BinaryBuild().Invoke() - - -if __name__ == "__main__": - DriverBuilder.main() # otherwise we're in __main__ context +# @file Edk2BinaryBuild.py +# This module contains code that supports building of binary files +# This is the main entry for the build and test process of binary builds +## +# Copyright (c) Microsoft Corporation +# +# SPDX-License-Identifier: BSD-2-Clause-Patent +## +import os +import sys +import logging +from edk2toolext.environment import plugin_manager +from edk2toolext.environment.plugintypes.uefi_helper_plugin import HelperFunctions +from edk2toolext.edk2_invocable import Edk2Invocable +from edk2toolext.environment import self_describing_environment +from edk2toolext.environment import shell_environment +from edk2toolext.environment.uefi_build import UefiBuilder +from edk2toolext import edk2_logging +# import pkg_resources +import DriverBuilder # this is a little weird + + +class BinaryBuildSettingsManager(): + ''' Platform settings will be accessed through this implementation. ''' + + def GetActiveScopes(self): + ''' get scope ''' + raise NotImplementedError() + + def GetWorkspaceRoot(self): + ''' get WorkspacePath ''' + raise NotImplementedError() + + def GetPackagesPath(self): + pass + + def GetConfigurations(self): + ''' + Gets the next configuration of this run + This is a generator pattern - use yield + ''' + raise NotImplementedError() + + def PreFirstBuildHook(self): + ''' Called after the before the first build ''' + return 0 + + def PostFinalBuildHook(self, ret): + ''' Called after the final build with the summed return code ''' + return 0 + + def PostBuildHook(self, ret): + ''' Called after each build with the return code ''' + return 0 + + def PreBuildHook(self): + ''' Called before each build ''' + return 0 + + def GetName(self): + ''' Get the name of the repo, platform, or product being build by CI ''' + raise NotImplementedError() + + def AddCommandLineOptions(self, parserObj): + ''' Implement in subclass to add command line options to the argparser ''' + pass + + def RetrieveCommandLineOptions(self, args): + ''' Implement in subclass to retrieve command line options from the argparser ''' + pass + + +class Edk2BinaryBuild(Edk2Invocable): + def GetLoggingLevel(self, loggerType): + ''' Get the logging level for a given type + base == lowest logging level supported + con == Screen logging + txt == plain text file logging + md == markdown file logging + ''' + if(loggerType == "con") and not self.Verbose: + return logging.WARNING + return logging.DEBUG + + def AddCommandLineOptions(self, parser): + pass + + def RetrieveCommandLineOptions(self, args): + ''' Retrieve command line options from the argparser ''' + pass + + def GetSettingsClass(self): + return BinaryBuildSettingsManager + + def GetLoggingFileName(self, loggerType): + return "BINARY_BUILDLOG" + + def Go(self): + ret = 0 + env = shell_environment.GetBuildVars() + env.SetValue("PRODUCT_NAME", + self.PlatformSettings.GetName(), "Platform Hardcoded") + env.SetValue("BLD_*_BUILDID_STRING", "201905", "Current Version") + env.SetValue("BUILDREPORTING", "TRUE", "Platform Hardcoded") + env.SetValue("BUILDREPORT_TYPES", + 'PCD DEPEX LIBRARY BUILD_FLAGS', "Platform Hardcoded") + + # make sure python_command is set + python_command = sys.executable + if " "in python_command: + python_command = '"' + python_command + '"' + shell_environment.GetEnvironment().set_shell_var("PYTHON_COMMAND", python_command) + + # Run pre build hook + ret += self.PlatformSettings.PreFirstBuildHook() + ws = self.GetWorkspaceRoot() + pp = self.PlatformSettings.GetModulePkgsPath() + # run each configuration + ret = 0 + try: + for config in self.PlatformSettings.GetConfigurations(): + pre_ret = self.PlatformSettings.PreBuildHook() # run pre build hook + if pre_ret != 0: + ret = pre_ret + raise RuntimeError("We failed in prebuild hook") + edk2_logging.log_progress(f"--Running next configuration--") + logging.info(config) + shell_environment.CheckpointBuildVars() # checkpoint our config + env = shell_environment.GetBuildVars() + # go through the config and apply to environement + for key in config: + env.SetValue(key, config[key], "provided by configuration") + # make sure to set this after in case the config did + env.SetValue("TOOL_CHAIN_TAG", "VS2017", "provided by builder") + platformBuilder = UefiBuilder() # create our builder + build_ret = platformBuilder.Go(ws, pp, self.helper, self.plugin_manager) + # we always want to run the post build hook + post_ret = self.PlatformSettings.PostBuildHook(ret) + if build_ret != 0: + ret = build_ret + raise RuntimeError("We failed in build") + if post_ret != 0: + ret = post_ret + raise RuntimeError("We failed in postbuild hook") + shell_environment.RevertBuildVars() + except RuntimeError: + pass + finally: + # make sure to do our final build hook + self.PlatformSettings.PostFinalBuildHook(ret) + return ret + + +def main(): + Edk2BinaryBuild().Invoke() + + +if __name__ == "__main__": + DriverBuilder.main() # otherwise we're in __main__ context diff --git a/NetworkPkg/SharedNetworking/HttpBootDxe.DEBUG.inf b/NetworkPkg/SharedNetworking/HttpBootDxe.DEBUG.inf index 60bf002a9e..e817a54cd7 100644 --- a/NetworkPkg/SharedNetworking/HttpBootDxe.DEBUG.inf +++ b/NetworkPkg/SharedNetworking/HttpBootDxe.DEBUG.inf @@ -1,81 +1,81 @@ -## @file -# This modules produce the Load File Protocol for UEFI HTTP boot. -# -# Copyright (c) 2015 - 2018, Intel Corporation. All rights reserved.
-# This program and the accompanying materials -# are licensed and made available under the terms and conditions of the BSD License -# which accompanies this distribution. The full text of the license may be found at -# http://opensource.org/licenses/bsd-license.php -# -# THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS, -# WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED. -# -## - -[Defines] - INF_VERSION = 0x0001001B - BASE_NAME = SharedHttpBootDxeDebug - FILE_GUID = 57EFEA0B-3D6F-494E-A16F-BF19F4D94C0F - MODULE_TYPE = UEFI_DRIVER - VERSION_STRING = 1.0 - ENTRY_POINT = HttpBootDxeDriverEntryPoint - UNLOAD_IMAGE = NetLibDefaultUnload - MODULE_UNI_FILE = HttpBootDxe.uni - -# -# VALID_ARCHITECTURES = IA32 X64# - - -[Binaries.X64] - PE32|Mu-SharedNetworking_extdep/DEBUG/X64/HttpBootDxe.efi|DEBUG - -[Binaries.IA32] - PE32|Mu-SharedNetworking_extdep/DEBUG/IA32/HttpBootDxe.efi|DEBUG - -[Binaries.AARCH64] - PE32|Mu-SharedNetworking_extdep/DEBUG/AARCH64/HttpBootDxe.efi|DEBUG - -[Packages] - MdePkg/MdePkg.dec - MdeModulePkg/MdeModulePkg.dec - NetworkPkg/NetworkPkg.dec - -[Protocols] - ## TO_START - ## BY_START - gEfiDevicePathProtocolGuid - - gEfiLoadFileProtocolGuid ## BY_START - gEfiHttpServiceBindingProtocolGuid ## CONSUMES - gEfiHttpProtocolGuid ## CONSUMES - gEfiDhcp4ServiceBindingProtocolGuid ## TO_START - gEfiDhcp4ProtocolGuid ## TO_START - gEfiIp4Config2ProtocolGuid ## TO_START - gEfiDhcp6ServiceBindingProtocolGuid ## TO_START - gEfiDhcp6ProtocolGuid ## TO_START - gEfiDns6ServiceBindingProtocolGuid ## SOMETIMES_CONSUMES - gEfiDns6ProtocolGuid ## SOMETIMES_CONSUMES - gEfiIp6ServiceBindingProtocolGuid ## TO_START - gEfiIp6ProtocolGuid ## TO_START - gEfiIp6ConfigProtocolGuid ## TO_START - gEfiNetworkInterfaceIdentifierProtocolGuid_31 ## SOMETIMES_CONSUMES - gEfiRamDiskProtocolGuid ## SOMETIMES_CONSUMES - gEfiHiiConfigAccessProtocolGuid ## BY_START - gEfiHttpBootCallbackProtocolGuid ## SOMETIMES_PRODUCES - gEfiAdapterInformationProtocolGuid ## SOMETIMES_CONSUMES - -[Guids] - ## SOMETIMES_CONSUMES ## GUID # HiiIsConfigHdrMatch mHttpBootConfigStorageName - ## SOMETIMES_PRODUCES ## GUID # HiiConstructConfigHdr mHttpBootConfigStorageName - ## SOMETIMES_PRODUCES ## GUID # HiiGetBrowserData mHttpBootConfigStorageName - ## SOMETIMES_CONSUMES ## HII - gHttpBootConfigGuid - gEfiVirtualCdGuid ## SOMETIMES_CONSUMES ## GUID - gEfiVirtualDiskGuid ## SOMETIMES_CONSUMES ## GUID - gEfiAdapterInfoUndiIpv6SupportGuid ## SOMETIMES_CONSUMES ## GUID - -[Pcd] - gEfiNetworkPkgTokenSpaceGuid.PcdAllowHttpConnections ## CONSUMES - -[Depex] - TRUE +## @file +# This modules produce the Load File Protocol for UEFI HTTP boot. +# +# Copyright (c) 2015 - 2018, Intel Corporation. All rights reserved.
+# This program and the accompanying materials +# are licensed and made available under the terms and conditions of the BSD License +# which accompanies this distribution. The full text of the license may be found at +# http://opensource.org/licenses/bsd-license.php +# +# THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS, +# WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED. +# +## + +[Defines] + INF_VERSION = 0x0001001B + BASE_NAME = SharedHttpBootDxeDebug + FILE_GUID = 57EFEA0B-3D6F-494E-A16F-BF19F4D94C0F + MODULE_TYPE = UEFI_DRIVER + VERSION_STRING = 1.0 + ENTRY_POINT = HttpBootDxeDriverEntryPoint + UNLOAD_IMAGE = NetLibDefaultUnload + MODULE_UNI_FILE = HttpBootDxe.uni + +# +# VALID_ARCHITECTURES = IA32 X64# + + +[Binaries.X64] + PE32|Mu-SharedNetworking_extdep/DEBUG/X64/HttpBootDxe.efi|DEBUG + +[Binaries.IA32] + PE32|Mu-SharedNetworking_extdep/DEBUG/IA32/HttpBootDxe.efi|DEBUG + +[Binaries.AARCH64] + PE32|Mu-SharedNetworking_extdep/DEBUG/AARCH64/HttpBootDxe.efi|DEBUG + +[Packages] + MdePkg/MdePkg.dec + MdeModulePkg/MdeModulePkg.dec + NetworkPkg/NetworkPkg.dec + +[Protocols] + ## TO_START + ## BY_START + gEfiDevicePathProtocolGuid + + gEfiLoadFileProtocolGuid ## BY_START + gEfiHttpServiceBindingProtocolGuid ## CONSUMES + gEfiHttpProtocolGuid ## CONSUMES + gEfiDhcp4ServiceBindingProtocolGuid ## TO_START + gEfiDhcp4ProtocolGuid ## TO_START + gEfiIp4Config2ProtocolGuid ## TO_START + gEfiDhcp6ServiceBindingProtocolGuid ## TO_START + gEfiDhcp6ProtocolGuid ## TO_START + gEfiDns6ServiceBindingProtocolGuid ## SOMETIMES_CONSUMES + gEfiDns6ProtocolGuid ## SOMETIMES_CONSUMES + gEfiIp6ServiceBindingProtocolGuid ## TO_START + gEfiIp6ProtocolGuid ## TO_START + gEfiIp6ConfigProtocolGuid ## TO_START + gEfiNetworkInterfaceIdentifierProtocolGuid_31 ## SOMETIMES_CONSUMES + gEfiRamDiskProtocolGuid ## SOMETIMES_CONSUMES + gEfiHiiConfigAccessProtocolGuid ## BY_START + gEfiHttpBootCallbackProtocolGuid ## SOMETIMES_PRODUCES + gEfiAdapterInformationProtocolGuid ## SOMETIMES_CONSUMES + +[Guids] + ## SOMETIMES_CONSUMES ## GUID # HiiIsConfigHdrMatch mHttpBootConfigStorageName + ## SOMETIMES_PRODUCES ## GUID # HiiConstructConfigHdr mHttpBootConfigStorageName + ## SOMETIMES_PRODUCES ## GUID # HiiGetBrowserData mHttpBootConfigStorageName + ## SOMETIMES_CONSUMES ## HII + gHttpBootConfigGuid + gEfiVirtualCdGuid ## SOMETIMES_CONSUMES ## GUID + gEfiVirtualDiskGuid ## SOMETIMES_CONSUMES ## GUID + gEfiAdapterInfoUndiIpv6SupportGuid ## SOMETIMES_CONSUMES ## GUID + +[Pcd] + gEfiNetworkPkgTokenSpaceGuid.PcdAllowHttpConnections ## CONSUMES + +[Depex] + TRUE diff --git a/NetworkPkg/SharedNetworking/HttpBootDxe.RELEASE.inf b/NetworkPkg/SharedNetworking/HttpBootDxe.RELEASE.inf index 416158ffea..fd5a15a11e 100644 --- a/NetworkPkg/SharedNetworking/HttpBootDxe.RELEASE.inf +++ b/NetworkPkg/SharedNetworking/HttpBootDxe.RELEASE.inf @@ -1,84 +1,84 @@ -## @file -# This modules produce the Load File Protocol for UEFI HTTP boot. -# -# Copyright (c) 2015 - 2018, Intel Corporation. All rights reserved.
-# This program and the accompanying materials -# are licensed and made available under the terms and conditions of the BSD License -# which accompanies this distribution. The full text of the license may be found at -# http://opensource.org/licenses/bsd-license.php -# -# THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS, -# WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED. -# -## - -[Defines] - INF_VERSION = 0x0001001B - BASE_NAME = SharedHttpBootDxeRelease - FILE_GUID = 3054B0D0-E163-4585-A1E9-642E72709FF0 - MODULE_TYPE = UEFI_DRIVER - VERSION_STRING = 1.0 - ENTRY_POINT = HttpBootDxeDriverEntryPoint - UNLOAD_IMAGE = NetLibDefaultUnload - MODULE_UNI_FILE = HttpBootDxe.uni - -# -# VALID_ARCHITECTURES = IA32 X64# - - -[Binaries.X64] - PE32|Mu-SharedNetworking_extdep/RELEASE/X64/HttpBootDxe.efi|RELEASE - -[Binaries.IA32] - PE32|Mu-SharedNetworking_extdep/RELEASE/IA32/HttpBootDxe.efi|RELEASE - -[Binaries.AARCH64] - PE32|Mu-SharedNetworking_extdep/RELEASE/AARCH64/HttpBootDxe.efi|RELEASE - -[Packages] - MdePkg/MdePkg.dec - MdeModulePkg/MdeModulePkg.dec - NetworkPkg/NetworkPkg.dec - -[Protocols] - ## TO_START - ## BY_START - gEfiDevicePathProtocolGuid - - gEfiLoadFileProtocolGuid ## BY_START - gEfiHttpServiceBindingProtocolGuid ## CONSUMES - gEfiHttpProtocolGuid ## CONSUMES - gEfiDhcp4ServiceBindingProtocolGuid ## TO_START - gEfiDhcp4ProtocolGuid ## TO_START - gEfiIp4Config2ProtocolGuid ## TO_START - gEfiDhcp6ServiceBindingProtocolGuid ## TO_START - gEfiDhcp6ProtocolGuid ## TO_START - gEfiDns6ServiceBindingProtocolGuid ## SOMETIMES_CONSUMES - gEfiDns6ProtocolGuid ## SOMETIMES_CONSUMES - gEfiIp6ServiceBindingProtocolGuid ## TO_START - gEfiIp6ProtocolGuid ## TO_START - gEfiIp6ConfigProtocolGuid ## TO_START - gEfiNetworkInterfaceIdentifierProtocolGuid_31 ## SOMETIMES_CONSUMES - gEfiRamDiskProtocolGuid ## SOMETIMES_CONSUMES - gEfiHiiConfigAccessProtocolGuid ## BY_START - gEfiHttpBootCallbackProtocolGuid ## SOMETIMES_PRODUCES - gEfiAdapterInformationProtocolGuid ## SOMETIMES_CONSUMES - -[Guids] - ## SOMETIMES_CONSUMES ## GUID # HiiIsConfigHdrMatch mHttpBootConfigStorageName - ## SOMETIMES_PRODUCES ## GUID # HiiConstructConfigHdr mHttpBootConfigStorageName - ## SOMETIMES_PRODUCES ## GUID # HiiGetBrowserData mHttpBootConfigStorageName - ## SOMETIMES_CONSUMES ## HII - gHttpBootConfigGuid - gEfiVirtualCdGuid ## SOMETIMES_CONSUMES ## GUID - gEfiVirtualDiskGuid ## SOMETIMES_CONSUMES ## GUID - gEfiAdapterInfoUndiIpv6SupportGuid ## SOMETIMES_CONSUMES ## GUID - -[Pcd] - gEfiNetworkPkgTokenSpaceGuid.PcdAllowHttpConnections ## CONSUMES - -[UserExtensions.TianoCore."ExtraFiles"] - HttpBootDxeExtra.uni - -[Depex] - TRUE +## @file +# This modules produce the Load File Protocol for UEFI HTTP boot. +# +# Copyright (c) 2015 - 2018, Intel Corporation. All rights reserved.
+# This program and the accompanying materials +# are licensed and made available under the terms and conditions of the BSD License +# which accompanies this distribution. The full text of the license may be found at +# http://opensource.org/licenses/bsd-license.php +# +# THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS, +# WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED. +# +## + +[Defines] + INF_VERSION = 0x0001001B + BASE_NAME = SharedHttpBootDxeRelease + FILE_GUID = 3054B0D0-E163-4585-A1E9-642E72709FF0 + MODULE_TYPE = UEFI_DRIVER + VERSION_STRING = 1.0 + ENTRY_POINT = HttpBootDxeDriverEntryPoint + UNLOAD_IMAGE = NetLibDefaultUnload + MODULE_UNI_FILE = HttpBootDxe.uni + +# +# VALID_ARCHITECTURES = IA32 X64# + + +[Binaries.X64] + PE32|Mu-SharedNetworking_extdep/RELEASE/X64/HttpBootDxe.efi|RELEASE + +[Binaries.IA32] + PE32|Mu-SharedNetworking_extdep/RELEASE/IA32/HttpBootDxe.efi|RELEASE + +[Binaries.AARCH64] + PE32|Mu-SharedNetworking_extdep/RELEASE/AARCH64/HttpBootDxe.efi|RELEASE + +[Packages] + MdePkg/MdePkg.dec + MdeModulePkg/MdeModulePkg.dec + NetworkPkg/NetworkPkg.dec + +[Protocols] + ## TO_START + ## BY_START + gEfiDevicePathProtocolGuid + + gEfiLoadFileProtocolGuid ## BY_START + gEfiHttpServiceBindingProtocolGuid ## CONSUMES + gEfiHttpProtocolGuid ## CONSUMES + gEfiDhcp4ServiceBindingProtocolGuid ## TO_START + gEfiDhcp4ProtocolGuid ## TO_START + gEfiIp4Config2ProtocolGuid ## TO_START + gEfiDhcp6ServiceBindingProtocolGuid ## TO_START + gEfiDhcp6ProtocolGuid ## TO_START + gEfiDns6ServiceBindingProtocolGuid ## SOMETIMES_CONSUMES + gEfiDns6ProtocolGuid ## SOMETIMES_CONSUMES + gEfiIp6ServiceBindingProtocolGuid ## TO_START + gEfiIp6ProtocolGuid ## TO_START + gEfiIp6ConfigProtocolGuid ## TO_START + gEfiNetworkInterfaceIdentifierProtocolGuid_31 ## SOMETIMES_CONSUMES + gEfiRamDiskProtocolGuid ## SOMETIMES_CONSUMES + gEfiHiiConfigAccessProtocolGuid ## BY_START + gEfiHttpBootCallbackProtocolGuid ## SOMETIMES_PRODUCES + gEfiAdapterInformationProtocolGuid ## SOMETIMES_CONSUMES + +[Guids] + ## SOMETIMES_CONSUMES ## GUID # HiiIsConfigHdrMatch mHttpBootConfigStorageName + ## SOMETIMES_PRODUCES ## GUID # HiiConstructConfigHdr mHttpBootConfigStorageName + ## SOMETIMES_PRODUCES ## GUID # HiiGetBrowserData mHttpBootConfigStorageName + ## SOMETIMES_CONSUMES ## HII + gHttpBootConfigGuid + gEfiVirtualCdGuid ## SOMETIMES_CONSUMES ## GUID + gEfiVirtualDiskGuid ## SOMETIMES_CONSUMES ## GUID + gEfiAdapterInfoUndiIpv6SupportGuid ## SOMETIMES_CONSUMES ## GUID + +[Pcd] + gEfiNetworkPkgTokenSpaceGuid.PcdAllowHttpConnections ## CONSUMES + +[UserExtensions.TianoCore."ExtraFiles"] + HttpBootDxeExtra.uni + +[Depex] + TRUE diff --git a/NetworkPkg/SharedNetworking/HttpUtilitiesDxe.DEBUG.inf b/NetworkPkg/SharedNetworking/HttpUtilitiesDxe.DEBUG.inf index aff040d2b9..4991ff8b7b 100644 --- a/NetworkPkg/SharedNetworking/HttpUtilitiesDxe.DEBUG.inf +++ b/NetworkPkg/SharedNetworking/HttpUtilitiesDxe.DEBUG.inf @@ -1,52 +1,52 @@ -## @file -# Implementation of EFI Http Utilities Protocol interfaces. -# -# Copyright (c) 2015, Intel Corporation. All rights reserved.
-# (C) Copyright 2016 Hewlett Packard Enterprise Development LP
-# -# This program and the accompanying materials -# are licensed and made available under the terms and conditions of the BSD License -# which accompanies this distribution. The full text of the license may be found at -# http://opensource.org/licenses/bsd-license.php. -# THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS, -# WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED. -# -# -## - - -[Defines] - INF_VERSION = 0x0001001B - BASE_NAME = SharedHttpUtilitiesDxeDebug - FILE_GUID = 74C271E0-9EA5-49E9-BE65-5D0030EDD819 - MODULE_TYPE = UEFI_DRIVER - VERSION_STRING = 1.0 - ENTRY_POINT = HttpUtilitiesDxeDriverEntryPoint - UNLOAD_IMAGE = HttpUtilitiesDxeUnload - MODULE_UNI_FILE = HttpUtilitiesDxe.uni - -# -# VALID_ARCHITECTURES = IA32 X64# - - -[Binaries.X64] - PE32|Mu-SharedNetworking_extdep/DEBUG/X64/HttpUtilitiesDxe.efi|DEBUG - -[Binaries.IA32] - PE32|Mu-SharedNetworking_extdep/DEBUG/IA32/HttpUtilitiesDxe.efi|DEBUG - -[Binaries.AARCH64] - PE32|Mu-SharedNetworking_extdep/DEBUG/AARCH64/HttpUtilitiesDxe.efi|DEBUG - -[Packages] - MdePkg/MdePkg.dec - MdeModulePkg/MdeModulePkg.dec - -[Protocols] - gEfiHttpUtilitiesProtocolGuid ## PRODUCES - -[UserExtensions.TianoCore."ExtraFiles"] - HttpUtilitiesDxeExtra.uni - -[Depex] - TRUE +## @file +# Implementation of EFI Http Utilities Protocol interfaces. +# +# Copyright (c) 2015, Intel Corporation. All rights reserved.
+# (C) Copyright 2016 Hewlett Packard Enterprise Development LP
+# +# This program and the accompanying materials +# are licensed and made available under the terms and conditions of the BSD License +# which accompanies this distribution. The full text of the license may be found at +# http://opensource.org/licenses/bsd-license.php. +# THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS, +# WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED. +# +# +## + + +[Defines] + INF_VERSION = 0x0001001B + BASE_NAME = SharedHttpUtilitiesDxeDebug + FILE_GUID = 74C271E0-9EA5-49E9-BE65-5D0030EDD819 + MODULE_TYPE = UEFI_DRIVER + VERSION_STRING = 1.0 + ENTRY_POINT = HttpUtilitiesDxeDriverEntryPoint + UNLOAD_IMAGE = HttpUtilitiesDxeUnload + MODULE_UNI_FILE = HttpUtilitiesDxe.uni + +# +# VALID_ARCHITECTURES = IA32 X64# + + +[Binaries.X64] + PE32|Mu-SharedNetworking_extdep/DEBUG/X64/HttpUtilitiesDxe.efi|DEBUG + +[Binaries.IA32] + PE32|Mu-SharedNetworking_extdep/DEBUG/IA32/HttpUtilitiesDxe.efi|DEBUG + +[Binaries.AARCH64] + PE32|Mu-SharedNetworking_extdep/DEBUG/AARCH64/HttpUtilitiesDxe.efi|DEBUG + +[Packages] + MdePkg/MdePkg.dec + MdeModulePkg/MdeModulePkg.dec + +[Protocols] + gEfiHttpUtilitiesProtocolGuid ## PRODUCES + +[UserExtensions.TianoCore."ExtraFiles"] + HttpUtilitiesDxeExtra.uni + +[Depex] + TRUE diff --git a/NetworkPkg/SharedNetworking/HttpUtilitiesDxe.RELEASE.inf b/NetworkPkg/SharedNetworking/HttpUtilitiesDxe.RELEASE.inf index 915bcf5466..d8066ea0ec 100644 --- a/NetworkPkg/SharedNetworking/HttpUtilitiesDxe.RELEASE.inf +++ b/NetworkPkg/SharedNetworking/HttpUtilitiesDxe.RELEASE.inf @@ -1,52 +1,52 @@ -## @file -# Implementation of EFI Http Utilities Protocol interfaces. -# -# Copyright (c) 2015, Intel Corporation. All rights reserved.
-# (C) Copyright 2016 Hewlett Packard Enterprise Development LP
-# -# This program and the accompanying materials -# are licensed and made available under the terms and conditions of the BSD License -# which accompanies this distribution. The full text of the license may be found at -# http://opensource.org/licenses/bsd-license.php. -# THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS, -# WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED. -# -# -## - - -[Defines] - INF_VERSION = 0x0001001B - BASE_NAME = SharedHttpUtilitiesDxeRelease - FILE_GUID = 1792C670-F707-4089-A5E6-47191829DFAE - MODULE_TYPE = UEFI_DRIVER - VERSION_STRING = 1.0 - ENTRY_POINT = HttpUtilitiesDxeDriverEntryPoint - UNLOAD_IMAGE = HttpUtilitiesDxeUnload - MODULE_UNI_FILE = HttpUtilitiesDxe.uni - -# -# VALID_ARCHITECTURES = IA32 X64# - - -[Binaries.X64] - PE32|Mu-SharedNetworking_extdep/RELEASE/X64/HttpUtilitiesDxe.efi|RELEASE - -[Binaries.IA32] - PE32|Mu-SharedNetworking_extdep/RELEASE/IA32/HttpUtilitiesDxe.efi|RELEASE - -[Binaries.AARCH64] - PE32|Mu-SharedNetworking_extdep/RELEASE/AARCH64/HttpUtilitiesDxe.efi|RELEASE - -[Packages] - MdePkg/MdePkg.dec - MdeModulePkg/MdeModulePkg.dec - -[Protocols] - gEfiHttpUtilitiesProtocolGuid ## PRODUCES - -[UserExtensions.TianoCore."ExtraFiles"] - HttpUtilitiesDxeExtra.uni - -[Depex] - TRUE +## @file +# Implementation of EFI Http Utilities Protocol interfaces. +# +# Copyright (c) 2015, Intel Corporation. All rights reserved.
+# (C) Copyright 2016 Hewlett Packard Enterprise Development LP
+# +# This program and the accompanying materials +# are licensed and made available under the terms and conditions of the BSD License +# which accompanies this distribution. The full text of the license may be found at +# http://opensource.org/licenses/bsd-license.php. +# THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS, +# WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED. +# +# +## + + +[Defines] + INF_VERSION = 0x0001001B + BASE_NAME = SharedHttpUtilitiesDxeRelease + FILE_GUID = 1792C670-F707-4089-A5E6-47191829DFAE + MODULE_TYPE = UEFI_DRIVER + VERSION_STRING = 1.0 + ENTRY_POINT = HttpUtilitiesDxeDriverEntryPoint + UNLOAD_IMAGE = HttpUtilitiesDxeUnload + MODULE_UNI_FILE = HttpUtilitiesDxe.uni + +# +# VALID_ARCHITECTURES = IA32 X64# + + +[Binaries.X64] + PE32|Mu-SharedNetworking_extdep/RELEASE/X64/HttpUtilitiesDxe.efi|RELEASE + +[Binaries.IA32] + PE32|Mu-SharedNetworking_extdep/RELEASE/IA32/HttpUtilitiesDxe.efi|RELEASE + +[Binaries.AARCH64] + PE32|Mu-SharedNetworking_extdep/RELEASE/AARCH64/HttpUtilitiesDxe.efi|RELEASE + +[Packages] + MdePkg/MdePkg.dec + MdeModulePkg/MdeModulePkg.dec + +[Protocols] + gEfiHttpUtilitiesProtocolGuid ## PRODUCES + +[UserExtensions.TianoCore."ExtraFiles"] + HttpUtilitiesDxeExtra.uni + +[Depex] + TRUE diff --git a/NetworkPkg/SharedNetworking/Ip6Dxe.DEBUG.inf b/NetworkPkg/SharedNetworking/Ip6Dxe.DEBUG.inf index 021feff850..32782a8a7d 100644 --- a/NetworkPkg/SharedNetworking/Ip6Dxe.DEBUG.inf +++ b/NetworkPkg/SharedNetworking/Ip6Dxe.DEBUG.inf @@ -1,74 +1,74 @@ -## @file -# Basic IPv6 packet I/O Service. -# -# This module provides basic network IPv6 packet I/O services which includes support for -# Neighbor Discovery Protocol (ND), Multicast Listener Discovery Protocol (MLD), -# and a subset of the Internet Control Message Protocol (ICMPv6). This driver -# also provides the mechanism to set and get various types of configurations for -# the EFI IPv6 network stack. -# -# Copyright (c) 2009 - 2018, Intel Corporation. All rights reserved.
-# -# This program and the accompanying materials -# are licensed and made available under the terms and conditions of the BSD License -# which accompanies this distribution. The full text of the license may be found at -# http://opensource.org/licenses/bsd-license.php. -# -# THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS, -# WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED. -# -## - - -[Defines] - INF_VERSION = 0x0001001B - BASE_NAME = SharedIp6DxeDebug - FILE_GUID = 05284575-618D-4C20-B52B-1BD70D8D15B4 - MODULE_TYPE = UEFI_DRIVER - VERSION_STRING = 1.0 - ENTRY_POINT = Ip6DriverEntryPoint - UNLOAD_IMAGE = NetLibDefaultUnload - MODULE_UNI_FILE = Ip6Dxe.uni - - -# -# VALID_ARCHITECTURES = IA32 X64# - - -[Binaries.X64] - PE32|Mu-SharedNetworking_extdep/DEBUG/X64/Ip6Dxe.efi|DEBUG - -[Binaries.IA32] - PE32|Mu-SharedNetworking_extdep/DEBUG/IA32/Ip6Dxe.efi|DEBUG - -[Binaries.AARCH64] - PE32|Mu-SharedNetworking_extdep/DEBUG/AARCH64/Ip6Dxe.efi|DEBUG - -[Packages] - MdePkg/MdePkg.dec - MdeModulePkg/MdeModulePkg.dec - NetworkPkg/NetworkPkg.dec - -[Protocols] - gEfiManagedNetworkServiceBindingProtocolGuid ## TO_START - gEfiManagedNetworkProtocolGuid ## TO_START - gEfiIp6ServiceBindingProtocolGuid ## BY_START - gEfiIp6ProtocolGuid ## BY_START - gEfiIp6ConfigProtocolGuid ## BY_START - gEfiDhcp6ServiceBindingProtocolGuid ## SOMETIMES_CONSUMES - gEfiDhcp6ProtocolGuid ## SOMETIMES_CONSUMES - gEfiIpSec2ProtocolGuid ## SOMETIMES_CONSUMES - gEfiHiiConfigAccessProtocolGuid ## SOMETIMES_CONSUMES - -[Guids] - ## SOMETIMES_CONSUMES ## HII - gEfiIfrTianoGuid - ## SOMETIMES_CONSUMES ## UNDEFINED # HiiIsConfigHdrMatch mIp6ConfigStorageName - ## SOMETIMES_PRODUCES ## UNDEFINED # HiiConstructConfigHdr mIp6ConfigStorageName - ## SOMETIMES_PRODUCES ## UNDEFINED # HiiAddPackages Ip6DxeStrings Ip6ConfigBin - ## SOMETIMES_CONSUMES ## UNDEFINED # HiiUpdateForm - ## SOMETIMES_CONSUMES ## HII - gIp6ConfigNvDataGuid - -[Depex] - TRUE +## @file +# Basic IPv6 packet I/O Service. +# +# This module provides basic network IPv6 packet I/O services which includes support for +# Neighbor Discovery Protocol (ND), Multicast Listener Discovery Protocol (MLD), +# and a subset of the Internet Control Message Protocol (ICMPv6). This driver +# also provides the mechanism to set and get various types of configurations for +# the EFI IPv6 network stack. +# +# Copyright (c) 2009 - 2018, Intel Corporation. All rights reserved.
+# +# This program and the accompanying materials +# are licensed and made available under the terms and conditions of the BSD License +# which accompanies this distribution. The full text of the license may be found at +# http://opensource.org/licenses/bsd-license.php. +# +# THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS, +# WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED. +# +## + + +[Defines] + INF_VERSION = 0x0001001B + BASE_NAME = SharedIp6DxeDebug + FILE_GUID = 05284575-618D-4C20-B52B-1BD70D8D15B4 + MODULE_TYPE = UEFI_DRIVER + VERSION_STRING = 1.0 + ENTRY_POINT = Ip6DriverEntryPoint + UNLOAD_IMAGE = NetLibDefaultUnload + MODULE_UNI_FILE = Ip6Dxe.uni + + +# +# VALID_ARCHITECTURES = IA32 X64# + + +[Binaries.X64] + PE32|Mu-SharedNetworking_extdep/DEBUG/X64/Ip6Dxe.efi|DEBUG + +[Binaries.IA32] + PE32|Mu-SharedNetworking_extdep/DEBUG/IA32/Ip6Dxe.efi|DEBUG + +[Binaries.AARCH64] + PE32|Mu-SharedNetworking_extdep/DEBUG/AARCH64/Ip6Dxe.efi|DEBUG + +[Packages] + MdePkg/MdePkg.dec + MdeModulePkg/MdeModulePkg.dec + NetworkPkg/NetworkPkg.dec + +[Protocols] + gEfiManagedNetworkServiceBindingProtocolGuid ## TO_START + gEfiManagedNetworkProtocolGuid ## TO_START + gEfiIp6ServiceBindingProtocolGuid ## BY_START + gEfiIp6ProtocolGuid ## BY_START + gEfiIp6ConfigProtocolGuid ## BY_START + gEfiDhcp6ServiceBindingProtocolGuid ## SOMETIMES_CONSUMES + gEfiDhcp6ProtocolGuid ## SOMETIMES_CONSUMES + gEfiIpSec2ProtocolGuid ## SOMETIMES_CONSUMES + gEfiHiiConfigAccessProtocolGuid ## SOMETIMES_CONSUMES + +[Guids] + ## SOMETIMES_CONSUMES ## HII + gEfiIfrTianoGuid + ## SOMETIMES_CONSUMES ## UNDEFINED # HiiIsConfigHdrMatch mIp6ConfigStorageName + ## SOMETIMES_PRODUCES ## UNDEFINED # HiiConstructConfigHdr mIp6ConfigStorageName + ## SOMETIMES_PRODUCES ## UNDEFINED # HiiAddPackages Ip6DxeStrings Ip6ConfigBin + ## SOMETIMES_CONSUMES ## UNDEFINED # HiiUpdateForm + ## SOMETIMES_CONSUMES ## HII + gIp6ConfigNvDataGuid + +[Depex] + TRUE diff --git a/NetworkPkg/SharedNetworking/Ip6Dxe.RELEASE.inf b/NetworkPkg/SharedNetworking/Ip6Dxe.RELEASE.inf index 5bfdd27261..98186273c6 100644 --- a/NetworkPkg/SharedNetworking/Ip6Dxe.RELEASE.inf +++ b/NetworkPkg/SharedNetworking/Ip6Dxe.RELEASE.inf @@ -1,73 +1,73 @@ -## @file -# Basic IPv6 packet I/O Service. -# -# This module provides basic network IPv6 packet I/O services which includes support for -# Neighbor Discovery Protocol (ND), Multicast Listener Discovery Protocol (MLD), -# and a subset of the Internet Control Message Protocol (ICMPv6). This driver -# also provides the mechanism to set and get various types of configurations for -# the EFI IPv6 network stack. -# -# Copyright (c) 2009 - 2018, Intel Corporation. All rights reserved.
-# -# This program and the accompanying materials -# are licensed and made available under the terms and conditions of the BSD License -# which accompanies this distribution. The full text of the license may be found at -# http://opensource.org/licenses/bsd-license.php. -# -# THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS, -# WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED. -# -## - - -[Defines] - INF_VERSION = 0x0001001B - BASE_NAME = SharedIp6DxeRelease - FILE_GUID = 304903A7-65F6-4526-9026-56D67453AEA5 - MODULE_TYPE = UEFI_DRIVER - VERSION_STRING = 1.0 - ENTRY_POINT = Ip6DriverEntryPoint - UNLOAD_IMAGE = NetLibDefaultUnload - MODULE_UNI_FILE = Ip6Dxe.uni - -# -# VALID_ARCHITECTURES = IA32 X64# - - -[Binaries.X64] - PE32|Mu-SharedNetworking_extdep/RELEASE/X64/Ip6Dxe.efi|RELEASE - -[Binaries.IA32] - PE32|Mu-SharedNetworking_extdep/RELEASE/IA32/Ip6Dxe.efi|RELEASE - -[Binaries.AARCH64] - PE32|Mu-SharedNetworking_extdep/RELEASE/AARCH64/Ip6Dxe.efi|RELEASE - -[Packages] - MdePkg/MdePkg.dec - MdeModulePkg/MdeModulePkg.dec - NetworkPkg/NetworkPkg.dec - -[Protocols] - gEfiManagedNetworkServiceBindingProtocolGuid ## TO_START - gEfiManagedNetworkProtocolGuid ## TO_START - gEfiIp6ServiceBindingProtocolGuid ## BY_START - gEfiIp6ProtocolGuid ## BY_START - gEfiIp6ConfigProtocolGuid ## BY_START - gEfiDhcp6ServiceBindingProtocolGuid ## SOMETIMES_CONSUMES - gEfiDhcp6ProtocolGuid ## SOMETIMES_CONSUMES - gEfiIpSec2ProtocolGuid ## SOMETIMES_CONSUMES - gEfiHiiConfigAccessProtocolGuid ## SOMETIMES_CONSUMES - -[Guids] - ## SOMETIMES_CONSUMES ## HII - gEfiIfrTianoGuid - ## SOMETIMES_CONSUMES ## UNDEFINED # HiiIsConfigHdrMatch mIp6ConfigStorageName - ## SOMETIMES_PRODUCES ## UNDEFINED # HiiConstructConfigHdr mIp6ConfigStorageName - ## SOMETIMES_PRODUCES ## UNDEFINED # HiiAddPackages Ip6DxeStrings Ip6ConfigBin - ## SOMETIMES_CONSUMES ## UNDEFINED # HiiUpdateForm - ## SOMETIMES_CONSUMES ## HII - gIp6ConfigNvDataGuid - -[Depex] - TRUE +## @file +# Basic IPv6 packet I/O Service. +# +# This module provides basic network IPv6 packet I/O services which includes support for +# Neighbor Discovery Protocol (ND), Multicast Listener Discovery Protocol (MLD), +# and a subset of the Internet Control Message Protocol (ICMPv6). This driver +# also provides the mechanism to set and get various types of configurations for +# the EFI IPv6 network stack. +# +# Copyright (c) 2009 - 2018, Intel Corporation. All rights reserved.
+# +# This program and the accompanying materials +# are licensed and made available under the terms and conditions of the BSD License +# which accompanies this distribution. The full text of the license may be found at +# http://opensource.org/licenses/bsd-license.php. +# +# THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS, +# WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED. +# +## + + +[Defines] + INF_VERSION = 0x0001001B + BASE_NAME = SharedIp6DxeRelease + FILE_GUID = 304903A7-65F6-4526-9026-56D67453AEA5 + MODULE_TYPE = UEFI_DRIVER + VERSION_STRING = 1.0 + ENTRY_POINT = Ip6DriverEntryPoint + UNLOAD_IMAGE = NetLibDefaultUnload + MODULE_UNI_FILE = Ip6Dxe.uni + +# +# VALID_ARCHITECTURES = IA32 X64# + + +[Binaries.X64] + PE32|Mu-SharedNetworking_extdep/RELEASE/X64/Ip6Dxe.efi|RELEASE + +[Binaries.IA32] + PE32|Mu-SharedNetworking_extdep/RELEASE/IA32/Ip6Dxe.efi|RELEASE + +[Binaries.AARCH64] + PE32|Mu-SharedNetworking_extdep/RELEASE/AARCH64/Ip6Dxe.efi|RELEASE + +[Packages] + MdePkg/MdePkg.dec + MdeModulePkg/MdeModulePkg.dec + NetworkPkg/NetworkPkg.dec + +[Protocols] + gEfiManagedNetworkServiceBindingProtocolGuid ## TO_START + gEfiManagedNetworkProtocolGuid ## TO_START + gEfiIp6ServiceBindingProtocolGuid ## BY_START + gEfiIp6ProtocolGuid ## BY_START + gEfiIp6ConfigProtocolGuid ## BY_START + gEfiDhcp6ServiceBindingProtocolGuid ## SOMETIMES_CONSUMES + gEfiDhcp6ProtocolGuid ## SOMETIMES_CONSUMES + gEfiIpSec2ProtocolGuid ## SOMETIMES_CONSUMES + gEfiHiiConfigAccessProtocolGuid ## SOMETIMES_CONSUMES + +[Guids] + ## SOMETIMES_CONSUMES ## HII + gEfiIfrTianoGuid + ## SOMETIMES_CONSUMES ## UNDEFINED # HiiIsConfigHdrMatch mIp6ConfigStorageName + ## SOMETIMES_PRODUCES ## UNDEFINED # HiiConstructConfigHdr mIp6ConfigStorageName + ## SOMETIMES_PRODUCES ## UNDEFINED # HiiAddPackages Ip6DxeStrings Ip6ConfigBin + ## SOMETIMES_CONSUMES ## UNDEFINED # HiiUpdateForm + ## SOMETIMES_CONSUMES ## HII + gIp6ConfigNvDataGuid + +[Depex] + TRUE diff --git a/NetworkPkg/SharedNetworking/README.md b/NetworkPkg/SharedNetworking/README.md index 16e38499a5..ffaedf7276 100644 --- a/NetworkPkg/SharedNetworking/README.md +++ b/NetworkPkg/SharedNetworking/README.md @@ -1,32 +1,32 @@ -# SharedNetworking - -Similar to SharedCrypto -(), -SharedNetworking is a collection of pre-built network binaries you can include -in your platform or other EDK2 project. - -SharedNetworking requires SharedCrypto for BaseCryptLib functionality (this only -applies to TlsLib and IScsiDxe) - -The build script for this (SharedNetworkSettings.py) pulls in MU_PLUS as it has -a dependency on SharedCrypto (which currently resides in MU_PLUS). This is -temporary and will not carry forward to 202002. It also doesn't apply to the -remainder of Basecore or CI. The dependency is only pulled in when build -SharedNetworking itself, which doesn't happen often. - -## Advantages - -- Faster Compile Times -- Potentially smaller binary sizes (depending on compression and a variety of - other factors) -- Easier to update and service since network binaries are packaged in an FV. - -## Including it in your project - -Just !include the SharedNetworking.fdf.inc as the example below shows: - -```edk2_fdf -[FV.FVDXE] - ... - !include NetworkPkg/SharedNetworking.fdf.inc -``` +# SharedNetworking + +Similar to SharedCrypto +(), +SharedNetworking is a collection of pre-built network binaries you can include +in your platform or other EDK2 project. + +SharedNetworking requires SharedCrypto for BaseCryptLib functionality (this only +applies to TlsLib and IScsiDxe) + +The build script for this (SharedNetworkSettings.py) pulls in MU_PLUS as it has +a dependency on SharedCrypto (which currently resides in MU_PLUS). This is +temporary and will not carry forward to 202002. It also doesn't apply to the +remainder of Basecore or CI. The dependency is only pulled in when build +SharedNetworking itself, which doesn't happen often. + +## Advantages + +- Faster Compile Times +- Potentially smaller binary sizes (depending on compression and a variety of + other factors) +- Easier to update and service since network binaries are packaged in an FV. + +## Including it in your project + +Just !include the SharedNetworking.fdf.inc as the example below shows: + +```edk2_fdf +[FV.FVDXE] + ... + !include NetworkPkg/SharedNetworking.fdf.inc +``` diff --git a/NetworkPkg/SharedNetworking/SharedNetworkPkg.dsc b/NetworkPkg/SharedNetworking/SharedNetworkPkg.dsc index d1e37397ae..62b6c4a071 100644 --- a/NetworkPkg/SharedNetworking/SharedNetworkPkg.dsc +++ b/NetworkPkg/SharedNetworking/SharedNetworkPkg.dsc @@ -1,177 +1,177 @@ -## @file -# UEFI 2.4 Network Module Package for All Architectures -# -# (C) Copyright 2014 Hewlett-Packard Development Company, L.P.
-# Copyright (c) 2009 - 2018, Intel Corporation. All rights reserved.
-# -# This program and the accompanying materials -# are licensed and made available under the terms and conditions of the BSD License -# which accompanies this distribution. The full text of the license may be found at -# http://opensource.org/licenses/bsd-license.php -# -# THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS, -# WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED. -# -## - -[Defines] - PLATFORM_NAME = SharedNetworkPkg - PLATFORM_GUID = 3FD34E9B-E90C-44e1-B510-1F632A509F10 - PLATFORM_VERSION = 0.98 - DSC_SPECIFICATION = 0x00010005 - OUTPUT_DIRECTORY = Build/SharedNetworkPkg - SUPPORTED_ARCHITECTURES = IA32|X64|EBC|ARM|AARCH64 - BUILD_TARGETS = DEBUG|RELEASE|NOOPT - SKUID_IDENTIFIER = DEFAULT - FLASH_DEFINITION = NetworkPkg/SharedNetworking/SharedNetworkPkg.fdf - NETWORK_ENABLE = TRUE - NETWORK_TLS_ENABLE = TRUE - NETWORK_ALLOW_HTTP_CONNECTIONS = TRUE - NETWORK_SNP_ENABLE = TRUE - !include NetworkPkg/NetworkDefines.dsc.inc - - -## MU_CHANGE Begin -[LibraryClasses.ARM, LibraryClasses.AARCH64] - NULL|MdePkg/Library/BaseStackCheckLib/BaseStackCheckLib.inf -## MU_CHANGE End - -[LibraryClasses] - !include NetworkPkg/NetworkLibs.dsc.inc - DebugLib|MdePkg/Library/UefiDebugLibDebugPortProtocol/UefiDebugLibDebugPortProtocol.inf - PrintLib|MdePkg/Library/BasePrintLib/BasePrintLib.inf - BaseLib|MdePkg/Library/BaseLib/BaseLib.inf - BaseMemoryLib|MdePkg/Library/BaseMemoryLibOptDxe/BaseMemoryLibOptDxe.inf - DevicePathLib|MdePkg/Library/UefiDevicePathLib/UefiDevicePathLib.inf - HiiLib|MdeModulePkg/Library/UefiHiiLib/UefiHiiLib.inf - MemoryAllocationLib|MdePkg/Library/UefiMemoryAllocationLib/UefiMemoryAllocationLib.inf - PcdLib|MdePkg/Library/BasePcdLibNull/BasePcdLibNull.inf - PrintLib|MdePkg/Library/BasePrintLib/BasePrintLib.inf - UefiDriverEntryPoint|MdePkg/Library/UefiDriverEntryPoint/UefiDriverEntryPoint.inf - UefiApplicationEntryPoint|MdePkg/Library/UefiApplicationEntryPoint/UefiApplicationEntryPoint.inf - UefiBootServicesTableLib|MdePkg/Library/UefiBootServicesTableLib/UefiBootServicesTableLib.inf - UefiLib|MdePkg/Library/UefiLib/UefiLib.inf - UefiRuntimeServicesTableLib|MdePkg/Library/UefiRuntimeServicesTableLib/UefiRuntimeServicesTableLib.inf - UefiHiiServicesLib|MdeModulePkg/Library/UefiHiiServicesLib/UefiHiiServicesLib.inf - UefiBootManagerLib|MdeModulePkg/Library/UefiBootManagerLib/UefiBootManagerLib.inf - MemoryTypeInformationChangeLib|MdeModulePkg/Library/MemoryTypeInformationChangeLibNull/MemoryTypeInformationChangeLibNull.inf # MU_CHANGE - PerformanceLib|MdePkg/Library/BasePerformanceLibNull/BasePerformanceLibNull.inf - PeCoffGetEntryPointLib|MdePkg/Library/BasePeCoffGetEntryPointLib/BasePeCoffGetEntryPointLib.inf - DxeServicesLib|MdePkg/Library/DxeServicesLib/DxeServicesLib.inf - DxeServicesTableLib|MdePkg/Library/DxeServicesTableLib/DxeServicesTableLib.inf - ReportStatusCodeLib|MdeModulePkg/Library/DxeReportStatusCodeLib/DxeReportStatusCodeLib.inf - SafeIntLib|MdePkg/Library/BaseSafeIntLib/BaseSafeIntLib.inf - BaseBinSecurityLibRng|MdePkg/Library/BaseBinSecurityLibNull/BaseBinSecurityLibNull.inf - - OpensslLib|CryptoPkg/Library/OpensslLib/OpensslLib.inf - DebugPrintErrorLevelLib|MdePkg/Library/BaseDebugPrintErrorLevelLib/BaseDebugPrintErrorLevelLib.inf - FileHandleLib|MdePkg/Library/UefiFileHandleLib/UefiFileHandleLib.inf - FileExplorerLib|MdeModulePkg/Library/FileExplorerLib/FileExplorerLib.inf - SortLib|MdeModulePkg/Library/UefiSortLib/UefiSortLib.inf - IntrinsicLib|CryptoPkg/Library/IntrinsicLib/IntrinsicLib.inf - -[LibraryClasses.common.DXE_CORE, LibraryClasses.common.DXE_DRIVER, LibraryClasses.common.DXE_RUNTIME_DRIVER, LibraryClasses.common.UEFI_DRIVER] - # Common\MU_TIANO\CryptoPkg\Library\BaseCryptLibOnProtocolPpi\DxeCryptLib.inf - BaseCryptLib|CryptoPkg/Library/BaseCryptLibOnProtocolPpi/DxeCryptLib.inf - TlsLib|CryptoPkg/Library/BaseCryptLibOnProtocolPpi/DxeCryptLib.inf - -[LibraryClasses.common.PEIM] - BaseCryptLib|CryptoPkg/Library/BaseCryptLibOnProtocolPpi/PeiCryptLib.inf - TlsLib|CryptoPkg/Library/BaseCryptLibOnProtocolPpi/PeiCryptLib.inf - -[LibraryClasses.x64.DXE_SMM_DRIVER, LibraryClasses.x64.SMM_CORE] - BaseCryptLib|CryptoPkg/Library/BaseCryptLibOnProtocolPpi/SmmCryptLib.inf - TlsLib|CryptoPkg/Library/BaseCryptLibOnProtocolPpi/SmmCryptLib.inf - -##MSCHANGE Begin -!if $(TOOL_CHAIN_TAG) == VS2019 or $(TOOL_CHAIN_TAG) == VS2022 -[LibraryClasses.X64] - # Provide StackCookie support lib so that we can link to /GS exports for VS builds - NULL|MdePkg/Library/BaseBinSecurityLibRng/BaseBinSecurityLibRng.inf - BaseBinSecurityLib|MdePkg/Library/BaseBinSecurityLibRng/BaseBinSecurityLibRng.inf -!endif -##MSCHANGE End -[LibraryClasses.DXE_RUNTIME_DRIVER, LibraryClasses.DXE_CORE] - DebugLib|MdePkg/Library/UefiDebugLibDebugPortProtocol/UefiDebugLibDebugPortProtocol.inf - ReportStatusCodeLib|MdeModulePkg/Library/DxeReportStatusCodeLib/DxeReportStatusCodeLib.inf - -[LibraryClasses.DXE_SMM_DRIVER, LibraryClasses.X64.SMM_CORE] - ReportStatusCodeLib|MdeModulePkg/Library/SmmReportStatusCodeLib/SmmReportStatusCodeLib.inf - DebugLib|MdeModulePkg/Library/PeiDxeDebugLibReportStatusCode/PeiDxeDebugLibReportStatusCode.inf - -[LibraryClasses.common.UEFI_DRIVER] - HobLib|MdePkg/Library/DxeHobLib/DxeHobLib.inf - ReportStatusCodeLib|MdeModulePkg/Library/DxeReportStatusCodeLib/DxeReportStatusCodeLib.inf - -[LibraryClasses.common.UEFI_APPLICATION] - DebugLib|MdePkg/Library/UefiDebugLibStdErr/UefiDebugLibStdErr.inf - ShellLib|ShellPkg/Library/UefiShellLib/UefiShellLib.inf - -[LibraryClasses.common.DXE_DRIVER, LibraryClasses.common.UEFI_APPLICATION, LibraryClasses.common.DXE_RUNTIME_DRIVER, LibraryClasses.common.DXE_CORE, LibraryClasses.common.UEFI_DRIVER] - #DXE_CORE DXE_DRIVER DXE_RUNTIME_DRIVER UEFI_APPLICATION UEFI_DRIVER - DebugLib|MdePkg/Library/UefiDebugLibDebugPortProtocol/UefiDebugLibDebugPortProtocol.inf - -[LibraryClasses.common.PEIM] - DebugLib|MsCorePkg/Library/PeiDebugLib/PeiDebugLib.inf - -[LibraryClasses.IA32, LibraryClasses.X64] - RngLib|MdePkg/Library/BaseRngLib/BaseRngLib.inf - -[LibraryClasses.ARM, LibraryClasses.AARCH64] - RngLib|SecurityPkg/RandomNumberGenerator/RngDxeLib/RngDxeLib.inf - -[LibraryClasses.ARM, LibraryClasses.AARCH64] - # - # It is not possible to prevent ARM compiler calls to generic intrinsic functions. - # This library provides the instrinsic functions generated by a given compiler. - # [LibraryClasses.ARM] and NULL mean link this library into all ARM images. - # -!if $(TOOL_CHAIN_TAG) != VS2017 or $(TOOL_CHAIN_TAG) != VS2015 or $(TOOL_CHAIN_TAG) != VS2019 or $(TOOL_CHAIN_TAG) != VS2022 ## MS_CHANGE only applies to ARM compiler - # NULL|ArmPkg/Library/CompilerIntrinsicsLib/CompilerIntrinsicsLib.inf # MU_CHANGE - NULL|MdePkg/Library/CompilerIntrinsicsLib/ArmCompilerIntrinsicsLib.inf # MU_CHANGE - BaseMemoryLib|MdePkg/Library/BaseMemoryLib/BaseMemoryLib.inf # while building with MSVC, we can't process the s files -!endif - NULL|MdePkg/Library/BaseStackCheckLib/BaseStackCheckLib.inf - # ArmSoftFloatLib|ArmPkg/Library/ArmSoftFloatLib/ArmSoftFloatLib.inf # MU_CHANGE - - -[PcdsFeatureFlag] - gEfiMdePkgTokenSpaceGuid.PcdComponentName2Disable|TRUE - gEfiMdePkgTokenSpaceGuid.PcdDriverDiagnostics2Disable|TRUE - -[PcdsFixedAtBuild] - gEfiMdePkgTokenSpaceGuid.PcdDebugPropertyMask|0x2f - gEfiMdePkgTokenSpaceGuid.PcdDebugPrintErrorLevel|0x80000000 - -################################################################################################### -# -# Components Section - list of the modules and components that will be processed by compilation -# tools and the EDK II tools to generate PE32/PE32+/Coff image files. -# -# Note: The EDK II DSC file is not used to specify how compiled binary images get placed -# into firmware volume images. This section is just a list of modules to compile from -# source into UEFI-compliant binaries. -# It is the FDF file that contains information on combining binary files into firmware -# volume images, whose concept is beyond UEFI and is described in PI specification. -# Binary modules do not need to be listed in this section, as they should be -# specified in the FDF file. For example: Shell binary (Shell_Full.efi), FAT binary (Fat.efi), -# Logo (Logo.bmp), and etc. -# There may also be modules listed in this section that are not required in the FDF file, -# When a module listed here is excluded from FDF file, then UEFI-compliant binary will be -# generated for it, but the binary will not be put into any firmware volume. -# -################################################################################################### - -[Components] - #NetworkPkg/WifiConnectionManagerDxe/WifiConnectionManagerDxe.inf # we don't care about wifi connections yet - NetworkPkg/Application/VConfig/VConfig.inf - - !include NetworkPkg/NetworkComponents.dsc.inc - -[BuildOptions] - *_*_*_CC_FLAGS = -D DISABLE_NEW_DEPRECATED_INTERFACES - - -[BuildOptions.common.EDKII.DXE_RUNTIME_DRIVER, BuildOptions.common.EDKII.DXE_SMM_DRIVER, BuildOptions.common.EDKII.SMM_CORE, BuildOptions.common.EDKII.DXE_DRIVER] - MSFT:*_*_IA32_DLINK_FLAGS = /ALIGN:4096 # enable 4k alignment for MAT and other protections. +## @file +# UEFI 2.4 Network Module Package for All Architectures +# +# (C) Copyright 2014 Hewlett-Packard Development Company, L.P.
+# Copyright (c) 2009 - 2018, Intel Corporation. All rights reserved.
+# +# This program and the accompanying materials +# are licensed and made available under the terms and conditions of the BSD License +# which accompanies this distribution. The full text of the license may be found at +# http://opensource.org/licenses/bsd-license.php +# +# THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS, +# WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED. +# +## + +[Defines] + PLATFORM_NAME = SharedNetworkPkg + PLATFORM_GUID = 3FD34E9B-E90C-44e1-B510-1F632A509F10 + PLATFORM_VERSION = 0.98 + DSC_SPECIFICATION = 0x00010005 + OUTPUT_DIRECTORY = Build/SharedNetworkPkg + SUPPORTED_ARCHITECTURES = IA32|X64|EBC|ARM|AARCH64 + BUILD_TARGETS = DEBUG|RELEASE|NOOPT + SKUID_IDENTIFIER = DEFAULT + FLASH_DEFINITION = NetworkPkg/SharedNetworking/SharedNetworkPkg.fdf + NETWORK_ENABLE = TRUE + NETWORK_TLS_ENABLE = TRUE + NETWORK_ALLOW_HTTP_CONNECTIONS = TRUE + NETWORK_SNP_ENABLE = TRUE + !include NetworkPkg/NetworkDefines.dsc.inc + + +## MU_CHANGE Begin +[LibraryClasses.ARM, LibraryClasses.AARCH64] + NULL|MdePkg/Library/BaseStackCheckLib/BaseStackCheckLib.inf +## MU_CHANGE End + +[LibraryClasses] + !include NetworkPkg/NetworkLibs.dsc.inc + DebugLib|MdePkg/Library/UefiDebugLibDebugPortProtocol/UefiDebugLibDebugPortProtocol.inf + PrintLib|MdePkg/Library/BasePrintLib/BasePrintLib.inf + BaseLib|MdePkg/Library/BaseLib/BaseLib.inf + BaseMemoryLib|MdePkg/Library/BaseMemoryLibOptDxe/BaseMemoryLibOptDxe.inf + DevicePathLib|MdePkg/Library/UefiDevicePathLib/UefiDevicePathLib.inf + HiiLib|MdeModulePkg/Library/UefiHiiLib/UefiHiiLib.inf + MemoryAllocationLib|MdePkg/Library/UefiMemoryAllocationLib/UefiMemoryAllocationLib.inf + PcdLib|MdePkg/Library/BasePcdLibNull/BasePcdLibNull.inf + PrintLib|MdePkg/Library/BasePrintLib/BasePrintLib.inf + UefiDriverEntryPoint|MdePkg/Library/UefiDriverEntryPoint/UefiDriverEntryPoint.inf + UefiApplicationEntryPoint|MdePkg/Library/UefiApplicationEntryPoint/UefiApplicationEntryPoint.inf + UefiBootServicesTableLib|MdePkg/Library/UefiBootServicesTableLib/UefiBootServicesTableLib.inf + UefiLib|MdePkg/Library/UefiLib/UefiLib.inf + UefiRuntimeServicesTableLib|MdePkg/Library/UefiRuntimeServicesTableLib/UefiRuntimeServicesTableLib.inf + UefiHiiServicesLib|MdeModulePkg/Library/UefiHiiServicesLib/UefiHiiServicesLib.inf + UefiBootManagerLib|MdeModulePkg/Library/UefiBootManagerLib/UefiBootManagerLib.inf + MemoryTypeInformationChangeLib|MdeModulePkg/Library/MemoryTypeInformationChangeLibNull/MemoryTypeInformationChangeLibNull.inf # MU_CHANGE + PerformanceLib|MdePkg/Library/BasePerformanceLibNull/BasePerformanceLibNull.inf + PeCoffGetEntryPointLib|MdePkg/Library/BasePeCoffGetEntryPointLib/BasePeCoffGetEntryPointLib.inf + DxeServicesLib|MdePkg/Library/DxeServicesLib/DxeServicesLib.inf + DxeServicesTableLib|MdePkg/Library/DxeServicesTableLib/DxeServicesTableLib.inf + ReportStatusCodeLib|MdeModulePkg/Library/DxeReportStatusCodeLib/DxeReportStatusCodeLib.inf + SafeIntLib|MdePkg/Library/BaseSafeIntLib/BaseSafeIntLib.inf + BaseBinSecurityLibRng|MdePkg/Library/BaseBinSecurityLibNull/BaseBinSecurityLibNull.inf + + OpensslLib|CryptoPkg/Library/OpensslLib/OpensslLib.inf + DebugPrintErrorLevelLib|MdePkg/Library/BaseDebugPrintErrorLevelLib/BaseDebugPrintErrorLevelLib.inf + FileHandleLib|MdePkg/Library/UefiFileHandleLib/UefiFileHandleLib.inf + FileExplorerLib|MdeModulePkg/Library/FileExplorerLib/FileExplorerLib.inf + SortLib|MdeModulePkg/Library/UefiSortLib/UefiSortLib.inf + IntrinsicLib|CryptoPkg/Library/IntrinsicLib/IntrinsicLib.inf + +[LibraryClasses.common.DXE_CORE, LibraryClasses.common.DXE_DRIVER, LibraryClasses.common.DXE_RUNTIME_DRIVER, LibraryClasses.common.UEFI_DRIVER] + # Common\MU_TIANO\CryptoPkg\Library\BaseCryptLibOnProtocolPpi\DxeCryptLib.inf + BaseCryptLib|CryptoPkg/Library/BaseCryptLibOnProtocolPpi/DxeCryptLib.inf + TlsLib|CryptoPkg/Library/BaseCryptLibOnProtocolPpi/DxeCryptLib.inf + +[LibraryClasses.common.PEIM] + BaseCryptLib|CryptoPkg/Library/BaseCryptLibOnProtocolPpi/PeiCryptLib.inf + TlsLib|CryptoPkg/Library/BaseCryptLibOnProtocolPpi/PeiCryptLib.inf + +[LibraryClasses.x64.DXE_SMM_DRIVER, LibraryClasses.x64.SMM_CORE] + BaseCryptLib|CryptoPkg/Library/BaseCryptLibOnProtocolPpi/SmmCryptLib.inf + TlsLib|CryptoPkg/Library/BaseCryptLibOnProtocolPpi/SmmCryptLib.inf + +##MSCHANGE Begin +!if $(TOOL_CHAIN_TAG) == VS2019 or $(TOOL_CHAIN_TAG) == VS2022 +[LibraryClasses.X64] + # Provide StackCookie support lib so that we can link to /GS exports for VS builds + NULL|MdePkg/Library/BaseBinSecurityLibRng/BaseBinSecurityLibRng.inf + BaseBinSecurityLib|MdePkg/Library/BaseBinSecurityLibRng/BaseBinSecurityLibRng.inf +!endif +##MSCHANGE End +[LibraryClasses.DXE_RUNTIME_DRIVER, LibraryClasses.DXE_CORE] + DebugLib|MdePkg/Library/UefiDebugLibDebugPortProtocol/UefiDebugLibDebugPortProtocol.inf + ReportStatusCodeLib|MdeModulePkg/Library/DxeReportStatusCodeLib/DxeReportStatusCodeLib.inf + +[LibraryClasses.DXE_SMM_DRIVER, LibraryClasses.X64.SMM_CORE] + ReportStatusCodeLib|MdeModulePkg/Library/SmmReportStatusCodeLib/SmmReportStatusCodeLib.inf + DebugLib|MdeModulePkg/Library/PeiDxeDebugLibReportStatusCode/PeiDxeDebugLibReportStatusCode.inf + +[LibraryClasses.common.UEFI_DRIVER] + HobLib|MdePkg/Library/DxeHobLib/DxeHobLib.inf + ReportStatusCodeLib|MdeModulePkg/Library/DxeReportStatusCodeLib/DxeReportStatusCodeLib.inf + +[LibraryClasses.common.UEFI_APPLICATION] + DebugLib|MdePkg/Library/UefiDebugLibStdErr/UefiDebugLibStdErr.inf + ShellLib|ShellPkg/Library/UefiShellLib/UefiShellLib.inf + +[LibraryClasses.common.DXE_DRIVER, LibraryClasses.common.UEFI_APPLICATION, LibraryClasses.common.DXE_RUNTIME_DRIVER, LibraryClasses.common.DXE_CORE, LibraryClasses.common.UEFI_DRIVER] + #DXE_CORE DXE_DRIVER DXE_RUNTIME_DRIVER UEFI_APPLICATION UEFI_DRIVER + DebugLib|MdePkg/Library/UefiDebugLibDebugPortProtocol/UefiDebugLibDebugPortProtocol.inf + +[LibraryClasses.common.PEIM] + DebugLib|MsCorePkg/Library/PeiDebugLib/PeiDebugLib.inf + +[LibraryClasses.IA32, LibraryClasses.X64] + RngLib|MdePkg/Library/BaseRngLib/BaseRngLib.inf + +[LibraryClasses.ARM, LibraryClasses.AARCH64] + RngLib|SecurityPkg/RandomNumberGenerator/RngDxeLib/RngDxeLib.inf + +[LibraryClasses.ARM, LibraryClasses.AARCH64] + # + # It is not possible to prevent ARM compiler calls to generic intrinsic functions. + # This library provides the instrinsic functions generated by a given compiler. + # [LibraryClasses.ARM] and NULL mean link this library into all ARM images. + # +!if $(TOOL_CHAIN_TAG) != VS2017 or $(TOOL_CHAIN_TAG) != VS2015 or $(TOOL_CHAIN_TAG) != VS2019 or $(TOOL_CHAIN_TAG) != VS2022 ## MS_CHANGE only applies to ARM compiler + # NULL|ArmPkg/Library/CompilerIntrinsicsLib/CompilerIntrinsicsLib.inf # MU_CHANGE + NULL|MdePkg/Library/CompilerIntrinsicsLib/ArmCompilerIntrinsicsLib.inf # MU_CHANGE + BaseMemoryLib|MdePkg/Library/BaseMemoryLib/BaseMemoryLib.inf # while building with MSVC, we can't process the s files +!endif + NULL|MdePkg/Library/BaseStackCheckLib/BaseStackCheckLib.inf + # ArmSoftFloatLib|ArmPkg/Library/ArmSoftFloatLib/ArmSoftFloatLib.inf # MU_CHANGE + + +[PcdsFeatureFlag] + gEfiMdePkgTokenSpaceGuid.PcdComponentName2Disable|TRUE + gEfiMdePkgTokenSpaceGuid.PcdDriverDiagnostics2Disable|TRUE + +[PcdsFixedAtBuild] + gEfiMdePkgTokenSpaceGuid.PcdDebugPropertyMask|0x2f + gEfiMdePkgTokenSpaceGuid.PcdDebugPrintErrorLevel|0x80000000 + +################################################################################################### +# +# Components Section - list of the modules and components that will be processed by compilation +# tools and the EDK II tools to generate PE32/PE32+/Coff image files. +# +# Note: The EDK II DSC file is not used to specify how compiled binary images get placed +# into firmware volume images. This section is just a list of modules to compile from +# source into UEFI-compliant binaries. +# It is the FDF file that contains information on combining binary files into firmware +# volume images, whose concept is beyond UEFI and is described in PI specification. +# Binary modules do not need to be listed in this section, as they should be +# specified in the FDF file. For example: Shell binary (Shell_Full.efi), FAT binary (Fat.efi), +# Logo (Logo.bmp), and etc. +# There may also be modules listed in this section that are not required in the FDF file, +# When a module listed here is excluded from FDF file, then UEFI-compliant binary will be +# generated for it, but the binary will not be put into any firmware volume. +# +################################################################################################### + +[Components] + #NetworkPkg/WifiConnectionManagerDxe/WifiConnectionManagerDxe.inf # we don't care about wifi connections yet + NetworkPkg/Application/VConfig/VConfig.inf + + !include NetworkPkg/NetworkComponents.dsc.inc + +[BuildOptions] + *_*_*_CC_FLAGS = -D DISABLE_NEW_DEPRECATED_INTERFACES + + +[BuildOptions.common.EDKII.DXE_RUNTIME_DRIVER, BuildOptions.common.EDKII.DXE_SMM_DRIVER, BuildOptions.common.EDKII.SMM_CORE, BuildOptions.common.EDKII.DXE_DRIVER] + MSFT:*_*_IA32_DLINK_FLAGS = /ALIGN:4096 # enable 4k alignment for MAT and other protections. MSFT:*_*_X64_DLINK_FLAGS = /ALIGN:4096 # enable 4k alignment for MAT and other protections. \ No newline at end of file diff --git a/NetworkPkg/SharedNetworking/SharedNetworkPkg.fdf b/NetworkPkg/SharedNetworking/SharedNetworkPkg.fdf index 433cf5782c..0b2bb67d42 100644 --- a/NetworkPkg/SharedNetworking/SharedNetworkPkg.fdf +++ b/NetworkPkg/SharedNetworking/SharedNetworkPkg.fdf @@ -1,48 +1,48 @@ -[Defines] -# These values are included to satisfy the build tool and should not be considered -# valid values for a product or platform. These values won't apply to the FV that -# is created once it is incldued in another platform. -DEFINE FLASH_BASE = 0xFF600000 # -DEFINE FLASH_SIZE = 0x00A00000 # -DEFINE FLASH_BLOCK_SIZE = 0x00010000 # -DEFINE FLASH_NUM_BLOCKS = 0x000000A0 # - -DEFINE FLASH_REGION_FVDXE_OFFSET = 0x00380000 # Flash addr (0xFF980000) -DEFINE FLASH_REGION_FVDXE_SIZE = 0x00280000 # -DEFINE NETWORK_HTTP_BOOT_ENABLE = FALSE - -[FV.FVDXE] - BlockSize = $(FLASH_BLOCK_SIZE) - 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 - - !include NetworkPkg/Network.fdf.inc - -[Rule.Common.UEFI_DRIVER] - FILE DRIVER = $(NAMED_GUID) { - DXE_DEPEX DXE_DEPEX Optional $(INF_OUTPUT)/$(MODULE_NAME).depex - PE32 PE32 $(INF_OUTPUT)/$(MODULE_NAME).efi - UI STRING="$(MODULE_NAME)" Optional - VERSION STRING="$(INF_VERSION)" Optional BUILD_NUM=$(BUILD_NUMBER) - } -[Rule.Common.DXE_DRIVER] - FILE DRIVER = $(NAMED_GUID) { - DXE_DEPEX DXE_DEPEX Optional $(INF_OUTPUT)/$(MODULE_NAME).depex - PE32 PE32 $(INF_OUTPUT)/$(MODULE_NAME).efi - UI STRING="$(MODULE_NAME)" Optional - VERSION STRING="$(INF_VERSION)" Optional BUILD_NUM=$(BUILD_NUMBER) +[Defines] +# These values are included to satisfy the build tool and should not be considered +# valid values for a product or platform. These values won't apply to the FV that +# is created once it is incldued in another platform. +DEFINE FLASH_BASE = 0xFF600000 # +DEFINE FLASH_SIZE = 0x00A00000 # +DEFINE FLASH_BLOCK_SIZE = 0x00010000 # +DEFINE FLASH_NUM_BLOCKS = 0x000000A0 # + +DEFINE FLASH_REGION_FVDXE_OFFSET = 0x00380000 # Flash addr (0xFF980000) +DEFINE FLASH_REGION_FVDXE_SIZE = 0x00280000 # +DEFINE NETWORK_HTTP_BOOT_ENABLE = FALSE + +[FV.FVDXE] + BlockSize = $(FLASH_BLOCK_SIZE) + 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 + + !include NetworkPkg/Network.fdf.inc + +[Rule.Common.UEFI_DRIVER] + FILE DRIVER = $(NAMED_GUID) { + DXE_DEPEX DXE_DEPEX Optional $(INF_OUTPUT)/$(MODULE_NAME).depex + PE32 PE32 $(INF_OUTPUT)/$(MODULE_NAME).efi + UI STRING="$(MODULE_NAME)" Optional + VERSION STRING="$(INF_VERSION)" Optional BUILD_NUM=$(BUILD_NUMBER) + } +[Rule.Common.DXE_DRIVER] + FILE DRIVER = $(NAMED_GUID) { + DXE_DEPEX DXE_DEPEX Optional $(INF_OUTPUT)/$(MODULE_NAME).depex + PE32 PE32 $(INF_OUTPUT)/$(MODULE_NAME).efi + UI STRING="$(MODULE_NAME)" Optional + VERSION STRING="$(INF_VERSION)" Optional BUILD_NUM=$(BUILD_NUMBER) } \ No newline at end of file diff --git a/NetworkPkg/SharedNetworking/SharedNetworkSettings.py b/NetworkPkg/SharedNetworking/SharedNetworkSettings.py index 4c53e99beb..e604a959ed 100644 --- a/NetworkPkg/SharedNetworking/SharedNetworkSettings.py +++ b/NetworkPkg/SharedNetworking/SharedNetworkSettings.py @@ -1,568 +1,568 @@ -## -# Script to Build Shared Crypto Driver -# Copyright Microsoft Corporation, 2019 -# -# This is to build the SharedNetworking binaries for NuGet publishing -## -import os -from edk2toolext.environment import shell_environment -import logging -import shutil -from edk2toolext.environment.uefi_build import UefiBuilder -from edk2toolext.invocables.edk2_ci_setup import CiSetupSettingsManager -from edk2toolext.invocables.edk2_update import UpdateSettingsManager -from edk2toollib.utility_functions import RunCmd -from edk2toollib.utility_functions import RunPythonScript -from edk2toolext.environment.extdeptypes.nuget_dependency import NugetDependency -import glob -from io import StringIO -import re -import tempfile -try: - from DriverBuilder import BinaryBuildSettingsManager -except Exception: - class BinaryBuildSettingsManager: - def __init__(): - raise RuntimeError("You shouldn't be including this") - pass -from edk2toollib.utility_functions import GetHostInfo - -# -# ========================================================================== -# PLATFORM BUILD ENVIRONMENT CONFIGURATION -# - - -def _CopyFile(srcDir, destDir, file_name, new_name=None): - if new_name is None: - new_name = file_name - shutil.copyfile(os.path.join(srcDir, file_name), - os.path.join(destDir, new_name)) - - -def _MoveArchTargetSpecificFile(binary, offset, output_dir): - binary_path = binary[offset:] - binary_name = os.path.basename(binary) - binary_folder = os.path.dirname(binary) - arch = _GetArchitecture(binary_path) - target = _GetTarget(binary_path) - if target is None: - raise FileExistsError("Unknown file {0}".format(binary)) - dest_path = os.path.join(output_dir, target, arch) - dest_filepath = os.path.join(dest_path, binary_name) - if os.path.exists(dest_filepath): - #logging.warning("Skipping {0}: {1} from {2}".format(binary_name, dest_filepath, binary)) - return - - if not os.path.exists(dest_path): - os.makedirs(dest_path) - # logging.warning("Copying {0}: {1}".format(binary_name,binary)) - _CopyFile(binary_folder, dest_path, binary_name) - - -def _GetArchitecture(path: str): - path = os.path.normpath(path) - path_parts = path.split(os.path.sep) - return path_parts[1] - - -def _GetTarget(path: str): - path = os.path.normpath(path) - path_parts = path.split(os.path.sep) - target = path_parts[0] - - if "_" in target: - return target.split("_")[0] - return None - - -def _GetCommitHashes(root_dir: os.PathLike): - # Recursively looks at every .git and gets the commit from there - search_path = os.path.join(root_dir, "**", ".git") - logging.info(f"Searching {search_path} for git repos") - search = glob.iglob(search_path, recursive=True) - found_repos = {} - cmd_args = "rev-parse HEAD" - for git_path in search: - git_path_dir = os.path.dirname(git_path) - if git_path_dir == root_dir: - git_repo_name = "MU_BASECORE" - else: - git_repo_name = os.path.relpath(git_path_dir, root_dir) - git_repo_name = git_repo_name.upper() - if git_repo_name in found_repos: - raise RuntimeError( - f"we've already found this repo before {git_repo_name} {git_path_dir}") - # read the git hash for this repo - return_buffer = StringIO() - RunCmd("git", cmd_args, workingdir=git_path_dir, outstream=return_buffer) - commit_hash = return_buffer.getvalue().strip() - return_buffer.close() - found_repos[git_repo_name] = commit_hash - return found_repos - -# Functions for getting the next nuget version - - -def _GetLatestNugetVersion(package_name, source=None): - cmd = NugetDependency.GetNugetCmd() - cmd += ["list"] - cmd += [package_name] - if source is not None: - cmd += ["-Source", source] - return_buffer = StringIO() - if (RunCmd(cmd[0], " ".join(cmd[1:]), outstream=return_buffer) == 0): - # Seek to the beginning of the output buffer and capture the output. - return_buffer.seek(0) - return_string = return_buffer.readlines() - return_buffer.close() - for line in return_string: - line = line.strip() - if line.startswith(package_name): - return line.replace(package_name, "").strip() - else: - return "0.0.0.0" - - -def _GetReleaseNote(): - cmd = "log --format=%B -n 1 HEAD" - return_buffer = StringIO() - if (RunCmd("git", cmd, outstream=return_buffer) == 0): - # Seek to the beginning of the output buffer and capture the output. - return_buffer.seek(0) - # read the first 155 characters and replace the - return_string = return_buffer.read(155).replace("\n", " ") - return_buffer.close() - # TODO: figure out if there was more input and append a ... if needed - return return_string.strip() - else: - raise RuntimeError("Unable to read release notes") - - -def _GetSubVersions(old_version: str, current_release: str, curr_hashes: dict, old_hashes: dict): - year, month, major, minor = old_version.split(".") - if len(current_release) < 4: - raise RuntimeError(f"Invalid version of {current_release}") - curr_year = int(current_release[0:4]) - curr_mon = int(current_release[4:]) - differences = [] - same = [] - for repo in curr_hashes: - if repo not in old_hashes: - logging.warning("Skipping comparing " + repo) - continue - if curr_hashes[repo] != old_hashes[repo]: - differences.append(repo) - else: - same.append(repo) - if curr_year != int(year) or curr_mon != int(month): - major = 1 - minor = 1 - elif "OPENSSL" in differences or "MU_TIANO" in differences: - major = int(major) + 1 - minor = 1 - elif len(differences) > 0: - minor = int(minor) + 1 - elif len(same) == 0: # if don't share any of the same repos as the old version - minor = int(minor) + 1 - return "{}.{}".format(major, minor) - - -class SettingsManager(UpdateSettingsManager, CiSetupSettingsManager, BinaryBuildSettingsManager): - def __init__(self): - SCRIPT_PATH = os.path.dirname(os.path.abspath(__file__)) - - WORKSPACE_PATH = os.path.dirname(os.path.dirname(SCRIPT_PATH)) - REQUIRED_REPOS = ['Common/MU_TIANO', - 'Common/MU_PLUS', - "Silicon/Arm/MU_TIANO"] # todo fix this - - MODULE_PKG_PATHS = os.pathsep.join(os.path.join( - WORKSPACE_PATH, pkg_name) for pkg_name in REQUIRED_REPOS) - - self.OUTPUT_DIR = os.path.join(WORKSPACE_PATH, "Build", ".NugetOutput") - self.ws = WORKSPACE_PATH - self.pp = MODULE_PKG_PATHS - self.rr = REQUIRED_REPOS - self.sp = SCRIPT_PATH - self.api_key = None - self.should_dump_version = False - self.release_notes_filename = "release_notes.md" - self.nuget_package_name = "Mu-SharedNetworking" - self.nuget_version = None - pass - - def _CreateReleaseNotes(self, note: str, new_version: str, old_release_notes: list, hashes: dict): - scriptDir = self.sp - - release_notes_path = os.path.join( - scriptDir, self.release_notes_filename) - current_notes_file = open(release_notes_path, "r") - notes = current_notes_file.readlines() - current_notes_file.close() - - notes += ["\n"] - notes += ["## {}- {}\n".format(new_version, note), "\n"] - for repo in hashes: - repo_hash = hashes[repo] - notes += ["{}@{}\n".format(repo, repo_hash)] - notes += ["\n"] - - # write our notes out to the file - current_notes_file = open(release_notes_path, "w") - current_notes_file.writelines(notes) - current_notes_file.writelines(old_release_notes) - current_notes_file.close() - - def _GetOldReleaseNotesAndHashes(self, notes_path: os.PathLike): - # Read in the text file - if not os.path.isfile(notes_path): - raise FileNotFoundError("Unable to find the old release notes") - old_notes_file = open(notes_path, "r") - notes = old_notes_file.readlines() - old_notes_file.close() - version_re = re.compile(r'##\s*\d+\.\d+\.\d+\.\d+') - while len(notes) > 0: # go through the notes until we find a version - if not version_re.match(notes[0]): - del notes[0] - else: - break - old_hashes = {} - hash_re = re.compile(r'([\w_]+)@([\w\d]+)') - for note_line in notes: - hash_match = hash_re.match(note_line) - if hash_match: - repo, commit_hash = hash_match.groups() - repo = str(repo).upper() - if repo not in old_hashes: - old_hashes[repo] = commit_hash - - return (notes, old_hashes) - - def _DownloadNugetPackageVersion(self, package_name: str, version: str, destination: os.PathLike, source=None): - cmd = NugetDependency.GetNugetCmd() - cmd += ["install", package_name] - if source is not None: - cmd += ["-Source", source] - cmd += ["-ExcludeVersion"] - cmd += ["-Version", version] - cmd += ["-Verbosity", "detailed"] - cmd += ["-OutputDirectory", '"' + destination + '"'] - ret = RunCmd(cmd[0], " ".join(cmd[1:])) - if ret != 0: - return False - else: - return True - - def _GetReleaseForCommit(self, commit_hash: str, n: int = 100): - if n > 2000: - logging.error("We couldn't find the release branch that we correspond to") - return "0.0.0.0" - git_dir = os.path.dirname(self.sp) - cmd_args = ["log", '--format="%h %D"', "-n " + str(n)] - return_buffer = StringIO() - RunCmd("git", " ".join(cmd_args), - workingdir=git_dir, outstream=return_buffer) - return_buffer.seek(0) - results = return_buffer.readlines() - return_buffer.close() - log_re = re.compile(r'(release|dev)/(\d{6})') - for log_item in results: - commit = log_item[:11] - branch = log_item[11:].strip() - if len(branch) == 0: - continue - match = log_re.search(branch) - if match: - logging.info( - "Basing our release commit off of commit " + commit) - return match.group(2) - return self._GetReleaseForCommit(commit_hash, n * 2) - - def _GetNextVersion(self, force_version=None): - # first get the last version - # TODO: get the source from the JSON file that configures this - old_version_raw = _GetLatestNugetVersion(self.nuget_package_name) - old_version = NugetDependency.normalize_version(old_version_raw) - logging.info(f"Found old version {old_version}") - # Get a temporary folder to download the nuget package into - temp_nuget_path = tempfile.mkdtemp() - # Download the Nuget Package - self._DownloadNugetPackageVersion( - self.nuget_package_name, old_version, temp_nuget_path) - # Unpack and read the previous release notes, skipping the header, also get hashes - old_notes, old_hashes = self._GetOldReleaseNotesAndHashes(os.path.join( - temp_nuget_path, self.nuget_package_name, self.nuget_package_name, self.release_notes_filename)) - # Get the current hashes of open ssl and ourself - curr_hashes = _GetCommitHashes(self.ws) - # Figure out what release branch we are in - logging.info(curr_hashes) - logging.info("OLD") - logging.info(old_hashes) - current_release = self._GetReleaseForCommit(curr_hashes["MU_BASECORE"]) - # Put that as the first two pieces of our version - if force_version is not None: - new_version = force_version - else: - new_version = current_release[0:4] + \ - "." + current_release[4:] + "." - # Calculate the newest version - new_version += _GetSubVersions(old_version, - current_release, curr_hashes, old_hashes) - # make sure to normalize the version - new_version = NugetDependency.normalize_version(new_version) - if new_version == old_version: - raise RuntimeError( - "We are unable to republish the same version that was published last") - # Create the release note from this branch, currently the commit message on the head? - release_note = _GetReleaseNote() - # Create our release notes, appending the old ones - self._CreateReleaseNotes( - release_note, new_version, old_notes, curr_hashes) - # Clean up the temporary nuget file? - logging.critical("Creating new version:" + new_version) - return new_version - - def GetActiveScopes(self): - ''' get scope ''' - scopes = ("corebuild", "sharednetworking_build", "project_mu", 'edk2-build' ) - # if (GetHostInfo().os == "Linux"): - # scopes += ("gcc_aarch64_linux",) - - return scopes - - def _PublishNuget(self): - # otherwise do the upload - logging.critical("PUBLISHING TO NUGET") - # get the root directory of mu_basecore - scriptDir = self.sp - rootDir = self.ws - build_dir = os.path.join(rootDir, "Build") - - if (self.should_dump_version): - print( - "##vso[task.setvariable variable=NugetPackageVersion;isOutput=true]" + self.nuget_version) - - config_file = "SharedNetworking.config.json" - - if self.api_key is not None: - logging.info("Will attempt to publish as well") - params = "--Operation PackAndPush --ConfigFilePath {0} --Version {1} --InputFolderPath {2} --ApiKey {3}".format( - config_file, self.nuget_version, self.OUTPUT_DIR, self.api_key) - else: - params = "--Operation Pack --ConfigFilePath {0} --Version {1} --InputFolderPath {2} --OutputFolderPath {3}".format( - config_file, self.nuget_version, self.OUTPUT_DIR, build_dir) - # TODO: change this from a runcmd to directly invoking nuget publishing - ret = RunCmd("nuget-publish", params, - capture=True, workingdir=scriptDir) - if ret != 0: - logging.error("Unable to pack/publish nuget package") - return False - logging.critical( - "Finished packaging/publishing Nuget version {0}".format(self.nuget_version)) - return True - - def _CollectNuget(self): - # get the root directory of mu_basecore - scriptDir = self.sp - rootDir = self.ws - # move the EFI's we generated to a folder to upload - logging.info("Running NugetPackager") - output_dir = self.OUTPUT_DIR - shared_networking_build_dir = os.path.realpath( - os.path.join(rootDir, "Build", "SharedNetworkPkg")) - - if not os.path.exists(shared_networking_build_dir): - logging.error( - "We were unable to find the build directory, skipping collecting Nuget build files") - return 1 - - # copy the md file - _CopyFile(scriptDir, output_dir, "SharedNetworking.md") - _CopyFile(scriptDir, output_dir, "release_notes.md") - - list_to_get = ["Tls*", "DnsDxe*", "Http*", "Arp*", "IScsi*", "Mnp*", "Snp*", - "Vlan*", "VConfig*", "Ip*", "Tcp*", "Udp*", "Dhcp*", "Mtft*", "Arp*"] - ending_list = [".efi", ".depex", ".pdb"] - - shared_networking_build_dir_offset = len( - shared_networking_build_dir) + 1 - - for list_item in list_to_get: - for item_ending in ending_list: - item = list_item + item_ending - item_search = os.path.join( - shared_networking_build_dir, "**", self.target + "*", "**", item) - logging.info(f"Searching for {item} = {item_search}") - for found_item in glob.iglob(item_search, recursive=True): - _MoveArchTargetSpecificFile( - found_item, shared_networking_build_dir_offset, output_dir) - - build_dir_txt_search = os.path.join( - shared_networking_build_dir, "**", "BUILD_REPORT.txt") - for txt in glob.iglob(build_dir_txt_search, recursive=True): - file_name = os.path.basename(txt) - srcDir = os.path.dirname(txt) - shutil.copyfile(os.path.join(srcDir, file_name), os.path.join( - output_dir, "{}_{}_{}".format(self.target, self.arch, file_name))) - - fv_search = os.path.join(shared_networking_build_dir, - self.target + "*", "FV", "FVDXE.Fv") - dest_path = os.path.join(output_dir, self.target, self.arch) - # copy the FV files - version = self.nuget_version - for found_item in glob.iglob(fv_search, recursive=True): - src_dir = os.path.dirname(found_item) - fv_name = os.path.basename(found_item) - #fv_name_parts = os.path.splitext(fv_name) - #fv_new_name = fv_name_parts[0] + "_" + version + fv_name_parts[1] - logging.info("Copying {} to {}".format(found_item, dest_path)) - _CopyFile(src_dir, dest_path, fv_name) # , fv_new_name) - - return 0 - - def _GetOutputDir(self): - return os.path.join(self.ws, "Build", ".NugetOutput") - - def PreFirstBuildHook(self): - output_dir = self.OUTPUT_DIR - try: - if os.path.exists(output_dir): - logging.warning(f"Deleting {output_dir}") - shutil.rmtree(output_dir, ignore_errors=True) - os.makedirs(output_dir) - except: - pass - - self.nuget_version = self._GetNextVersion(self.nuget_version) - - return 0 - - def PostBuildHook(self, ret): - if ret == 0: - ret = self._CollectNuget() - if ret != 0: - logging.error("Error occured in post build hook") - raise RuntimeError("Error occured in post build hook") - return ret - - def PostFinalBuildHook(self, ret): - if ret != 0: - logging.error( - "There was failure along the way aborting NUGET publish") - return - self._PublishNuget() - - def GetWorkspaceRoot(self): - ''' get WorkspacePath ''' - return self.ws - - def GetModulePkgsPath(self): - ''' get module packages path ''' - return self.pp - - def GetRequiredRepos(self): - ''' get required repos ''' - return self.rr - - def GetName(self): - return "SharedNetworking" - - def GetPackagesSupported(self): - return "NetworkPkg" - - def GetArchitecturesSupported(self): - return ["X64", "IA32", "AARCH64"] - - def GetTargetsSupported(self): - return ["DEBUG", "RELEASE"] - - def GetConfigurations(self): - TARGETS = self.GetTargetsSupported() - ARCHS = self.GetArchitecturesSupported() - # combine options together - for target in TARGETS: - for arch in ARCHS: - self.target = target - self.arch = arch - yield({"TARGET": target, "TARGET_ARCH": arch, "ACTIVE_PLATFORM": "NetworkPkg/SharedNetworking/SharedNetworkPkg.dsc"}) - - def GetDependencies(self): - return [ - { - "Path": "Silicon/Arm/MU_TIANO", - "Url": "https://github.com/Microsoft/mu_silicon_arm_tiano.git", - "Branch": "release/202002" - }, - { - "Path": "Common/MU_TIANO", - "Url": "https://github.com/Microsoft/mu_tiano_plus.git", - "Branch": "release/202002" - }, - { - "Path": "Common/MU_PLUS", - "Url": "https://github.com/Microsoft/mu_plus.git", - "Branch": "release/202002" - } - ] - - def AddCommandLineOptions(self, parserObj): - ''' Add command line options to the argparser ''' - # TODO Add this parameter to adjust the scopes so we don't pull in the realtek ext dep - parserObj.add_argument('-a' '--api_key', dest='api_key', - type=str, help='nuget api key used to upload the package') - - parserObj.add_argument('-d', '--dump_version', '--dump-version', dest='dump_version', - type=bool, default=False, help='Should I dump nuget information?') - parserObj.add_argument("-nv", "--nuget_version", "--nuget-version", dest="nug_ver", - type=str, default=None, help="Nuget Version for package") - - def RetrieveCommandLineOptions(self, args): - ''' Retrieve command line options from the argparser ''' - shell_environment.GetBuildVars().SetValue("TOOL_CHAIN_TAG", "VS2017", "Set default") - if args.api_key is not None: - self.api_key = args.api_key - print("Using API KEY") - self.nuget_version = args.nug_ver - - self.should_dump_version = args.dump_version - - -def main(): - import argparse - import sys - import os - from edk2toolext.invocables.edk2_update import Edk2Update - from edk2toolext.invocables.edk2_ci_setup import Edk2CiBuildSetup - from edk2toolext.invocables.edk2_platform_build import Edk2PlatformBuild - import DriverBuilder - print("Invoking Stuart") - print(" ) _ _") - print(" ( (^)-~-(^)") - print("__,-.\_( 0 0 )__,-.___") - print(" 'W' \ / 'W'") - print(" >o<") - SCRIPT_PATH = os.path.relpath(__file__) - parser = argparse.ArgumentParser(add_help=False) - parse_group = parser.add_mutually_exclusive_group() - parse_group.add_argument("--update", "--UPDATE", - action='store_true', help="Invokes stuart_update") - parse_group.add_argument("--setup", "--SETUP", - action='store_true', help="Invokes stuart_setup") - args, remaining = parser.parse_known_args() - new_args = ["stuart", "-c", SCRIPT_PATH] - new_args = new_args + remaining - sys.argv = new_args - if args.setup: - print("Running stuart_ci_setup -c " + SCRIPT_PATH) - Edk2CiBuildSetup().Invoke() - elif args.update: - print("Running stuart_update -c " + SCRIPT_PATH) - Edk2Update().Invoke() - else: - print("Running DriverBuilder -c " + SCRIPT_PATH) - DriverBuilder.Edk2BinaryBuild().Invoke() - -if __name__ == "__main__": - import SharedNetworkSettings +## +# Script to Build Shared Crypto Driver +# Copyright Microsoft Corporation, 2019 +# +# This is to build the SharedNetworking binaries for NuGet publishing +## +import os +from edk2toolext.environment import shell_environment +import logging +import shutil +from edk2toolext.environment.uefi_build import UefiBuilder +from edk2toolext.invocables.edk2_ci_setup import CiSetupSettingsManager +from edk2toolext.invocables.edk2_update import UpdateSettingsManager +from edk2toollib.utility_functions import RunCmd +from edk2toollib.utility_functions import RunPythonScript +from edk2toolext.environment.extdeptypes.nuget_dependency import NugetDependency +import glob +from io import StringIO +import re +import tempfile +try: + from DriverBuilder import BinaryBuildSettingsManager +except Exception: + class BinaryBuildSettingsManager: + def __init__(): + raise RuntimeError("You shouldn't be including this") + pass +from edk2toollib.utility_functions import GetHostInfo + +# +# ========================================================================== +# PLATFORM BUILD ENVIRONMENT CONFIGURATION +# + + +def _CopyFile(srcDir, destDir, file_name, new_name=None): + if new_name is None: + new_name = file_name + shutil.copyfile(os.path.join(srcDir, file_name), + os.path.join(destDir, new_name)) + + +def _MoveArchTargetSpecificFile(binary, offset, output_dir): + binary_path = binary[offset:] + binary_name = os.path.basename(binary) + binary_folder = os.path.dirname(binary) + arch = _GetArchitecture(binary_path) + target = _GetTarget(binary_path) + if target is None: + raise FileExistsError("Unknown file {0}".format(binary)) + dest_path = os.path.join(output_dir, target, arch) + dest_filepath = os.path.join(dest_path, binary_name) + if os.path.exists(dest_filepath): + #logging.warning("Skipping {0}: {1} from {2}".format(binary_name, dest_filepath, binary)) + return + + if not os.path.exists(dest_path): + os.makedirs(dest_path) + # logging.warning("Copying {0}: {1}".format(binary_name,binary)) + _CopyFile(binary_folder, dest_path, binary_name) + + +def _GetArchitecture(path: str): + path = os.path.normpath(path) + path_parts = path.split(os.path.sep) + return path_parts[1] + + +def _GetTarget(path: str): + path = os.path.normpath(path) + path_parts = path.split(os.path.sep) + target = path_parts[0] + + if "_" in target: + return target.split("_")[0] + return None + + +def _GetCommitHashes(root_dir: os.PathLike): + # Recursively looks at every .git and gets the commit from there + search_path = os.path.join(root_dir, "**", ".git") + logging.info(f"Searching {search_path} for git repos") + search = glob.iglob(search_path, recursive=True) + found_repos = {} + cmd_args = "rev-parse HEAD" + for git_path in search: + git_path_dir = os.path.dirname(git_path) + if git_path_dir == root_dir: + git_repo_name = "MU_BASECORE" + else: + git_repo_name = os.path.relpath(git_path_dir, root_dir) + git_repo_name = git_repo_name.upper() + if git_repo_name in found_repos: + raise RuntimeError( + f"we've already found this repo before {git_repo_name} {git_path_dir}") + # read the git hash for this repo + return_buffer = StringIO() + RunCmd("git", cmd_args, workingdir=git_path_dir, outstream=return_buffer) + commit_hash = return_buffer.getvalue().strip() + return_buffer.close() + found_repos[git_repo_name] = commit_hash + return found_repos + +# Functions for getting the next nuget version + + +def _GetLatestNugetVersion(package_name, source=None): + cmd = NugetDependency.GetNugetCmd() + cmd += ["list"] + cmd += [package_name] + if source is not None: + cmd += ["-Source", source] + return_buffer = StringIO() + if (RunCmd(cmd[0], " ".join(cmd[1:]), outstream=return_buffer) == 0): + # Seek to the beginning of the output buffer and capture the output. + return_buffer.seek(0) + return_string = return_buffer.readlines() + return_buffer.close() + for line in return_string: + line = line.strip() + if line.startswith(package_name): + return line.replace(package_name, "").strip() + else: + return "0.0.0.0" + + +def _GetReleaseNote(): + cmd = "log --format=%B -n 1 HEAD" + return_buffer = StringIO() + if (RunCmd("git", cmd, outstream=return_buffer) == 0): + # Seek to the beginning of the output buffer and capture the output. + return_buffer.seek(0) + # read the first 155 characters and replace the + return_string = return_buffer.read(155).replace("\n", " ") + return_buffer.close() + # TODO: figure out if there was more input and append a ... if needed + return return_string.strip() + else: + raise RuntimeError("Unable to read release notes") + + +def _GetSubVersions(old_version: str, current_release: str, curr_hashes: dict, old_hashes: dict): + year, month, major, minor = old_version.split(".") + if len(current_release) < 4: + raise RuntimeError(f"Invalid version of {current_release}") + curr_year = int(current_release[0:4]) + curr_mon = int(current_release[4:]) + differences = [] + same = [] + for repo in curr_hashes: + if repo not in old_hashes: + logging.warning("Skipping comparing " + repo) + continue + if curr_hashes[repo] != old_hashes[repo]: + differences.append(repo) + else: + same.append(repo) + if curr_year != int(year) or curr_mon != int(month): + major = 1 + minor = 1 + elif "OPENSSL" in differences or "MU_TIANO" in differences: + major = int(major) + 1 + minor = 1 + elif len(differences) > 0: + minor = int(minor) + 1 + elif len(same) == 0: # if don't share any of the same repos as the old version + minor = int(minor) + 1 + return "{}.{}".format(major, minor) + + +class SettingsManager(UpdateSettingsManager, CiSetupSettingsManager, BinaryBuildSettingsManager): + def __init__(self): + SCRIPT_PATH = os.path.dirname(os.path.abspath(__file__)) + + WORKSPACE_PATH = os.path.dirname(os.path.dirname(SCRIPT_PATH)) + REQUIRED_REPOS = ['Common/MU_TIANO', + 'Common/MU_PLUS', + "Silicon/Arm/MU_TIANO"] # todo fix this + + MODULE_PKG_PATHS = os.pathsep.join(os.path.join( + WORKSPACE_PATH, pkg_name) for pkg_name in REQUIRED_REPOS) + + self.OUTPUT_DIR = os.path.join(WORKSPACE_PATH, "Build", ".NugetOutput") + self.ws = WORKSPACE_PATH + self.pp = MODULE_PKG_PATHS + self.rr = REQUIRED_REPOS + self.sp = SCRIPT_PATH + self.api_key = None + self.should_dump_version = False + self.release_notes_filename = "release_notes.md" + self.nuget_package_name = "Mu-SharedNetworking" + self.nuget_version = None + pass + + def _CreateReleaseNotes(self, note: str, new_version: str, old_release_notes: list, hashes: dict): + scriptDir = self.sp + + release_notes_path = os.path.join( + scriptDir, self.release_notes_filename) + current_notes_file = open(release_notes_path, "r") + notes = current_notes_file.readlines() + current_notes_file.close() + + notes += ["\n"] + notes += ["## {}- {}\n".format(new_version, note), "\n"] + for repo in hashes: + repo_hash = hashes[repo] + notes += ["{}@{}\n".format(repo, repo_hash)] + notes += ["\n"] + + # write our notes out to the file + current_notes_file = open(release_notes_path, "w") + current_notes_file.writelines(notes) + current_notes_file.writelines(old_release_notes) + current_notes_file.close() + + def _GetOldReleaseNotesAndHashes(self, notes_path: os.PathLike): + # Read in the text file + if not os.path.isfile(notes_path): + raise FileNotFoundError("Unable to find the old release notes") + old_notes_file = open(notes_path, "r") + notes = old_notes_file.readlines() + old_notes_file.close() + version_re = re.compile(r'##\s*\d+\.\d+\.\d+\.\d+') + while len(notes) > 0: # go through the notes until we find a version + if not version_re.match(notes[0]): + del notes[0] + else: + break + old_hashes = {} + hash_re = re.compile(r'([\w_]+)@([\w\d]+)') + for note_line in notes: + hash_match = hash_re.match(note_line) + if hash_match: + repo, commit_hash = hash_match.groups() + repo = str(repo).upper() + if repo not in old_hashes: + old_hashes[repo] = commit_hash + + return (notes, old_hashes) + + def _DownloadNugetPackageVersion(self, package_name: str, version: str, destination: os.PathLike, source=None): + cmd = NugetDependency.GetNugetCmd() + cmd += ["install", package_name] + if source is not None: + cmd += ["-Source", source] + cmd += ["-ExcludeVersion"] + cmd += ["-Version", version] + cmd += ["-Verbosity", "detailed"] + cmd += ["-OutputDirectory", '"' + destination + '"'] + ret = RunCmd(cmd[0], " ".join(cmd[1:])) + if ret != 0: + return False + else: + return True + + def _GetReleaseForCommit(self, commit_hash: str, n: int = 100): + if n > 2000: + logging.error("We couldn't find the release branch that we correspond to") + return "0.0.0.0" + git_dir = os.path.dirname(self.sp) + cmd_args = ["log", '--format="%h %D"', "-n " + str(n)] + return_buffer = StringIO() + RunCmd("git", " ".join(cmd_args), + workingdir=git_dir, outstream=return_buffer) + return_buffer.seek(0) + results = return_buffer.readlines() + return_buffer.close() + log_re = re.compile(r'(release|dev)/(\d{6})') + for log_item in results: + commit = log_item[:11] + branch = log_item[11:].strip() + if len(branch) == 0: + continue + match = log_re.search(branch) + if match: + logging.info( + "Basing our release commit off of commit " + commit) + return match.group(2) + return self._GetReleaseForCommit(commit_hash, n * 2) + + def _GetNextVersion(self, force_version=None): + # first get the last version + # TODO: get the source from the JSON file that configures this + old_version_raw = _GetLatestNugetVersion(self.nuget_package_name) + old_version = NugetDependency.normalize_version(old_version_raw) + logging.info(f"Found old version {old_version}") + # Get a temporary folder to download the nuget package into + temp_nuget_path = tempfile.mkdtemp() + # Download the Nuget Package + self._DownloadNugetPackageVersion( + self.nuget_package_name, old_version, temp_nuget_path) + # Unpack and read the previous release notes, skipping the header, also get hashes + old_notes, old_hashes = self._GetOldReleaseNotesAndHashes(os.path.join( + temp_nuget_path, self.nuget_package_name, self.nuget_package_name, self.release_notes_filename)) + # Get the current hashes of open ssl and ourself + curr_hashes = _GetCommitHashes(self.ws) + # Figure out what release branch we are in + logging.info(curr_hashes) + logging.info("OLD") + logging.info(old_hashes) + current_release = self._GetReleaseForCommit(curr_hashes["MU_BASECORE"]) + # Put that as the first two pieces of our version + if force_version is not None: + new_version = force_version + else: + new_version = current_release[0:4] + \ + "." + current_release[4:] + "." + # Calculate the newest version + new_version += _GetSubVersions(old_version, + current_release, curr_hashes, old_hashes) + # make sure to normalize the version + new_version = NugetDependency.normalize_version(new_version) + if new_version == old_version: + raise RuntimeError( + "We are unable to republish the same version that was published last") + # Create the release note from this branch, currently the commit message on the head? + release_note = _GetReleaseNote() + # Create our release notes, appending the old ones + self._CreateReleaseNotes( + release_note, new_version, old_notes, curr_hashes) + # Clean up the temporary nuget file? + logging.critical("Creating new version:" + new_version) + return new_version + + def GetActiveScopes(self): + ''' get scope ''' + scopes = ("corebuild", "sharednetworking_build", "project_mu", 'edk2-build' ) + # if (GetHostInfo().os == "Linux"): + # scopes += ("gcc_aarch64_linux",) + + return scopes + + def _PublishNuget(self): + # otherwise do the upload + logging.critical("PUBLISHING TO NUGET") + # get the root directory of mu_basecore + scriptDir = self.sp + rootDir = self.ws + build_dir = os.path.join(rootDir, "Build") + + if (self.should_dump_version): + print( + "##vso[task.setvariable variable=NugetPackageVersion;isOutput=true]" + self.nuget_version) + + config_file = "SharedNetworking.config.json" + + if self.api_key is not None: + logging.info("Will attempt to publish as well") + params = "--Operation PackAndPush --ConfigFilePath {0} --Version {1} --InputFolderPath {2} --ApiKey {3}".format( + config_file, self.nuget_version, self.OUTPUT_DIR, self.api_key) + else: + params = "--Operation Pack --ConfigFilePath {0} --Version {1} --InputFolderPath {2} --OutputFolderPath {3}".format( + config_file, self.nuget_version, self.OUTPUT_DIR, build_dir) + # TODO: change this from a runcmd to directly invoking nuget publishing + ret = RunCmd("nuget-publish", params, + capture=True, workingdir=scriptDir) + if ret != 0: + logging.error("Unable to pack/publish nuget package") + return False + logging.critical( + "Finished packaging/publishing Nuget version {0}".format(self.nuget_version)) + return True + + def _CollectNuget(self): + # get the root directory of mu_basecore + scriptDir = self.sp + rootDir = self.ws + # move the EFI's we generated to a folder to upload + logging.info("Running NugetPackager") + output_dir = self.OUTPUT_DIR + shared_networking_build_dir = os.path.realpath( + os.path.join(rootDir, "Build", "SharedNetworkPkg")) + + if not os.path.exists(shared_networking_build_dir): + logging.error( + "We were unable to find the build directory, skipping collecting Nuget build files") + return 1 + + # copy the md file + _CopyFile(scriptDir, output_dir, "SharedNetworking.md") + _CopyFile(scriptDir, output_dir, "release_notes.md") + + list_to_get = ["Tls*", "DnsDxe*", "Http*", "Arp*", "IScsi*", "Mnp*", "Snp*", + "Vlan*", "VConfig*", "Ip*", "Tcp*", "Udp*", "Dhcp*", "Mtft*", "Arp*"] + ending_list = [".efi", ".depex", ".pdb"] + + shared_networking_build_dir_offset = len( + shared_networking_build_dir) + 1 + + for list_item in list_to_get: + for item_ending in ending_list: + item = list_item + item_ending + item_search = os.path.join( + shared_networking_build_dir, "**", self.target + "*", "**", item) + logging.info(f"Searching for {item} = {item_search}") + for found_item in glob.iglob(item_search, recursive=True): + _MoveArchTargetSpecificFile( + found_item, shared_networking_build_dir_offset, output_dir) + + build_dir_txt_search = os.path.join( + shared_networking_build_dir, "**", "BUILD_REPORT.txt") + for txt in glob.iglob(build_dir_txt_search, recursive=True): + file_name = os.path.basename(txt) + srcDir = os.path.dirname(txt) + shutil.copyfile(os.path.join(srcDir, file_name), os.path.join( + output_dir, "{}_{}_{}".format(self.target, self.arch, file_name))) + + fv_search = os.path.join(shared_networking_build_dir, + self.target + "*", "FV", "FVDXE.Fv") + dest_path = os.path.join(output_dir, self.target, self.arch) + # copy the FV files + version = self.nuget_version + for found_item in glob.iglob(fv_search, recursive=True): + src_dir = os.path.dirname(found_item) + fv_name = os.path.basename(found_item) + #fv_name_parts = os.path.splitext(fv_name) + #fv_new_name = fv_name_parts[0] + "_" + version + fv_name_parts[1] + logging.info("Copying {} to {}".format(found_item, dest_path)) + _CopyFile(src_dir, dest_path, fv_name) # , fv_new_name) + + return 0 + + def _GetOutputDir(self): + return os.path.join(self.ws, "Build", ".NugetOutput") + + def PreFirstBuildHook(self): + output_dir = self.OUTPUT_DIR + try: + if os.path.exists(output_dir): + logging.warning(f"Deleting {output_dir}") + shutil.rmtree(output_dir, ignore_errors=True) + os.makedirs(output_dir) + except: + pass + + self.nuget_version = self._GetNextVersion(self.nuget_version) + + return 0 + + def PostBuildHook(self, ret): + if ret == 0: + ret = self._CollectNuget() + if ret != 0: + logging.error("Error occured in post build hook") + raise RuntimeError("Error occured in post build hook") + return ret + + def PostFinalBuildHook(self, ret): + if ret != 0: + logging.error( + "There was failure along the way aborting NUGET publish") + return + self._PublishNuget() + + def GetWorkspaceRoot(self): + ''' get WorkspacePath ''' + return self.ws + + def GetModulePkgsPath(self): + ''' get module packages path ''' + return self.pp + + def GetRequiredRepos(self): + ''' get required repos ''' + return self.rr + + def GetName(self): + return "SharedNetworking" + + def GetPackagesSupported(self): + return "NetworkPkg" + + def GetArchitecturesSupported(self): + return ["X64", "IA32", "AARCH64"] + + def GetTargetsSupported(self): + return ["DEBUG", "RELEASE"] + + def GetConfigurations(self): + TARGETS = self.GetTargetsSupported() + ARCHS = self.GetArchitecturesSupported() + # combine options together + for target in TARGETS: + for arch in ARCHS: + self.target = target + self.arch = arch + yield({"TARGET": target, "TARGET_ARCH": arch, "ACTIVE_PLATFORM": "NetworkPkg/SharedNetworking/SharedNetworkPkg.dsc"}) + + def GetDependencies(self): + return [ + { + "Path": "Silicon/Arm/MU_TIANO", + "Url": "https://github.com/Microsoft/mu_silicon_arm_tiano.git", + "Branch": "release/202002" + }, + { + "Path": "Common/MU_TIANO", + "Url": "https://github.com/Microsoft/mu_tiano_plus.git", + "Branch": "release/202002" + }, + { + "Path": "Common/MU_PLUS", + "Url": "https://github.com/Microsoft/mu_plus.git", + "Branch": "release/202002" + } + ] + + def AddCommandLineOptions(self, parserObj): + ''' Add command line options to the argparser ''' + # TODO Add this parameter to adjust the scopes so we don't pull in the realtek ext dep + parserObj.add_argument('-a' '--api_key', dest='api_key', + type=str, help='nuget api key used to upload the package') + + parserObj.add_argument('-d', '--dump_version', '--dump-version', dest='dump_version', + type=bool, default=False, help='Should I dump nuget information?') + parserObj.add_argument("-nv", "--nuget_version", "--nuget-version", dest="nug_ver", + type=str, default=None, help="Nuget Version for package") + + def RetrieveCommandLineOptions(self, args): + ''' Retrieve command line options from the argparser ''' + shell_environment.GetBuildVars().SetValue("TOOL_CHAIN_TAG", "VS2017", "Set default") + if args.api_key is not None: + self.api_key = args.api_key + print("Using API KEY") + self.nuget_version = args.nug_ver + + self.should_dump_version = args.dump_version + + +def main(): + import argparse + import sys + import os + from edk2toolext.invocables.edk2_update import Edk2Update + from edk2toolext.invocables.edk2_ci_setup import Edk2CiBuildSetup + from edk2toolext.invocables.edk2_platform_build import Edk2PlatformBuild + import DriverBuilder + print("Invoking Stuart") + print(" ) _ _") + print(" ( (^)-~-(^)") + print("__,-.\_( 0 0 )__,-.___") + print(" 'W' \ / 'W'") + print(" >o<") + SCRIPT_PATH = os.path.relpath(__file__) + parser = argparse.ArgumentParser(add_help=False) + parse_group = parser.add_mutually_exclusive_group() + parse_group.add_argument("--update", "--UPDATE", + action='store_true', help="Invokes stuart_update") + parse_group.add_argument("--setup", "--SETUP", + action='store_true', help="Invokes stuart_setup") + args, remaining = parser.parse_known_args() + new_args = ["stuart", "-c", SCRIPT_PATH] + new_args = new_args + remaining + sys.argv = new_args + if args.setup: + print("Running stuart_ci_setup -c " + SCRIPT_PATH) + Edk2CiBuildSetup().Invoke() + elif args.update: + print("Running stuart_update -c " + SCRIPT_PATH) + Edk2Update().Invoke() + else: + print("Running DriverBuilder -c " + SCRIPT_PATH) + DriverBuilder.Edk2BinaryBuild().Invoke() + +if __name__ == "__main__": + import SharedNetworkSettings SharedNetworkSettings.main() # otherwise we're in __main__ context \ No newline at end of file diff --git a/NetworkPkg/SharedNetworking/SharedNetworking.config.json b/NetworkPkg/SharedNetworking/SharedNetworking.config.json index d6c3135692..d198f73864 100644 --- a/NetworkPkg/SharedNetworking/SharedNetworking.config.json +++ b/NetworkPkg/SharedNetworking/SharedNetworking.config.json @@ -1,9 +1,9 @@ -{ - "name": "Mu-SharedNetworking", - "author_string": "ProjectMu, TianoCore", - "server_url": "https://api.nuget.org/v3/index.json", - "project_url": "https://aka.ms/projectmu", - "license_url": "https://github.com/Microsoft/mu/blob/master/LICENSE", - "description_string": "The SharedNetworking Binary Package for Project Mu", - "copyright_string": "Copyright 2019" +{ + "name": "Mu-SharedNetworking", + "author_string": "ProjectMu, TianoCore", + "server_url": "https://api.nuget.org/v3/index.json", + "project_url": "https://aka.ms/projectmu", + "license_url": "https://github.com/Microsoft/mu/blob/master/LICENSE", + "description_string": "The SharedNetworking Binary Package for Project Mu", + "copyright_string": "Copyright 2019" } \ No newline at end of file diff --git a/NetworkPkg/SharedNetworking/SharedNetworking.md b/NetworkPkg/SharedNetworking/SharedNetworking.md index 19ff02e7b3..02b6874ad3 100644 --- a/NetworkPkg/SharedNetworking/SharedNetworking.md +++ b/NetworkPkg/SharedNetworking/SharedNetworking.md @@ -1,95 +1,95 @@ -# Shared Networking DXE - -## What is it - -Shared Networking is a packaged versions of networking components from EDK II. -Similar to SharedCrypto (see the SharedCryptoPkg), it precompiles certain -components and allows them to be included in a platform without having to build -the underlying library. - -## How it works - -Since many parts of the network simply publish a protocol (like TlsDxe), it was -fairly trivial to compile that into an EFI. This EFI is then downloaded via a -NuGet External Dependency (see SharedNetworking_ext_dep.json). Versions are -modified in a similar way to SharedCrypto. - -### Versioning - -A typical version consists of 4 numbers. The year, the month of the EDK II -release, the revision number, and the build number. An example of this would be -_2019.03.02.01_, which would translate to EDK II 1903 release, the second -revision and the first build. This means that there were two code changes within -1903 (either in BaseCryptLib or OpenSSL). Release notes will be provided on the -NuGet package page and on this repo. Build numbers are reved whenever there -needs to be a recompiled binary due to a mistake on our part or a build flag is -tweaked. - -## How to use it - -There are two ways to use SharedNetworking. For first way is to use the FV, -which contains all the networking components needed. The second is to replace -individual components with INF's. - -## DSC/INF way - -Including it in your platform is easy peezy lemon squeezy. In fact, you only -need three changes. In the example below we show X64, which happens to -correspond with DXE but that could easily be changed. Look at your platform for -where Networking is already defined. One thing to note is that each binary is -released for two targets, RELEASE and DEBUG. Make sure to include the right INF. - -### DSC Changes - -Parts need to be replaced on a compoenent by component basis. For example, here -is how to move over TlsDxe. You need to remove the reference to TLSLib since we -no longer need it (the only consumer is TlsDxe). Then switch the component to -the Shared version of TLS. It looks like this: - -```edk2_dsc -[LibraryClasses.X64] - #TlsLib|CryptoPkg/Library/TlsLib/TlsLib.inf # remove this line - -[Components.X64] - NetworkPkg/SharedNetworking/TlsDxe.$(TARGET).inf -``` - -### FDF Changes - -```edk2_fdf - -[FV.FVDXE] - INF NetworkPkg/SharedNetworking/TlsDxe.$(TARGET).inf # Shared_TLS instead of TlsDxe - ... -``` - -## FV way - -This way is still under development, so it maybe subject to change. In your FDF, -add these lines. - -```edk2_fdf -[FV.FVDXE] - -FILE FV_IMAGE = {GUID} { - SECTION FV_IMAGE = NetworkPkg/SharedNetworking/Mu-SharedNetworking_extdep/$(TARGET)/{ARCH of your platform}/FVDXE.fv # Shared_Networking - SECTION UI = "SharedNetworking" -} -``` - -With {GUID} being a guid you generated. We use -E205F779-07E3-4B64-A2E2-EEDE717B0F59. {Arch of your platform} being the platform -you're using. We currently support IA32, X64, and AARCH64. as supposered values -You'll also need to remove the networking components that were already in your -FDF. - -## Why to Use SharedNetworking - -Depending on your platform, it could net you some small space savings depending -on your linker. The main advantage is that when used with SharedCrypto, you can -remove the need to compile OpenSSL, reducing compile times. - -## Questions - -If you have any questions about anything in this package or the universe in -general, feel free to comment on our Github or contact the Project Mu team. +# Shared Networking DXE + +## What is it + +Shared Networking is a packaged versions of networking components from EDK II. +Similar to SharedCrypto (see the SharedCryptoPkg), it precompiles certain +components and allows them to be included in a platform without having to build +the underlying library. + +## How it works + +Since many parts of the network simply publish a protocol (like TlsDxe), it was +fairly trivial to compile that into an EFI. This EFI is then downloaded via a +NuGet External Dependency (see SharedNetworking_ext_dep.json). Versions are +modified in a similar way to SharedCrypto. + +### Versioning + +A typical version consists of 4 numbers. The year, the month of the EDK II +release, the revision number, and the build number. An example of this would be +_2019.03.02.01_, which would translate to EDK II 1903 release, the second +revision and the first build. This means that there were two code changes within +1903 (either in BaseCryptLib or OpenSSL). Release notes will be provided on the +NuGet package page and on this repo. Build numbers are reved whenever there +needs to be a recompiled binary due to a mistake on our part or a build flag is +tweaked. + +## How to use it + +There are two ways to use SharedNetworking. For first way is to use the FV, +which contains all the networking components needed. The second is to replace +individual components with INF's. + +## DSC/INF way + +Including it in your platform is easy peezy lemon squeezy. In fact, you only +need three changes. In the example below we show X64, which happens to +correspond with DXE but that could easily be changed. Look at your platform for +where Networking is already defined. One thing to note is that each binary is +released for two targets, RELEASE and DEBUG. Make sure to include the right INF. + +### DSC Changes + +Parts need to be replaced on a compoenent by component basis. For example, here +is how to move over TlsDxe. You need to remove the reference to TLSLib since we +no longer need it (the only consumer is TlsDxe). Then switch the component to +the Shared version of TLS. It looks like this: + +```edk2_dsc +[LibraryClasses.X64] + #TlsLib|CryptoPkg/Library/TlsLib/TlsLib.inf # remove this line + +[Components.X64] + NetworkPkg/SharedNetworking/TlsDxe.$(TARGET).inf +``` + +### FDF Changes + +```edk2_fdf + +[FV.FVDXE] + INF NetworkPkg/SharedNetworking/TlsDxe.$(TARGET).inf # Shared_TLS instead of TlsDxe + ... +``` + +## FV way + +This way is still under development, so it maybe subject to change. In your FDF, +add these lines. + +```edk2_fdf +[FV.FVDXE] + +FILE FV_IMAGE = {GUID} { + SECTION FV_IMAGE = NetworkPkg/SharedNetworking/Mu-SharedNetworking_extdep/$(TARGET)/{ARCH of your platform}/FVDXE.fv # Shared_Networking + SECTION UI = "SharedNetworking" +} +``` + +With {GUID} being a guid you generated. We use +E205F779-07E3-4B64-A2E2-EEDE717B0F59. {Arch of your platform} being the platform +you're using. We currently support IA32, X64, and AARCH64. as supposered values +You'll also need to remove the networking components that were already in your +FDF. + +## Why to Use SharedNetworking + +Depending on your platform, it could net you some small space savings depending +on your linker. The main advantage is that when used with SharedCrypto, you can +remove the need to compile OpenSSL, reducing compile times. + +## Questions + +If you have any questions about anything in this package or the universe in +general, feel free to comment on our Github or contact the Project Mu team. diff --git a/NetworkPkg/SharedNetworking/SharedNetworking_ext_dep.json b/NetworkPkg/SharedNetworking/SharedNetworking_ext_dep.json index 02aedf7789..eef8bfe30d 100644 --- a/NetworkPkg/SharedNetworking/SharedNetworking_ext_dep.json +++ b/NetworkPkg/SharedNetworking/SharedNetworking_ext_dep.json @@ -1,8 +1,8 @@ -{ - "scope": "global-disabled", - "type": "nuget", - "name": "Mu-SharedNetworking", - "source": "https://api.nuget.org/v3/index.json", - "version": "2021.02.1", - "flags": [] +{ + "scope": "global-disabled", + "type": "nuget", + "name": "Mu-SharedNetworking", + "source": "https://api.nuget.org/v3/index.json", + "version": "2021.02.1", + "flags": [] } \ No newline at end of file diff --git a/NetworkPkg/SharedNetworking/TcpDxe.DEBUG.inf b/NetworkPkg/SharedNetworking/TcpDxe.DEBUG.inf index fc1249bab9..fc0a9ce39a 100644 --- a/NetworkPkg/SharedNetworking/TcpDxe.DEBUG.inf +++ b/NetworkPkg/SharedNetworking/TcpDxe.DEBUG.inf @@ -1,64 +1,64 @@ -## @file -# TCPv4 I/O and TCPv6 I/O services. -# -# This module provides EFI TCPv4 Protocol and EFI TCPv6 Protocol to send and receive data stream. -# It might provide TCPv4 Protocol or TCPv6 Protocol or both of them that depends on which network -# stack has been loaded in system. This driver supports both IPv4 and IPv6 network stack. -# -# Copyright (c) 2009 - 2018, Intel Corporation. All rights reserved.
-# -# This program and the accompanying materials -# are licensed and made available under the terms and conditions of the BSD License -# which accompanies this distribution. The full text of the license may be found at -# http://opensource.org/licenses/bsd-license.php. -# -# THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS, -# WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED. -# -## - -[Defines] - INF_VERSION = 0x0001001B - BASE_NAME = SharedTcpDxeDebug - FILE_GUID = D36A870A-972D-4366-B39E-509431A149C9 - MODULE_TYPE = UEFI_DRIVER - VERSION_STRING = 1.0 - ENTRY_POINT = TcpDriverEntryPoint - UNLOAD_IMAGE = NetLibDefaultUnload - MODULE_UNI_FILE = TcpDxe.uni - -# -# VALID_ARCHITECTURES = IA32 X64# - - -[Binaries.X64] - PE32|Mu-SharedNetworking_extdep/DEBUG/X64/TcpDxe.efi|DEBUG - -[Binaries.IA32] - PE32|Mu-SharedNetworking_extdep/DEBUG/IA32/TcpDxe.efi|DEBUG - -[Binaries.AARCH64] - PE32|Mu-SharedNetworking_extdep/DEBUG/AARCH64/TcpDxe.efi|DEBUG - -[Packages] - MdePkg/MdePkg.dec - MdeModulePkg/MdeModulePkg.dec - -[Protocols] - ## SOMETIMES_CONSUMES - ## SOMETIMES_PRODUCES - gEfiDevicePathProtocolGuid - gEfiIp4ProtocolGuid ## TO_START - gEfiIp4ServiceBindingProtocolGuid ## TO_START - gEfiTcp4ProtocolGuid ## BY_START - gEfiTcp4ServiceBindingProtocolGuid ## BY_START - gEfiIp6ProtocolGuid ## TO_START - gEfiIp6ServiceBindingProtocolGuid ## TO_START - gEfiTcp6ProtocolGuid ## BY_START - gEfiTcp6ServiceBindingProtocolGuid ## BY_START - -[UserExtensions.TianoCore."ExtraFiles"] - TcpDxeExtra.uni - -[Depex] - TRUE +## @file +# TCPv4 I/O and TCPv6 I/O services. +# +# This module provides EFI TCPv4 Protocol and EFI TCPv6 Protocol to send and receive data stream. +# It might provide TCPv4 Protocol or TCPv6 Protocol or both of them that depends on which network +# stack has been loaded in system. This driver supports both IPv4 and IPv6 network stack. +# +# Copyright (c) 2009 - 2018, Intel Corporation. All rights reserved.
+# +# This program and the accompanying materials +# are licensed and made available under the terms and conditions of the BSD License +# which accompanies this distribution. The full text of the license may be found at +# http://opensource.org/licenses/bsd-license.php. +# +# THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS, +# WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED. +# +## + +[Defines] + INF_VERSION = 0x0001001B + BASE_NAME = SharedTcpDxeDebug + FILE_GUID = D36A870A-972D-4366-B39E-509431A149C9 + MODULE_TYPE = UEFI_DRIVER + VERSION_STRING = 1.0 + ENTRY_POINT = TcpDriverEntryPoint + UNLOAD_IMAGE = NetLibDefaultUnload + MODULE_UNI_FILE = TcpDxe.uni + +# +# VALID_ARCHITECTURES = IA32 X64# + + +[Binaries.X64] + PE32|Mu-SharedNetworking_extdep/DEBUG/X64/TcpDxe.efi|DEBUG + +[Binaries.IA32] + PE32|Mu-SharedNetworking_extdep/DEBUG/IA32/TcpDxe.efi|DEBUG + +[Binaries.AARCH64] + PE32|Mu-SharedNetworking_extdep/DEBUG/AARCH64/TcpDxe.efi|DEBUG + +[Packages] + MdePkg/MdePkg.dec + MdeModulePkg/MdeModulePkg.dec + +[Protocols] + ## SOMETIMES_CONSUMES + ## SOMETIMES_PRODUCES + gEfiDevicePathProtocolGuid + gEfiIp4ProtocolGuid ## TO_START + gEfiIp4ServiceBindingProtocolGuid ## TO_START + gEfiTcp4ProtocolGuid ## BY_START + gEfiTcp4ServiceBindingProtocolGuid ## BY_START + gEfiIp6ProtocolGuid ## TO_START + gEfiIp6ServiceBindingProtocolGuid ## TO_START + gEfiTcp6ProtocolGuid ## BY_START + gEfiTcp6ServiceBindingProtocolGuid ## BY_START + +[UserExtensions.TianoCore."ExtraFiles"] + TcpDxeExtra.uni + +[Depex] + TRUE diff --git a/NetworkPkg/SharedNetworking/TcpDxe.RELEASE.inf b/NetworkPkg/SharedNetworking/TcpDxe.RELEASE.inf index 16265d545f..acd9293d5a 100644 --- a/NetworkPkg/SharedNetworking/TcpDxe.RELEASE.inf +++ b/NetworkPkg/SharedNetworking/TcpDxe.RELEASE.inf @@ -1,64 +1,64 @@ -## @file -# TCPv4 I/O and TCPv6 I/O services. -# -# This module provides EFI TCPv4 Protocol and EFI TCPv6 Protocol to send and receive data stream. -# It might provide TCPv4 Protocol or TCPv6 Protocol or both of them that depends on which network -# stack has been loaded in system. This driver supports both IPv4 and IPv6 network stack. -# -# Copyright (c) 2009 - 2018, Intel Corporation. All rights reserved.
-# -# This program and the accompanying materials -# are licensed and made available under the terms and conditions of the BSD License -# which accompanies this distribution. The full text of the license may be found at -# http://opensource.org/licenses/bsd-license.php. -# -# THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS, -# WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED. -# -## - -[Defines] - INF_VERSION = 0x0001001B - BASE_NAME = SharedTcpDxeRelease - FILE_GUID = 0981D464-4E74-42D9-BD3E-3CE90C15ED9F - MODULE_TYPE = UEFI_DRIVER - VERSION_STRING = 1.0 - ENTRY_POINT = TcpDriverEntryPoint - UNLOAD_IMAGE = NetLibDefaultUnload - MODULE_UNI_FILE = TcpDxe.uni - -# -# VALID_ARCHITECTURES = IA32 X64# - - -[Binaries.X64] - PE32|Mu-SharedNetworking_extdep/RELEASE/X64/TcpDxe.efi|RELEASE - -[Binaries.IA32] - PE32|Mu-SharedNetworking_extdep/RELEASE/IA32/TcpDxe.efi|RELEASE - -[Binaries.AARCH64] - PE32|Mu-SharedNetworking_extdep/RELEASE/AARCH64/TcpDxe.efi|RELEASE - -[Packages] - MdePkg/MdePkg.dec - MdeModulePkg/MdeModulePkg.dec - -[Protocols] - ## SOMETIMES_CONSUMES - ## SOMETIMES_PRODUCES - gEfiDevicePathProtocolGuid - gEfiIp4ProtocolGuid ## TO_START - gEfiIp4ServiceBindingProtocolGuid ## TO_START - gEfiTcp4ProtocolGuid ## BY_START - gEfiTcp4ServiceBindingProtocolGuid ## BY_START - gEfiIp6ProtocolGuid ## TO_START - gEfiIp6ServiceBindingProtocolGuid ## TO_START - gEfiTcp6ProtocolGuid ## BY_START - gEfiTcp6ServiceBindingProtocolGuid ## BY_START - -[UserExtensions.TianoCore."ExtraFiles"] - TcpDxeExtra.uni - -[Depex] - TRUE +## @file +# TCPv4 I/O and TCPv6 I/O services. +# +# This module provides EFI TCPv4 Protocol and EFI TCPv6 Protocol to send and receive data stream. +# It might provide TCPv4 Protocol or TCPv6 Protocol or both of them that depends on which network +# stack has been loaded in system. This driver supports both IPv4 and IPv6 network stack. +# +# Copyright (c) 2009 - 2018, Intel Corporation. All rights reserved.
+# +# This program and the accompanying materials +# are licensed and made available under the terms and conditions of the BSD License +# which accompanies this distribution. The full text of the license may be found at +# http://opensource.org/licenses/bsd-license.php. +# +# THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS, +# WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED. +# +## + +[Defines] + INF_VERSION = 0x0001001B + BASE_NAME = SharedTcpDxeRelease + FILE_GUID = 0981D464-4E74-42D9-BD3E-3CE90C15ED9F + MODULE_TYPE = UEFI_DRIVER + VERSION_STRING = 1.0 + ENTRY_POINT = TcpDriverEntryPoint + UNLOAD_IMAGE = NetLibDefaultUnload + MODULE_UNI_FILE = TcpDxe.uni + +# +# VALID_ARCHITECTURES = IA32 X64# + + +[Binaries.X64] + PE32|Mu-SharedNetworking_extdep/RELEASE/X64/TcpDxe.efi|RELEASE + +[Binaries.IA32] + PE32|Mu-SharedNetworking_extdep/RELEASE/IA32/TcpDxe.efi|RELEASE + +[Binaries.AARCH64] + PE32|Mu-SharedNetworking_extdep/RELEASE/AARCH64/TcpDxe.efi|RELEASE + +[Packages] + MdePkg/MdePkg.dec + MdeModulePkg/MdeModulePkg.dec + +[Protocols] + ## SOMETIMES_CONSUMES + ## SOMETIMES_PRODUCES + gEfiDevicePathProtocolGuid + gEfiIp4ProtocolGuid ## TO_START + gEfiIp4ServiceBindingProtocolGuid ## TO_START + gEfiTcp4ProtocolGuid ## BY_START + gEfiTcp4ServiceBindingProtocolGuid ## BY_START + gEfiIp6ProtocolGuid ## TO_START + gEfiIp6ServiceBindingProtocolGuid ## TO_START + gEfiTcp6ProtocolGuid ## BY_START + gEfiTcp6ServiceBindingProtocolGuid ## BY_START + +[UserExtensions.TianoCore."ExtraFiles"] + TcpDxeExtra.uni + +[Depex] + TRUE diff --git a/NetworkPkg/SharedNetworking/TlsDxe.DEBUG.inf b/NetworkPkg/SharedNetworking/TlsDxe.DEBUG.inf index ce29a0dde1..adb4b79683 100644 --- a/NetworkPkg/SharedNetworking/TlsDxe.DEBUG.inf +++ b/NetworkPkg/SharedNetworking/TlsDxe.DEBUG.inf @@ -1,58 +1,58 @@ -## @file -# This module produces EFI TLS Protocol, EFI TLS Service Binding Protocol and -# EFI TLS Configuration Protocol. -# -# This module produces EFI TLS (Transport Layer Security) Protocol and EFI TLS -# Service Binding Protocol, to provide TLS services. -# -# Copyright (c) 2016 - 2018, Intel Corporation. All rights reserved.
-# -# This program and the accompanying materials -# are licensed and made available under the terms and conditions of the BSD License -# which accompanies this distribution. The full text of the license may be found at -# http://opensource.org/licenses/bsd-license.php. -# THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS, -# WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED. -# -# -## - -[Defines] - INF_VERSION = 0x0001001B - BASE_NAME = SharedTlsDxeDebug - FILE_GUID = EE3A5D43-5392-45EB-8714-0BB7C26E3CD4 - MODULE_TYPE = UEFI_DRIVER - VERSION_STRING = 1.0 - ENTRY_POINT = TlsDriverEntryPoint - UNLOAD_IMAGE = TlsUnload - MODULE_UNI_FILE = TlsDxe.uni - -# -# VALID_ARCHITECTURES = IA32 X64# - - -[Binaries.X64] - PE32|Mu-SharedNetworking_extdep/DEBUG/X64/TlsDxe.efi|DEBUG - -[Binaries.IA32] - PE32|Mu-SharedNetworking_extdep/DEBUG/IA32/TlsDxe.efi|DEBUG - -[Binaries.AARCH64] - PE32|Mu-SharedNetworking_extdep/DEBUG/AARCH64/TlsDxe.efi|DEBUG - -[Packages] - NetworkPkg/NetworkPkg.dec - MdePkg/MdePkg.dec - MdeModulePkg/MdeModulePkg.dec - CryptoPkg/CryptoPkg.dec - -[Protocols] - gEfiTlsServiceBindingProtocolGuid ## PRODUCES - gEfiTlsProtocolGuid ## PRODUCES - gEfiTlsConfigurationProtocolGuid ## PRODUCES - -[UserExtensions.TianoCore."ExtraFiles"] - TlsDxeExtra.uni - -[Depex] - TRUE +## @file +# This module produces EFI TLS Protocol, EFI TLS Service Binding Protocol and +# EFI TLS Configuration Protocol. +# +# This module produces EFI TLS (Transport Layer Security) Protocol and EFI TLS +# Service Binding Protocol, to provide TLS services. +# +# Copyright (c) 2016 - 2018, Intel Corporation. All rights reserved.
+# +# This program and the accompanying materials +# are licensed and made available under the terms and conditions of the BSD License +# which accompanies this distribution. The full text of the license may be found at +# http://opensource.org/licenses/bsd-license.php. +# THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS, +# WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED. +# +# +## + +[Defines] + INF_VERSION = 0x0001001B + BASE_NAME = SharedTlsDxeDebug + FILE_GUID = EE3A5D43-5392-45EB-8714-0BB7C26E3CD4 + MODULE_TYPE = UEFI_DRIVER + VERSION_STRING = 1.0 + ENTRY_POINT = TlsDriverEntryPoint + UNLOAD_IMAGE = TlsUnload + MODULE_UNI_FILE = TlsDxe.uni + +# +# VALID_ARCHITECTURES = IA32 X64# + + +[Binaries.X64] + PE32|Mu-SharedNetworking_extdep/DEBUG/X64/TlsDxe.efi|DEBUG + +[Binaries.IA32] + PE32|Mu-SharedNetworking_extdep/DEBUG/IA32/TlsDxe.efi|DEBUG + +[Binaries.AARCH64] + PE32|Mu-SharedNetworking_extdep/DEBUG/AARCH64/TlsDxe.efi|DEBUG + +[Packages] + NetworkPkg/NetworkPkg.dec + MdePkg/MdePkg.dec + MdeModulePkg/MdeModulePkg.dec + CryptoPkg/CryptoPkg.dec + +[Protocols] + gEfiTlsServiceBindingProtocolGuid ## PRODUCES + gEfiTlsProtocolGuid ## PRODUCES + gEfiTlsConfigurationProtocolGuid ## PRODUCES + +[UserExtensions.TianoCore."ExtraFiles"] + TlsDxeExtra.uni + +[Depex] + TRUE diff --git a/NetworkPkg/SharedNetworking/TlsDxe.RELEASE.inf b/NetworkPkg/SharedNetworking/TlsDxe.RELEASE.inf index 2b7645a300..69cb65b57c 100644 --- a/NetworkPkg/SharedNetworking/TlsDxe.RELEASE.inf +++ b/NetworkPkg/SharedNetworking/TlsDxe.RELEASE.inf @@ -1,58 +1,58 @@ -## @file -# This module produces EFI TLS Protocol, EFI TLS Service Binding Protocol and -# EFI TLS Configuration Protocol. -# -# This module produces EFI TLS (Transport Layer Security) Protocol and EFI TLS -# Service Binding Protocol, to provide TLS services. -# -# Copyright (c) 2016 - 2018, Intel Corporation. All rights reserved.
-# -# This program and the accompanying materials -# are licensed and made available under the terms and conditions of the BSD License -# which accompanies this distribution. The full text of the license may be found at -# http://opensource.org/licenses/bsd-license.php. -# THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS, -# WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED. -# -# -## - -[Defines] - INF_VERSION = 0x0001001B - BASE_NAME = SharedTlsDxeRelease - FILE_GUID = C1E15908-AB7B-4DA8-8C56-417B0B0D8D5B - MODULE_TYPE = UEFI_DRIVER - VERSION_STRING = 1.0 - ENTRY_POINT = TlsDriverEntryPoint - UNLOAD_IMAGE = TlsUnload - MODULE_UNI_FILE = TlsDxe.uni - -# -# VALID_ARCHITECTURES = IA32 X64# - - -[Binaries.X64] - PE32|Mu-SharedNetworking_extdep/RELEASE/X64/TlsDxe.efi|RELEASE - -[Binaries.IA32] - PE32|Mu-SharedNetworking_extdep/RELEASE/IA32/TlsDxe.efi|RELEASE - -[Binaries.AARCH64] - PE32|Mu-SharedNetworking_extdep/RELEASE/AARCH64/TlsDxe.efi|RELEASE - -[Packages] - NetworkPkg/NetworkPkg.dec - MdePkg/MdePkg.dec - MdeModulePkg/MdeModulePkg.dec - CryptoPkg/CryptoPkg.dec - -[Protocols] - gEfiTlsServiceBindingProtocolGuid ## PRODUCES - gEfiTlsProtocolGuid ## PRODUCES - gEfiTlsConfigurationProtocolGuid ## PRODUCES - -[UserExtensions.TianoCore."ExtraFiles"] - TlsDxeExtra.uni - -[Depex] - TRUE +## @file +# This module produces EFI TLS Protocol, EFI TLS Service Binding Protocol and +# EFI TLS Configuration Protocol. +# +# This module produces EFI TLS (Transport Layer Security) Protocol and EFI TLS +# Service Binding Protocol, to provide TLS services. +# +# Copyright (c) 2016 - 2018, Intel Corporation. All rights reserved.
+# +# This program and the accompanying materials +# are licensed and made available under the terms and conditions of the BSD License +# which accompanies this distribution. The full text of the license may be found at +# http://opensource.org/licenses/bsd-license.php. +# THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS, +# WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED. +# +# +## + +[Defines] + INF_VERSION = 0x0001001B + BASE_NAME = SharedTlsDxeRelease + FILE_GUID = C1E15908-AB7B-4DA8-8C56-417B0B0D8D5B + MODULE_TYPE = UEFI_DRIVER + VERSION_STRING = 1.0 + ENTRY_POINT = TlsDriverEntryPoint + UNLOAD_IMAGE = TlsUnload + MODULE_UNI_FILE = TlsDxe.uni + +# +# VALID_ARCHITECTURES = IA32 X64# + + +[Binaries.X64] + PE32|Mu-SharedNetworking_extdep/RELEASE/X64/TlsDxe.efi|RELEASE + +[Binaries.IA32] + PE32|Mu-SharedNetworking_extdep/RELEASE/IA32/TlsDxe.efi|RELEASE + +[Binaries.AARCH64] + PE32|Mu-SharedNetworking_extdep/RELEASE/AARCH64/TlsDxe.efi|RELEASE + +[Packages] + NetworkPkg/NetworkPkg.dec + MdePkg/MdePkg.dec + MdeModulePkg/MdeModulePkg.dec + CryptoPkg/CryptoPkg.dec + +[Protocols] + gEfiTlsServiceBindingProtocolGuid ## PRODUCES + gEfiTlsProtocolGuid ## PRODUCES + gEfiTlsConfigurationProtocolGuid ## PRODUCES + +[UserExtensions.TianoCore."ExtraFiles"] + TlsDxeExtra.uni + +[Depex] + TRUE diff --git a/NetworkPkg/SharedNetworking/TlsDxe.uni b/NetworkPkg/SharedNetworking/TlsDxe.uni index 911ebe73de..5a9dc46c4f 100644 --- a/NetworkPkg/SharedNetworking/TlsDxe.uni +++ b/NetworkPkg/SharedNetworking/TlsDxe.uni @@ -1,24 +1,24 @@ -// /** @file -// This module produces EFI TLS Protocol, EFI TLS Service Binding Protocol and -// EFI TLS Configuration Protocol. -// -// This module produces EFI TLS (Transport Layer Security) Protocol, EFI TLS -// Service Binding Protocol, and EFI TLS Configuration Protocol to provide TLS -// services. -// -// Copyright (c) 2016, Intel Corporation. All rights reserved.
-// -// This program and the accompanying materials -// are licensed and made available under the terms and conditions of the BSD License -// which accompanies this distribution. The full text of the license may be found at -// http://opensource.org/licenses/bsd-license.php -// -// THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS, -// WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED. -// -// **/ - - -#string STR_MODULE_ABSTRACT #language en-US "UEFI TLS Shared service" - -#string STR_MODULE_DESCRIPTION #language en-US "This module produces EFI TLS Protocol, EFI TLS Service Binding Protocol and EFI TLS Configuration Protocol to provide EFI TLS services." +// /** @file +// This module produces EFI TLS Protocol, EFI TLS Service Binding Protocol and +// EFI TLS Configuration Protocol. +// +// This module produces EFI TLS (Transport Layer Security) Protocol, EFI TLS +// Service Binding Protocol, and EFI TLS Configuration Protocol to provide TLS +// services. +// +// Copyright (c) 2016, Intel Corporation. All rights reserved.
+// +// This program and the accompanying materials +// are licensed and made available under the terms and conditions of the BSD License +// which accompanies this distribution. The full text of the license may be found at +// http://opensource.org/licenses/bsd-license.php +// +// THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS, +// WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED. +// +// **/ + + +#string STR_MODULE_ABSTRACT #language en-US "UEFI TLS Shared service" + +#string STR_MODULE_DESCRIPTION #language en-US "This module produces EFI TLS Protocol, EFI TLS Service Binding Protocol and EFI TLS Configuration Protocol to provide EFI TLS services." diff --git a/NetworkPkg/SharedNetworking/TlsDxeExtra.uni b/NetworkPkg/SharedNetworking/TlsDxeExtra.uni index 23d3ab436e..5ec97ac25e 100644 --- a/NetworkPkg/SharedNetworking/TlsDxeExtra.uni +++ b/NetworkPkg/SharedNetworking/TlsDxeExtra.uni @@ -1,18 +1,18 @@ -// /** @file -// TlsDxe Localized Strings and Content -// -// Copyright (c) 2016, Intel Corporation. All rights reserved.
-// -// This program and the accompanying materials -// are licensed and made available under the terms and conditions of the BSD License -// which accompanies this distribution. The full text of the license may be found at -// http://opensource.org/licenses/bsd-license.php. -// -// THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS, -// WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED. -// -// **/ - -#string STR_PROPERTIES_MODULE_NAME -#language en-US -"EFI TLS Shared DXE Driver" +// /** @file +// TlsDxe Localized Strings and Content +// +// Copyright (c) 2016, Intel Corporation. All rights reserved.
+// +// This program and the accompanying materials +// are licensed and made available under the terms and conditions of the BSD License +// which accompanies this distribution. The full text of the license may be found at +// http://opensource.org/licenses/bsd-license.php. +// +// THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS, +// WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED. +// +// **/ + +#string STR_PROPERTIES_MODULE_NAME +#language en-US +"EFI TLS Shared DXE Driver" diff --git a/NetworkPkg/SharedNetworking/Udp6Dxe.DEBUG.inf b/NetworkPkg/SharedNetworking/Udp6Dxe.DEBUG.inf index 7c30af275a..dccbd2a49f 100644 --- a/NetworkPkg/SharedNetworking/Udp6Dxe.DEBUG.inf +++ b/NetworkPkg/SharedNetworking/Udp6Dxe.DEBUG.inf @@ -1,56 +1,56 @@ -## @file Udp6Dxe.inf -# UDP packet service based on IPv6 stack. -# -# This module produces EFI UDPv6 Protocol which provides simple packet-oriented -# services to transmit and receive UDP packets. -# -# Copyright (c) 2009 - 2018, Intel Corporation. All rights reserved.
-# -# This program and the accompanying materials -# are licensed and made available under the terms and conditions of the BSD License -# which accompanies this distribution. The full text of the license may be found at -# http://opensource.org/licenses/bsd-license.php. -# -# THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS, -# WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED. -# -## - -[Defines] - INF_VERSION = 0x0001001B - BASE_NAME = SharedUdp6DxeDebug - FILE_GUID = DDDCD7D3-FA35-4E2F-8535-A7C431BEE46D - MODULE_TYPE = UEFI_DRIVER - VERSION_STRING = 1.0 - ENTRY_POINT = Udp6DriverEntryPoint - UNLOAD_IMAGE = NetLibDefaultUnload - MODULE_UNI_FILE = Udp6Dxe.uni - -# -# VALID_ARCHITECTURES = IA32 X64# - - -[Binaries.X64] - PE32|Mu-SharedNetworking_extdep/DEBUG/X64/Udp6Dxe.efi|DEBUG - -[Binaries.IA32] - PE32|Mu-SharedNetworking_extdep/DEBUG/IA32/Udp6Dxe.efi|DEBUG - -[Binaries.AARCH64] - PE32|Mu-SharedNetworking_extdep/DEBUG/AARCH64/Udp6Dxe.efi|DEBUG - -[Packages] - MdePkg/MdePkg.dec - MdeModulePkg/MdeModulePkg.dec - -[Protocols] - gEfiIp6ProtocolGuid ## TO_START - gEfiIp6ServiceBindingProtocolGuid ## TO_START - gEfiUdp6ServiceBindingProtocolGuid ## BY_START - gEfiUdp6ProtocolGuid ## BY_START - -[UserExtensions.TianoCore."ExtraFiles"] - Udp6DxeExtra.uni - -[Depex] - TRUE +## @file Udp6Dxe.inf +# UDP packet service based on IPv6 stack. +# +# This module produces EFI UDPv6 Protocol which provides simple packet-oriented +# services to transmit and receive UDP packets. +# +# Copyright (c) 2009 - 2018, Intel Corporation. All rights reserved.
+# +# This program and the accompanying materials +# are licensed and made available under the terms and conditions of the BSD License +# which accompanies this distribution. The full text of the license may be found at +# http://opensource.org/licenses/bsd-license.php. +# +# THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS, +# WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED. +# +## + +[Defines] + INF_VERSION = 0x0001001B + BASE_NAME = SharedUdp6DxeDebug + FILE_GUID = DDDCD7D3-FA35-4E2F-8535-A7C431BEE46D + MODULE_TYPE = UEFI_DRIVER + VERSION_STRING = 1.0 + ENTRY_POINT = Udp6DriverEntryPoint + UNLOAD_IMAGE = NetLibDefaultUnload + MODULE_UNI_FILE = Udp6Dxe.uni + +# +# VALID_ARCHITECTURES = IA32 X64# + + +[Binaries.X64] + PE32|Mu-SharedNetworking_extdep/DEBUG/X64/Udp6Dxe.efi|DEBUG + +[Binaries.IA32] + PE32|Mu-SharedNetworking_extdep/DEBUG/IA32/Udp6Dxe.efi|DEBUG + +[Binaries.AARCH64] + PE32|Mu-SharedNetworking_extdep/DEBUG/AARCH64/Udp6Dxe.efi|DEBUG + +[Packages] + MdePkg/MdePkg.dec + MdeModulePkg/MdeModulePkg.dec + +[Protocols] + gEfiIp6ProtocolGuid ## TO_START + gEfiIp6ServiceBindingProtocolGuid ## TO_START + gEfiUdp6ServiceBindingProtocolGuid ## BY_START + gEfiUdp6ProtocolGuid ## BY_START + +[UserExtensions.TianoCore."ExtraFiles"] + Udp6DxeExtra.uni + +[Depex] + TRUE diff --git a/NetworkPkg/SharedNetworking/Udp6Dxe.RELEASE.inf b/NetworkPkg/SharedNetworking/Udp6Dxe.RELEASE.inf index f7284e0f69..08d171e6d7 100644 --- a/NetworkPkg/SharedNetworking/Udp6Dxe.RELEASE.inf +++ b/NetworkPkg/SharedNetworking/Udp6Dxe.RELEASE.inf @@ -1,56 +1,56 @@ -## @file Udp6Dxe.inf -# UDP packet service based on IPv6 stack. -# -# This module produces EFI UDPv6 Protocol which provides simple packet-oriented -# services to transmit and receive UDP packets. -# -# Copyright (c) 2009 - 2018, Intel Corporation. All rights reserved.
-# -# This program and the accompanying materials -# are licensed and made available under the terms and conditions of the BSD License -# which accompanies this distribution. The full text of the license may be found at -# http://opensource.org/licenses/bsd-license.php. -# -# THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS, -# WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED. -# -## - -[Defines] - INF_VERSION = 0x0001001B - BASE_NAME = SharedUdp6DxeRelease - FILE_GUID = 6B037DCF-75BB-4310-9071-17CB8ED96A14 - MODULE_TYPE = UEFI_DRIVER - VERSION_STRING = 1.0 - ENTRY_POINT = Udp6DriverEntryPoint - UNLOAD_IMAGE = NetLibDefaultUnload - MODULE_UNI_FILE = Udp6Dxe.uni - -# -# VALID_ARCHITECTURES = IA32 X64# - - -[Binaries.X64] - PE32|Mu-SharedNetworking_extdep/RELEASE/X64/Udp6Dxe.efi|RELEASE - -[Binaries.IA32] - PE32|Mu-SharedNetworking_extdep/RELEASE/IA32/Udp6Dxe.efi|RELEASE - -[Binaries.AARCH64] - PE32|Mu-SharedNetworking_extdep/RELEASE/AARCH64/Udp6Dxe.efi|RELEASE - -[Packages] - MdePkg/MdePkg.dec - MdeModulePkg/MdeModulePkg.dec - -[Protocols] - gEfiIp6ProtocolGuid ## TO_START - gEfiIp6ServiceBindingProtocolGuid ## TO_START - gEfiUdp6ServiceBindingProtocolGuid ## BY_START - gEfiUdp6ProtocolGuid ## BY_START - -[UserExtensions.TianoCore."ExtraFiles"] - Udp6DxeExtra.uni - -[Depex] - TRUE +## @file Udp6Dxe.inf +# UDP packet service based on IPv6 stack. +# +# This module produces EFI UDPv6 Protocol which provides simple packet-oriented +# services to transmit and receive UDP packets. +# +# Copyright (c) 2009 - 2018, Intel Corporation. All rights reserved.
+# +# This program and the accompanying materials +# are licensed and made available under the terms and conditions of the BSD License +# which accompanies this distribution. The full text of the license may be found at +# http://opensource.org/licenses/bsd-license.php. +# +# THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS, +# WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED. +# +## + +[Defines] + INF_VERSION = 0x0001001B + BASE_NAME = SharedUdp6DxeRelease + FILE_GUID = 6B037DCF-75BB-4310-9071-17CB8ED96A14 + MODULE_TYPE = UEFI_DRIVER + VERSION_STRING = 1.0 + ENTRY_POINT = Udp6DriverEntryPoint + UNLOAD_IMAGE = NetLibDefaultUnload + MODULE_UNI_FILE = Udp6Dxe.uni + +# +# VALID_ARCHITECTURES = IA32 X64# + + +[Binaries.X64] + PE32|Mu-SharedNetworking_extdep/RELEASE/X64/Udp6Dxe.efi|RELEASE + +[Binaries.IA32] + PE32|Mu-SharedNetworking_extdep/RELEASE/IA32/Udp6Dxe.efi|RELEASE + +[Binaries.AARCH64] + PE32|Mu-SharedNetworking_extdep/RELEASE/AARCH64/Udp6Dxe.efi|RELEASE + +[Packages] + MdePkg/MdePkg.dec + MdeModulePkg/MdeModulePkg.dec + +[Protocols] + gEfiIp6ProtocolGuid ## TO_START + gEfiIp6ServiceBindingProtocolGuid ## TO_START + gEfiUdp6ServiceBindingProtocolGuid ## BY_START + gEfiUdp6ProtocolGuid ## BY_START + +[UserExtensions.TianoCore."ExtraFiles"] + Udp6DxeExtra.uni + +[Depex] + TRUE diff --git a/NetworkPkg/SharedNetworking/azure-pipelines-sharednetworking-release-gate.yml b/NetworkPkg/SharedNetworking/azure-pipelines-sharednetworking-release-gate.yml index 08402bdd8e..420a6e49fa 100644 --- a/NetworkPkg/SharedNetworking/azure-pipelines-sharednetworking-release-gate.yml +++ b/NetworkPkg/SharedNetworking/azure-pipelines-sharednetworking-release-gate.yml @@ -1,93 +1,93 @@ -workspace: - clean: all - -trigger: none # will disable CI builds entirely - -# Currently don't have the SecMirrorCommon variables -#variables: -#- group: SecMirrorCommon -pool: - vmImage: windows-latest - -steps: -- checkout: self - clean: true - -- task: UsePythonVersion@0 - inputs: - versionSpec: '3.9.x' - architecture: 'x64' - -- script: python -m pip install --upgrade pip - displayName: 'Install/Upgrade pip' - -- script: pip install -r pip-requirements.txt --upgrade - displayName: 'Install/Upgrade mu_build' - -# Create a variable -#- powershell: | -# Write-Host "##vso[task.setvariable variable=GIT_CREDS]projectmu:$(secmircom.pat)" -#- script: | -# echo my pipeline variable is $(GIT_CREDS) - -# Update dependencies -- task: CmdLine@1 - displayName: Setup - inputs: - filename: stuart_ci_setup - arguments: -c NetworkPkg/SharedNetworking/SharedNetworkSettings.py - -- task: CmdLine@1 - displayName: 'Update Dependencies' - inputs: - filename: stuart_update - arguments: -c NetworkPkg/SharedNetworking/SharedNetworkSettings.py - failOnStderr: false - -# Build and publish -- task: PythonScript@0 - displayName: 'Build and Ship' - condition: eq(variables.ShouldPublish, 'true') - inputs: - scriptSource: 'filePath' - scriptPath: 'NetworkPkg/SharedNetworking/DriverBuilder.py' - arguments: '-c NetworkPkg/SharedNetworking/SharedNetworkSettings.py -nv=$(NugetVersion) --api-key=$(NUGET_API_KEY)' - failOnStderr: false - -# Build but don't publish -- task: PythonScript@0 - displayName: 'Build but do not publish' - condition: not(eq(variables.ShouldPublish, 'true')) - inputs: - scriptSource: 'filePath' - scriptPath: 'NetworkPkg/SharedNetworking/DriverBuilder.py' - arguments: '-c NetworkPkg/SharedNetworking/SharedNetworkSettings.py --verbose' - failOnStderr: false - -# Copy the Nuget Package -- task: CopyFiles@2 - displayName: 'Copy Nuget Pkg' - inputs: - contents: 'Build/**.nupkg' - targetFolder: $(Build.ArtifactStagingDirectory) - -# Copy the TXT file -- task: CopyFiles@2 - displayName: 'Copy Build files' - inputs: - contents: | - Build\**\BUILDLOG_*.txt - Build\**\BUILDLOG_*.md - Build\**\CI_*.txt - Build\**\CI_*.md - Build\**\TestSuites.xml - targetFolder: $(Build.ArtifactStagingDirectory) - -# Publish Build Artifacts -# Publish build artifacts to Azure Artifacts/TFS or a file share -- task: PublishBuildArtifacts@1 - displayName: 'Publish NugetPackage' - continueOnError: true - condition: succeeded() - inputs: +workspace: + clean: all + +trigger: none # will disable CI builds entirely + +# Currently don't have the SecMirrorCommon variables +#variables: +#- group: SecMirrorCommon +pool: + vmImage: windows-latest + +steps: +- checkout: self + clean: true + +- task: UsePythonVersion@0 + inputs: + versionSpec: '3.9.x' + architecture: 'x64' + +- script: python -m pip install --upgrade pip + displayName: 'Install/Upgrade pip' + +- script: pip install -r pip-requirements.txt --upgrade + displayName: 'Install/Upgrade mu_build' + +# Create a variable +#- powershell: | +# Write-Host "##vso[task.setvariable variable=GIT_CREDS]projectmu:$(secmircom.pat)" +#- script: | +# echo my pipeline variable is $(GIT_CREDS) + +# Update dependencies +- task: CmdLine@1 + displayName: Setup + inputs: + filename: stuart_ci_setup + arguments: -c NetworkPkg/SharedNetworking/SharedNetworkSettings.py + +- task: CmdLine@1 + displayName: 'Update Dependencies' + inputs: + filename: stuart_update + arguments: -c NetworkPkg/SharedNetworking/SharedNetworkSettings.py + failOnStderr: false + +# Build and publish +- task: PythonScript@0 + displayName: 'Build and Ship' + condition: eq(variables.ShouldPublish, 'true') + inputs: + scriptSource: 'filePath' + scriptPath: 'NetworkPkg/SharedNetworking/DriverBuilder.py' + arguments: '-c NetworkPkg/SharedNetworking/SharedNetworkSettings.py -nv=$(NugetVersion) --api-key=$(NUGET_API_KEY)' + failOnStderr: false + +# Build but don't publish +- task: PythonScript@0 + displayName: 'Build but do not publish' + condition: not(eq(variables.ShouldPublish, 'true')) + inputs: + scriptSource: 'filePath' + scriptPath: 'NetworkPkg/SharedNetworking/DriverBuilder.py' + arguments: '-c NetworkPkg/SharedNetworking/SharedNetworkSettings.py --verbose' + failOnStderr: false + +# Copy the Nuget Package +- task: CopyFiles@2 + displayName: 'Copy Nuget Pkg' + inputs: + contents: 'Build/**.nupkg' + targetFolder: $(Build.ArtifactStagingDirectory) + +# Copy the TXT file +- task: CopyFiles@2 + displayName: 'Copy Build files' + inputs: + contents: | + Build\**\BUILDLOG_*.txt + Build\**\BUILDLOG_*.md + Build\**\CI_*.txt + Build\**\CI_*.md + Build\**\TestSuites.xml + targetFolder: $(Build.ArtifactStagingDirectory) + +# Publish Build Artifacts +# Publish build artifacts to Azure Artifacts/TFS or a file share +- task: PublishBuildArtifacts@1 + displayName: 'Publish NugetPackage' + continueOnError: true + condition: succeeded() + inputs: artifactName: 'Nuget Package' \ No newline at end of file diff --git a/NetworkPkg/SharedNetworking/release_notes.md b/NetworkPkg/SharedNetworking/release_notes.md index 167e68343f..d7b16926d8 100644 --- a/NetworkPkg/SharedNetworking/release_notes.md +++ b/NetworkPkg/SharedNetworking/release_notes.md @@ -1,4 +1,4 @@ -# Shared Network Release Notes - -This is the packaged version of NetworkPkg. Please see more documentation here: - +# Shared Network Release Notes + +This is the packaged version of NetworkPkg. Please see more documentation here: + diff --git a/PerformancePkg/Application/FbptDump/FbptDump.inf b/PerformancePkg/Application/FbptDump/FbptDump.inf index 881ce7b4fb..74511dbc96 100644 --- a/PerformancePkg/Application/FbptDump/FbptDump.inf +++ b/PerformancePkg/Application/FbptDump/FbptDump.inf @@ -1,38 +1,38 @@ -## @file FbptDump.inf -# This user-facing application dumps FBPT into a file. -# -## -# Copyright (c) Microsoft Corporation. All rights reserved. -# SPDX-License-Identifier: BSD-2-Clause-Patent -# -## - -[Defines] - INF_VERSION = 0x00010017 - BASE_NAME = FbptDump - FILE_GUID = CBA0E029-EE38-41F4-9D01-759AFA4B82BE - VERSION_STRING = 1.0 - MODULE_TYPE = UEFI_APPLICATION - ENTRY_POINT = FbptDumpEntryPoint - - -[Sources] - FbptDump.c - -[Packages] - MdePkg/MdePkg.dec - MdeModulePkg/MdeModulePkg.dec - ShellPkg/ShellPkg.dec - -[LibraryClasses] - ShellLib - UefiApplicationEntryPoint - PrintLib - DebugLib - UefiBootServicesTableLib - UefiLib - SafeIntLib - -[Protocols] - gEfiAcpiSdtProtocolGuid +## @file FbptDump.inf +# This user-facing application dumps FBPT into a file. +# +## +# Copyright (c) Microsoft Corporation. All rights reserved. +# SPDX-License-Identifier: BSD-2-Clause-Patent +# +## + +[Defines] + INF_VERSION = 0x00010017 + BASE_NAME = FbptDump + FILE_GUID = CBA0E029-EE38-41F4-9D01-759AFA4B82BE + VERSION_STRING = 1.0 + MODULE_TYPE = UEFI_APPLICATION + ENTRY_POINT = FbptDumpEntryPoint + + +[Sources] + FbptDump.c + +[Packages] + MdePkg/MdePkg.dec + MdeModulePkg/MdeModulePkg.dec + ShellPkg/ShellPkg.dec + +[LibraryClasses] + ShellLib + UefiApplicationEntryPoint + PrintLib + DebugLib + UefiBootServicesTableLib + UefiLib + SafeIntLib + +[Protocols] + gEfiAcpiSdtProtocolGuid gEfiSmbiosProtocolGuid \ No newline at end of file diff --git a/PolicyServicePkg/CommonPolicy/Template_PolicyHeader.yaml b/PolicyServicePkg/CommonPolicy/Template_PolicyHeader.yaml index 4a281e0964..386e392642 100644 --- a/PolicyServicePkg/CommonPolicy/Template_PolicyHeader.yaml +++ b/PolicyServicePkg/CommonPolicy/Template_PolicyHeader.yaml @@ -1,27 +1,27 @@ -## @file -# -# Slim Bootloader CFGDATA Default File. -# -# Copyright (c) 2020, Intel Corporation. All rights reserved.
-# SPDX-License-Identifier: BSD-2-Clause-Patent -# -## - -# Template section for common policy header, template name has to end with `_TMPL` -# Policy structure metadata, will be used for policy headers and genereating unique macro definitions -POLICY_HEADER_TMPL: > - # Unique identifier for this polisy structure. Duplicate category in an active platform will cause build break - - category : $(1) - # Signature field for verfied policy header - - signature : - - length : 0x08 - - value : $(2) - # Major version field for verfied policy header - - majver : - - length : 0x02 - - value : $(3) - # Minor version field for verfied policy header is automatically populated with the highest minor version from fields - # Size field for verfied policy header, should be what your - - size : - - length : 0x04 - - value : $(4) +## @file +# +# Slim Bootloader CFGDATA Default File. +# +# Copyright (c) 2020, Intel Corporation. All rights reserved.
+# SPDX-License-Identifier: BSD-2-Clause-Patent +# +## + +# Template section for common policy header, template name has to end with `_TMPL` +# Policy structure metadata, will be used for policy headers and genereating unique macro definitions +POLICY_HEADER_TMPL: > + # Unique identifier for this polisy structure. Duplicate category in an active platform will cause build break + - category : $(1) + # Signature field for verfied policy header + - signature : + - length : 0x08 + - value : $(2) + # Major version field for verfied policy header + - majver : + - length : 0x02 + - value : $(3) + # Minor version field for verfied policy header is automatically populated with the highest minor version from fields + # Size field for verfied policy header, should be what your + - size : + - length : 0x04 + - value : $(4) diff --git a/PolicyServicePkg/Plugins/UpdatePolicyHdr/UpdatePolicyHdr.py b/PolicyServicePkg/Plugins/UpdatePolicyHdr/UpdatePolicyHdr.py index f54ac87836..4f9c843f5a 100644 --- a/PolicyServicePkg/Plugins/UpdatePolicyHdr/UpdatePolicyHdr.py +++ b/PolicyServicePkg/Plugins/UpdatePolicyHdr/UpdatePolicyHdr.py @@ -1,262 +1,262 @@ -## -# This plugin generates policy header files -# from platform supplied YAML policy. -# -# Copyright (c) Microsoft Corporation -# SPDX-License-Identifier: BSD-2-Clause-Patent -## - -import logging -import os -import shutil -from collections import OrderedDict -from copy import deepcopy -import xml.etree.ElementTree -import hashlib -import json -import time -import re -import xml.etree.ElementTree as ET -from edk2toolext.environment import shell_environment -from edk2toolext.environment.plugintypes.uefi_build_plugin import IUefiBuildPlugin -from edk2toollib.utility_functions import RunPythonScript -from edk2toollib.uefi.edk2.path_utilities import Edk2Path - -import sys - -import yaml -sys.path.append(os.path.join(os.path.dirname(os.path.dirname(os.path.dirname(__file__))), 'Tools')) -from GenCfgData import CGenCfgData - -class UpdatePolicyHdr(IUefiBuildPlugin): - - def trimTreeBaseOnMinver (self, tree, list): - - if type(tree) is not OrderedDict: - raise Exception ("Incorrect tree type!!!") - - try: - ver = int(tree["minver"], 0) - except: - ver = 0 - - trim_list = [] - for idx in range(len(list)): - if idx < ver and list[idx] != None: - # trim the entry if this minver is higher than it belongs - list[idx] = None - trim_list.append(idx) - - for value in tree: - if type(tree[value]) is OrderedDict: - sub_list = [] - for idx in range(len(list)): - if list[idx] != None: - sub_list.append(list[idx][value]) - else: - sub_list.append(None) - sub_trim_list = self.trimTreeBaseOnMinver (tree[value], sub_list) - for item in sub_trim_list: - del list[item][value] - - return trim_list - - # in-place prettyprint formatter - @staticmethod - def indent(elem, level=0): - i = "\n" + level*" " - if len(elem): - if not elem.text or not elem.text.strip(): - elem.text = i + " " - if not elem.tail or not elem.tail.strip(): - elem.tail = i - for elem in elem: - UpdatePolicyHdr.indent(elem, level+1) - if not elem.tail or not elem.tail.strip(): - elem.tail = i - else: - if level and (not elem.tail or not elem.tail.strip()): - elem.tail = i - - # Attempt to run GenCfgData to generate C header files - # - # Consumes build environement variables: "BUILD_OUTPUT_BASE", "UPDATE_SETTINGS", - # and either of "POLICY_REPORT_FOLDER" or "ACTIVE_PLATFORM" - def do_pre_build(self, thebuilder): - need_check = thebuilder.env.GetValue("UPDATE_SETTINGS") - if need_check is not None and need_check.upper() == "FALSE": - logging.warn ("Platform indicated as not checking YAML file changes, will not be updated!") - return 0 - - yaml_list = [] - exception_list = [] - ws = thebuilder.ws - pp = thebuilder.pp.split(os.pathsep) - edk2 = Edk2Path(ws, pp) - - # Form the exception list of formatted absolute paths. And always ignore our own samples. - exception_list.append (thebuilder.mws.join (thebuilder.ws, "PolicyServicePkg", "Samples")) - platform_exception = thebuilder.env.GetValue("POLICY_IGNORE_PATHS") - if platform_exception is not None: - plat_list = platform_exception.split(';') - for each in plat_list: - exception_list.append(os.path.normpath (thebuilder.mws.join (thebuilder.ws, each))) - - # Look for *_policy_def.yaml files in all package paths. - for pkg_path in pp: - for subdir, dirs, files in os.walk(pkg_path): - for file in files: - if file.endswith ("_policy_def.yaml") or file.endswith ("_policy_def.yml"): - yaml_path = os.path.normpath(os.path.join (subdir, file)) - ignore = False - for exception in exception_list: - if yaml_path.startswith (exception): - ignore = True - break - if ignore: - continue - yaml_list.append (yaml_path) - logging.debug (yaml_path) - - err_count = 0 - type = 'POLICY' - report_dir = thebuilder.env.GetValue("%s_REPORT_FOLDER" % type) - if report_dir is None: - report_dir = edk2.GetAbsolutePathOnThisSystemFromEdk2RelativePath ( - edk2.GetContainingPackage( - edk2.GetAbsolutePathOnThisSystemFromEdk2RelativePath( - thebuilder.env.GetValue("ACTIVE_PLATFORM")))) - - report_file = os.path.join (report_dir, "%s_REPORT.xml" % type) - - if os.path.isfile (report_file): - tree = ET.parse(report_file).getroot() - else: - tree = None - - comment = ET.Comment(' === Auto-Generated. Please do not change anything!!! === ') - root = ET.Element('Settings') - root.insert(0, comment) - - for setting in yaml_list: - - if not os.path.normcase(setting).startswith(os.path.normcase(report_dir.rstrip(os.sep)) + os.sep): - continue - - logging.info ("Processing settings from %s" % setting) - - final_dir = os.path.join (edk2.GetAbsolutePathOnThisSystemFromEdk2RelativePath( - edk2.GetContainingPackage (setting)), "Include") - if not os.path.isdir(final_dir): - os.mkdir (final_dir) - - # Set up a playground first - op_dir = thebuilder.mws.join(thebuilder.ws, thebuilder.env.GetValue("BUILD_OUTPUT_BASE"), "ConfPolicy") - if not os.path.isdir(op_dir): - os.makedirs(op_dir) - - cmd = thebuilder.mws.join(thebuilder.ws, "PolicyServicePkg", "Tools", "GenCfgData.py") - - conf_file = setting - if conf_file is None: - logging.warn ("YAML file not specified, system might not work as expected!!!") - return 0 - if not os.path.isfile(conf_file): - logging.error ("YAML file specified is not found!!!") - return 1 - - gen_cfg_data = CGenCfgData() - - if gen_cfg_data.load_yaml(conf_file, shallow_load=True) != 0: - raise Exception(gen_cfg_data.get_last_error()) - - merged_cfg_tree = gen_cfg_data.get_cfg_tree() - - minor_tree_list = [] - max_minver = gen_cfg_data.findMaxMinver (merged_cfg_tree) - # each minor version needs a spot, thus plus 1 here - for _ in range(max_minver + 1): - new_tree = deepcopy (merged_cfg_tree) - minor_tree_list.append (new_tree) - self.trimTreeBaseOnMinver (merged_cfg_tree, minor_tree_list) - - target = merged_cfg_tree['PolicyHeader']['category'] - major_version = int (merged_cfg_tree['PolicyHeader']['majver']['value'], 0) - - # Insert xml leaf for this conf/policy/etc - leaf = ET.Element(target) - leaf.set("MajorVersion", '0x%04X' % major_version) - leaf.set("MinorVersion", '0x%04X' % max_minver) - - for idx in range(len(minor_tree_list)): - minhash_item = ET.Element("Hash-v%x.%x" % (major_version, idx)) - hash_obj = hashlib.md5() - tree_js = json.dumps(minor_tree_list[idx]) - hash_obj.update(tree_js.encode('utf-8')) - result = hash_obj.hexdigest() - minhash_item.text = result - leaf.append (minhash_item) - - cached_root = None - if tree != None: - cached_root = tree.find (target) - if cached_root != None: - cached_maj_ver = int (cached_root.get("MajorVersion"), 0) - - if cached_maj_ver == None or major_version != cached_maj_ver: - # Print error message here and we will fail the build later on - logging.error ("Platform major verison does not match YAML files. Please update the %s descriptor file." % type) - err_count = err_count + 1 - - count = 0 - - for idx in range(len(minor_tree_list)): - saved_res = cached_root.find("Hash-v%x.%x" % (major_version, idx)) - calc_ret = leaf.find("Hash-v%x.%x" % (major_version, idx)) - if saved_res == None or saved_res.text != calc_ret.text: - count = count + 1 - if idx == 0: - logging.error ("Minor version 0 has changed, please consider bumping up major version") - logging.error ("%d minor version fields have changed, please update your report file" % idx) - err_count = err_count + 1 - - # Just to check if the cached hash file has extra entries compared to reality - for res in cached_root: - calc_ret = leaf.find(res.tag) - if calc_ret == None: - logging.error ("A tag from cached xml (%s) is not found" % res.tag) - err_count = err_count + 1 - - tree.remove (cached_root) - else: - logging.error ("%s report file not found, please add the autogen xml file to your %s_REPORT_FOLDER" % (type, type)) - err_count = err_count + 1 - - # Now that we have the PKL file, output the header files - params = ["GENHDR"] - params.append(conf_file) - params.append("PolicyDataStruct%s.h" % target) - - ret = RunPythonScript(cmd, " ".join(params), workingdir=final_dir) - if ret != 0: - return ret - - root.append (leaf) - - if tree != None and 0 != len(tree): - logging.error ("There is stale policy from cached xml %s, please remove them or use the newly created report." % (str([i.tag for i in tree]))) - err_count = err_count + len(tree) - - if err_count != 0: - UpdatePolicyHdr.indent(root) - hash_obj = hashlib.md5() - tree_xml = ET.tostring(root, encoding="utf-8", xml_declaration=True) - hash_obj.update(tree_xml) - xml_hash = hash_obj.hexdigest() - new_file = os.path.join (report_dir, "%s_REPORT_%s.xml" % (type, xml_hash)) - xml_file = open(new_file, 'wb') - xml_file.write(tree_xml) - xml_file.close() - logging.info ("New %s report xml was generated at %s, please replace %s with this new file." % (type, report_file, new_file)) - - return err_count +## +# This plugin generates policy header files +# from platform supplied YAML policy. +# +# Copyright (c) Microsoft Corporation +# SPDX-License-Identifier: BSD-2-Clause-Patent +## + +import logging +import os +import shutil +from collections import OrderedDict +from copy import deepcopy +import xml.etree.ElementTree +import hashlib +import json +import time +import re +import xml.etree.ElementTree as ET +from edk2toolext.environment import shell_environment +from edk2toolext.environment.plugintypes.uefi_build_plugin import IUefiBuildPlugin +from edk2toollib.utility_functions import RunPythonScript +from edk2toollib.uefi.edk2.path_utilities import Edk2Path + +import sys + +import yaml +sys.path.append(os.path.join(os.path.dirname(os.path.dirname(os.path.dirname(__file__))), 'Tools')) +from GenCfgData import CGenCfgData + +class UpdatePolicyHdr(IUefiBuildPlugin): + + def trimTreeBaseOnMinver (self, tree, list): + + if type(tree) is not OrderedDict: + raise Exception ("Incorrect tree type!!!") + + try: + ver = int(tree["minver"], 0) + except: + ver = 0 + + trim_list = [] + for idx in range(len(list)): + if idx < ver and list[idx] != None: + # trim the entry if this minver is higher than it belongs + list[idx] = None + trim_list.append(idx) + + for value in tree: + if type(tree[value]) is OrderedDict: + sub_list = [] + for idx in range(len(list)): + if list[idx] != None: + sub_list.append(list[idx][value]) + else: + sub_list.append(None) + sub_trim_list = self.trimTreeBaseOnMinver (tree[value], sub_list) + for item in sub_trim_list: + del list[item][value] + + return trim_list + + # in-place prettyprint formatter + @staticmethod + def indent(elem, level=0): + i = "\n" + level*" " + if len(elem): + if not elem.text or not elem.text.strip(): + elem.text = i + " " + if not elem.tail or not elem.tail.strip(): + elem.tail = i + for elem in elem: + UpdatePolicyHdr.indent(elem, level+1) + if not elem.tail or not elem.tail.strip(): + elem.tail = i + else: + if level and (not elem.tail or not elem.tail.strip()): + elem.tail = i + + # Attempt to run GenCfgData to generate C header files + # + # Consumes build environement variables: "BUILD_OUTPUT_BASE", "UPDATE_SETTINGS", + # and either of "POLICY_REPORT_FOLDER" or "ACTIVE_PLATFORM" + def do_pre_build(self, thebuilder): + need_check = thebuilder.env.GetValue("UPDATE_SETTINGS") + if need_check is not None and need_check.upper() == "FALSE": + logging.warn ("Platform indicated as not checking YAML file changes, will not be updated!") + return 0 + + yaml_list = [] + exception_list = [] + ws = thebuilder.ws + pp = thebuilder.pp.split(os.pathsep) + edk2 = Edk2Path(ws, pp) + + # Form the exception list of formatted absolute paths. And always ignore our own samples. + exception_list.append (thebuilder.mws.join (thebuilder.ws, "PolicyServicePkg", "Samples")) + platform_exception = thebuilder.env.GetValue("POLICY_IGNORE_PATHS") + if platform_exception is not None: + plat_list = platform_exception.split(';') + for each in plat_list: + exception_list.append(os.path.normpath (thebuilder.mws.join (thebuilder.ws, each))) + + # Look for *_policy_def.yaml files in all package paths. + for pkg_path in pp: + for subdir, dirs, files in os.walk(pkg_path): + for file in files: + if file.endswith ("_policy_def.yaml") or file.endswith ("_policy_def.yml"): + yaml_path = os.path.normpath(os.path.join (subdir, file)) + ignore = False + for exception in exception_list: + if yaml_path.startswith (exception): + ignore = True + break + if ignore: + continue + yaml_list.append (yaml_path) + logging.debug (yaml_path) + + err_count = 0 + type = 'POLICY' + report_dir = thebuilder.env.GetValue("%s_REPORT_FOLDER" % type) + if report_dir is None: + report_dir = edk2.GetAbsolutePathOnThisSystemFromEdk2RelativePath ( + edk2.GetContainingPackage( + edk2.GetAbsolutePathOnThisSystemFromEdk2RelativePath( + thebuilder.env.GetValue("ACTIVE_PLATFORM")))) + + report_file = os.path.join (report_dir, "%s_REPORT.xml" % type) + + if os.path.isfile (report_file): + tree = ET.parse(report_file).getroot() + else: + tree = None + + comment = ET.Comment(' === Auto-Generated. Please do not change anything!!! === ') + root = ET.Element('Settings') + root.insert(0, comment) + + for setting in yaml_list: + + if not os.path.normcase(setting).startswith(os.path.normcase(report_dir.rstrip(os.sep)) + os.sep): + continue + + logging.info ("Processing settings from %s" % setting) + + final_dir = os.path.join (edk2.GetAbsolutePathOnThisSystemFromEdk2RelativePath( + edk2.GetContainingPackage (setting)), "Include") + if not os.path.isdir(final_dir): + os.mkdir (final_dir) + + # Set up a playground first + op_dir = thebuilder.mws.join(thebuilder.ws, thebuilder.env.GetValue("BUILD_OUTPUT_BASE"), "ConfPolicy") + if not os.path.isdir(op_dir): + os.makedirs(op_dir) + + cmd = thebuilder.mws.join(thebuilder.ws, "PolicyServicePkg", "Tools", "GenCfgData.py") + + conf_file = setting + if conf_file is None: + logging.warn ("YAML file not specified, system might not work as expected!!!") + return 0 + if not os.path.isfile(conf_file): + logging.error ("YAML file specified is not found!!!") + return 1 + + gen_cfg_data = CGenCfgData() + + if gen_cfg_data.load_yaml(conf_file, shallow_load=True) != 0: + raise Exception(gen_cfg_data.get_last_error()) + + merged_cfg_tree = gen_cfg_data.get_cfg_tree() + + minor_tree_list = [] + max_minver = gen_cfg_data.findMaxMinver (merged_cfg_tree) + # each minor version needs a spot, thus plus 1 here + for _ in range(max_minver + 1): + new_tree = deepcopy (merged_cfg_tree) + minor_tree_list.append (new_tree) + self.trimTreeBaseOnMinver (merged_cfg_tree, minor_tree_list) + + target = merged_cfg_tree['PolicyHeader']['category'] + major_version = int (merged_cfg_tree['PolicyHeader']['majver']['value'], 0) + + # Insert xml leaf for this conf/policy/etc + leaf = ET.Element(target) + leaf.set("MajorVersion", '0x%04X' % major_version) + leaf.set("MinorVersion", '0x%04X' % max_minver) + + for idx in range(len(minor_tree_list)): + minhash_item = ET.Element("Hash-v%x.%x" % (major_version, idx)) + hash_obj = hashlib.md5() + tree_js = json.dumps(minor_tree_list[idx]) + hash_obj.update(tree_js.encode('utf-8')) + result = hash_obj.hexdigest() + minhash_item.text = result + leaf.append (minhash_item) + + cached_root = None + if tree != None: + cached_root = tree.find (target) + if cached_root != None: + cached_maj_ver = int (cached_root.get("MajorVersion"), 0) + + if cached_maj_ver == None or major_version != cached_maj_ver: + # Print error message here and we will fail the build later on + logging.error ("Platform major verison does not match YAML files. Please update the %s descriptor file." % type) + err_count = err_count + 1 + + count = 0 + + for idx in range(len(minor_tree_list)): + saved_res = cached_root.find("Hash-v%x.%x" % (major_version, idx)) + calc_ret = leaf.find("Hash-v%x.%x" % (major_version, idx)) + if saved_res == None or saved_res.text != calc_ret.text: + count = count + 1 + if idx == 0: + logging.error ("Minor version 0 has changed, please consider bumping up major version") + logging.error ("%d minor version fields have changed, please update your report file" % idx) + err_count = err_count + 1 + + # Just to check if the cached hash file has extra entries compared to reality + for res in cached_root: + calc_ret = leaf.find(res.tag) + if calc_ret == None: + logging.error ("A tag from cached xml (%s) is not found" % res.tag) + err_count = err_count + 1 + + tree.remove (cached_root) + else: + logging.error ("%s report file not found, please add the autogen xml file to your %s_REPORT_FOLDER" % (type, type)) + err_count = err_count + 1 + + # Now that we have the PKL file, output the header files + params = ["GENHDR"] + params.append(conf_file) + params.append("PolicyDataStruct%s.h" % target) + + ret = RunPythonScript(cmd, " ".join(params), workingdir=final_dir) + if ret != 0: + return ret + + root.append (leaf) + + if tree != None and 0 != len(tree): + logging.error ("There is stale policy from cached xml %s, please remove them or use the newly created report." % (str([i.tag for i in tree]))) + err_count = err_count + len(tree) + + if err_count != 0: + UpdatePolicyHdr.indent(root) + hash_obj = hashlib.md5() + tree_xml = ET.tostring(root, encoding="utf-8", xml_declaration=True) + hash_obj.update(tree_xml) + xml_hash = hash_obj.hexdigest() + new_file = os.path.join (report_dir, "%s_REPORT_%s.xml" % (type, xml_hash)) + xml_file = open(new_file, 'wb') + xml_file.write(tree_xml) + xml_file.close() + logging.info ("New %s report xml was generated at %s, please replace %s with this new file." % (type, report_file, new_file)) + + return err_count diff --git a/PolicyServicePkg/Samples/PolicyDefinitions/GFX_policy_def.yaml b/PolicyServicePkg/Samples/PolicyDefinitions/GFX_policy_def.yaml index 2e7945fe7a..04b82d3c0d 100644 --- a/PolicyServicePkg/Samples/PolicyDefinitions/GFX_policy_def.yaml +++ b/PolicyServicePkg/Samples/PolicyDefinitions/GFX_policy_def.yaml @@ -1,43 +1,43 @@ -## @file -# -# Slim Bootloader CFGDATA Default File. -# -# Copyright (c) 2020, Intel Corporation. All rights reserved.
-# SPDX-License-Identifier: BSD-2-Clause-Patent -# -## - -# Template section for common structure definitions, template name has to end with `_TMPL` -template: - - !include PolicyServicePkg/CommonPolicy/Template_PolicyHeader.yaml - - # Template for minor version 0 of GFX structure, $(#) are replacable parameters through !expand syntax - GFX_POLICY_TMPL: > - - Power_State_Port_$(1) : - name : Power state of GFX port $(1) - length : 0x02 - value : $(2) - - # Template for minor version 1 of GFX structure, these should always be appended after - # all existed minor 0 structures, $(#) are replacable parameters through !expand syntax - GFX_POLICY_SUP1_TMPL: > - - Skip_Check_$(1) : - name : Flag to skip this controller or not - length : 0x02 - value : $(2) - minver : 0x01 - -configs: - # Policy structure metadata, will be used for policy headers and genereating unique macro definitions - - PolicyHeader: - - !expand { POLICY_HEADER_TMPL : [GFX, 'PDATAGFX', 0x01, _LENGTH_GFX_POLICY_DATA_] } - - # Main structure definitions for this policy - - GFX_POLICY_DATA : - # Structure filled with populated templates, minor version 0 first - - !expand { GFX_POLICY_TMPL : [ 0, 1] } - - !expand { GFX_POLICY_TMPL : [ 1, 1] } - - # Structure filled with populated templates, minor version 1 second - - !expand { GFX_POLICY_SUP1_TMPL : [ 0, 0] } - - !expand { GFX_POLICY_SUP1_TMPL : [ 1, 0] } +## @file +# +# Slim Bootloader CFGDATA Default File. +# +# Copyright (c) 2020, Intel Corporation. All rights reserved.
+# SPDX-License-Identifier: BSD-2-Clause-Patent +# +## + +# Template section for common structure definitions, template name has to end with `_TMPL` +template: + - !include PolicyServicePkg/CommonPolicy/Template_PolicyHeader.yaml + + # Template for minor version 0 of GFX structure, $(#) are replacable parameters through !expand syntax + GFX_POLICY_TMPL: > + - Power_State_Port_$(1) : + name : Power state of GFX port $(1) + length : 0x02 + value : $(2) + + # Template for minor version 1 of GFX structure, these should always be appended after + # all existed minor 0 structures, $(#) are replacable parameters through !expand syntax + GFX_POLICY_SUP1_TMPL: > + - Skip_Check_$(1) : + name : Flag to skip this controller or not + length : 0x02 + value : $(2) + minver : 0x01 + +configs: + # Policy structure metadata, will be used for policy headers and genereating unique macro definitions + - PolicyHeader: + - !expand { POLICY_HEADER_TMPL : [GFX, 'PDATAGFX', 0x01, _LENGTH_GFX_POLICY_DATA_] } + + # Main structure definitions for this policy + - GFX_POLICY_DATA : + # Structure filled with populated templates, minor version 0 first + - !expand { GFX_POLICY_TMPL : [ 0, 1] } + - !expand { GFX_POLICY_TMPL : [ 1, 1] } + + # Structure filled with populated templates, minor version 1 second + - !expand { GFX_POLICY_SUP1_TMPL : [ 0, 0] } + - !expand { GFX_POLICY_SUP1_TMPL : [ 1, 0] } diff --git a/PolicyServicePkg/Tools/GenCfgData.py b/PolicyServicePkg/Tools/GenCfgData.py index 4efbd28b3e..eb8dbac88a 100644 --- a/PolicyServicePkg/Tools/GenCfgData.py +++ b/PolicyServicePkg/Tools/GenCfgData.py @@ -1,2564 +1,2564 @@ -## @ GenCfgData.py -# -# Copyright (c) 2020, Intel Corporation. All rights reserved.
-# Copyright (c) Microsoft Corporation. -# SPDX-License-Identifier: BSD-2-Clause-Patent -# -## - -import os -import sys -import re -import struct -import marshal -import pprint -import string -import operator as op -import ast -import binascii -from typing import Type, final -from unicodedata import category -import uuid -from datetime import date -from collections import OrderedDict - -from CommonUtility import * - -# Generated file copyright header -__copyright_tmp__ = """/** @file - - Platform Configuration %s File. - - Copyright (c) %4d, Intel Corporation. All rights reserved.
- Copyright (c) Microsoft Corporation. - SPDX-License-Identifier: BSD-2-Clause-Patent - - This file is automatically generated. Please do NOT modify !!! - -**/ -""" - -def get_copyright_header (file_type, allow_modify = False): - file_description = { - 'yaml': 'Boot Setting', - 'dlt' : 'Delta', - 'inc' : 'C Binary Blob', - 'h' : 'C Struct Header' - } - if file_type in ['yaml', 'dlt']: - comment_char = '#' - else: - comment_char = '' - lines = __copyright_tmp__.split('\n') - if allow_modify: - lines = [line for line in lines if 'Please do NOT modify' not in line] - copyright_hdr = '\n'.join('%s%s' % (comment_char, line) for line in lines)[:-1] + '\n' - return copyright_hdr % (file_description[file_type], date.today().year) - -def check_quote (text): - if (text[0] == "'" and text[-1] == "'") or (text[0] == '"' and text[-1] == '"'): - return True - return False - -def strip_quote (text): - new_text = text.strip() - if check_quote (new_text): - return new_text[1:-1] - return text - -def strip_delimiter (text, delim): - new_text = text.strip() - if new_text: - if new_text[0] == delim[0] and new_text[-1] == delim[-1]: - return new_text[1:-1] - return text - -def bytes_to_bracket_str (bytes): - return '{ %s }' % (', '.join('0x%02x' % i for i in bytes)) - -def array_str_to_value (val_str): - val_str = val_str.strip() - val_str = strip_delimiter (val_str, '{}') - val_str = strip_quote (val_str) - value = 0 - for each in val_str.split(',')[::-1]: - each = each.strip() - value = (value << 8) | int(each, 0) - return value - -def write_lines (lines, file): - fo = open(file, "w") - fo.write (''.join ([x[0] for x in lines])) - fo.close () - -def read_lines (file): - if not os.path.exists(file): - test_file = os.path.basename(file) - if os.path.exists(test_file): - file = test_file - fi = open (file, 'r') - lines = fi.readlines () - fi.close () - return lines - -def expand_file_value (path, value_str): - result = bytearray() - match = re.match("\{\s*FILE:(.+)\}", value_str) - if match: - file_list = match.group(1).split(',') - for file in file_list: - file = file.strip() - bin_path = os.path.join(path, file) - result.extend(bytearray(open(bin_path, 'rb').read())) - return result - -class ExpressionEval(ast.NodeVisitor): - operators = { - ast.Add: op.add, - ast.Sub: op.sub, - ast.Mult: op.mul, - ast.Div: op.floordiv, - ast.Mod: op.mod, - ast.Eq: op.eq, - ast.NotEq: op.ne, - ast.Gt: op.gt, - ast.Lt: op.lt, - ast.GtE: op.ge, - ast.LtE: op.le, - ast.BitXor: op.xor, - ast.BitAnd: op.and_, - ast.BitOr: op.or_, - ast.Invert: op.invert, - ast.USub: op.neg - } - - - def __init__(self): - self._debug = False - self._expression = '' - self._namespace = {} - self._get_variable = None - - def eval(self, expr, vars={}): - self._expression = expr - if type(vars) is dict: - self._namespace = vars - self._get_variable = None - else: - self._namespace = {} - self._get_variable = vars - node = ast.parse(self._expression, mode='eval') - result = self.visit(node.body) - if self._debug: - print ('EVAL [ %s ] = %s' % (expr, str(result))) - return result - - def visit_Name(self, node): - if self._get_variable is not None: - return self._get_variable(node.id) - else: - return self._namespace[node.id] - - def visit_Num(self, node): - return node.n - - def visit_NameConstant(self, node): - return node.value - - def visit_BoolOp(self, node): - result = False - if isinstance(node.op, ast.And): - for value in node.values: - result = self.visit(value) - if not result: - break - elif isinstance(node.op, ast.Or): - for value in node.values: - result = self.visit(value) - if result: - break - return True if result else False - - def visit_UnaryOp(self, node): - val = self.visit(node.operand) - return operators[type(node.op)](val) - - def visit_BinOp(self, node): - lhs = self.visit(node.left) - rhs = self.visit(node.right) - return ExpressionEval.operators[type(node.op)](lhs, rhs) - - def visit_Compare(self, node): - right = self.visit(node.left) - result = True - for operation, comp in zip(node.ops, node.comparators): - if not result: - break - left = right - right = self.visit(comp) - result = ExpressionEval.operators[type(operation)](left, right) - return result - - def visit_Call(self, node): - if node.func.id in ['ternary']: - condition = self.visit (node.args[0]) - val_true = self.visit (node.args[1]) - val_false = self.visit (node.args[2]) - return val_true if condition else val_false - elif node.func.id in ['offset', 'length']: - if self._get_variable is not None: - return self._get_variable(node.args[0].s, node.func.id) - else: - raise ValueError("Unsupported function: " + repr(node)) - - def generic_visit(self, node): - raise ValueError("malformed node or string: " + repr(node)) - - -class CFG_YAML(): - TEMPLATE = 'template' - CONFIGS = 'configs' - VARIABLE = 'variable' - - def __init__ (self, is_policy=False): - self.log_line = False - self.allow_template = False - self.cfg_tree = None - self.tmp_tree = None - self.var_dict = None - self.def_dict = {} - self.yaml_path = '' - self.lines = [] - self.full_lines = [] - self.index = 0 - self.is_policy = is_policy - self.re_expand = re.compile (r'(.+:\s+|\s*\-\s*)!expand\s+\{\s*(\w+_TMPL)\s*:\s*\[(.+)]\s*\}') - self.re_include = re.compile (r'(.+:\s+|\s*\-\s*)!include\s+(.+)') - - @staticmethod - def count_indent (line): - return next((i for i, c in enumerate(line) if not c.isspace()), len(line)) - - @staticmethod - def substitue_args (text, arg_dict): - for arg in arg_dict: - text = text.replace ('$' + arg, arg_dict[arg]) - return text - - @staticmethod - def dprint (*args): - pass - - def process_include (self, line, insert = True): - match = self.re_include.match (line) - if not match: - raise Exception ("Invalid !include format '%s' !" % line.strip()) - - prefix = match.group(1) - include = match.group(2) - if prefix.strip() == '-': - prefix = '' - adjust = 0 - else: - adjust = 2 - - include = strip_quote (include) - request = CFG_YAML.count_indent (line) + adjust - - if self.log_line: - # remove the include line itself - del self.full_lines[-1] - - inc_path = os.path.join (self.yaml_path, include) - if not os.path.exists(inc_path): - # try relative path to project root - try_path = os.path.join(os.path.dirname (os.path.realpath(__file__)), "../..", include) - if os.path.exists(try_path): - inc_path = try_path - else: - raise Exception ("ERROR: Cannot open file '%s'." % inc_path) - - lines = read_lines (inc_path) - - current = 0 - same_line = False - for idx, each in enumerate (lines): - start = each.lstrip() - if start == '' or start[0] == '#': - continue - - if start[0] == '>': - # append the content directly at the same line - same_line = True - - start = idx - current = CFG_YAML.count_indent (each) - break - - lines = lines[start+1:] if same_line else lines[start:] - leading = '' - if same_line: - request = len(prefix) - leading = '>' - - lines = [prefix + '%s\n' % leading] + [' ' * request + i[current:] for i in lines] - if insert: - self.lines = lines + self.lines - - return lines - - def process_expand (self, line): - match = self.re_expand.match(line) - if not match: - raise Exception ("Invalid !expand format '%s' !" % line.strip()) - lines = [] - prefix = match.group(1) - temp_name = match.group(2) - args = match.group(3) - - if prefix.strip() == '-': - indent = 0 - else: - indent = 2 - lines = self.process_expand_template (temp_name, prefix, args, indent) - self.lines = lines + self.lines - - - def process_expand_template (self, temp_name, prefix, args, indent = 2): - # expand text with arg substitution - if temp_name not in self.tmp_tree: - raise Exception ("Could not find template '%s' !" % temp_name) - parts = args.split(',') - parts = [i.strip() for i in parts] - num = len(parts) - arg_dict = dict(zip( ['(%d)' % (i + 1) for i in range(num)], parts)) - str_data = self.tmp_tree[temp_name] - text = DefTemplate(str_data).safe_substitute(self.def_dict) - text = CFG_YAML.substitue_args (text, arg_dict) - target = CFG_YAML.count_indent (prefix) + indent - current = CFG_YAML.count_indent (text) - padding = target * ' ' - if indent == 0: - leading = [] - else: - leading = [prefix + '\n'] - text = leading + [(padding + i + '\n')[current:] for i in text.splitlines()] - return text - - - def load_file (self, yaml_file): - self.index = 0 - self.lines = read_lines (yaml_file) - - - def peek_line (self): - if len(self.lines) == 0: - return None - else: - return self.lines[0] - - - def put_line (self, line): - self.lines.insert (0, line) - if self.log_line: - del self.full_lines[-1] - - - def get_line (self): - if len(self.lines) == 0: - return None - else: - line = self.lines.pop(0) - if self.log_line: - self.full_lines.append (line.rstrip()) - return line - - - def get_multiple_line (self, indent): - text = '' - newind = indent + 1 - while True: - line = self.peek_line () - if line is None: - break - sline = line.strip() - if sline != '': - newind = CFG_YAML.count_indent(line) - if newind <= indent: - break - self.get_line () - if sline != '': - text = text + line - return text - - - def traverse_cfg_tree (self, handler): - def _traverse_cfg_tree (root, level = 0): - # config structure - for key in root: - if type(root[key]) is OrderedDict: - level += 1 - handler (key, root[key], level) - _traverse_cfg_tree (root[key], level) - level -= 1 - _traverse_cfg_tree (self.cfg_tree) - - - def count (self): - def _count (name, cfgs, level): - num[0] += 1 - num = [0] - self.traverse_cfg_tree (_count) - return num[0] - - - def parse (self, parent_name = '', curr = None, level = 0): - child = None - last_indent = None - temp_chk = {} - - while True: - line = self.get_line () - if line is None: - break - - curr_line = line.strip() - if curr_line == '' or curr_line[0] == '#': - continue - - indent = CFG_YAML.count_indent(line) - if last_indent is None: - last_indent = indent - - if indent != last_indent: - # outside of current block, put the line back to queue - self.put_line (' ' * indent + curr_line) - - if curr_line.endswith (': >'): - # multiline marker - old_count = len(self.full_lines) - line = self.get_multiple_line (indent) - if self.log_line and not self.allow_template and '!include ' in line: - # expand include in template - new_lines = [] - lines = line.splitlines() - for idx, each in enumerate(lines): - if '!include ' in each: - new_line = ''.join(self.process_include (each, False)) - new_lines.append(new_line) - else: - new_lines.append(each) - self.full_lines = self.full_lines[:old_count] + new_lines - curr_line = curr_line + line - - if indent > last_indent: - # child nodes - if child is None: - raise Exception ('Unexpected format at line: %s' % (curr_line)) - - level += 1 - self.parse (key, child, level) - level -= 1 - - line = self.peek_line () - if line is not None: - curr_line = line.strip() - indent = CFG_YAML.count_indent(line) - if indent >= last_indent: - # consume the line - self.get_line () - else: - # end of file - indent = -1 - - if curr is None: - curr = OrderedDict() - - if indent < last_indent: - return curr - - marker1 = curr_line[0] - marker2 = curr_line[-1] - start = 1 if marker1 == '-' else 0 - pos = curr_line.find(': ') - if pos > 0: - child = None - key = curr_line[start:pos].strip() - if curr_line[pos + 2] == '>': - curr[key] = curr_line[pos + 3:] - else: - # XXXX: !include / !expand - if '!include ' in curr_line: - self.process_include (line) - elif '!expand ' in curr_line: - if self.allow_template and not self.log_line: - self.process_expand (line) - else: - value_str = curr_line[pos + 2:].strip() - if key == "IdTag" or key == "ArrayIdTag": - # Insert the headers corresponds to this ID tag from here, most contents are hardcoded for now - cfg_hdr = OrderedDict() - cfg_hdr['length'] = '0x04' - cfg_hdr['value'] = '{0x01:2b, (_LENGTH_%s_/4):10b, %d:4b, 0:4b, %s:12b}' % (parent_name, 0 if key == "IdTag" else 1, value_str) - curr['CfgHeader'] = cfg_hdr - - cnd_val = OrderedDict() - cnd_val['length'] = '0x04' - cnd_val['value'] = '0x00000000' - curr['CondValue'] = cnd_val - else: - curr[key] = value_str - if self.log_line and value_str[0] == '{': - # expand {FILE: xxxx} format in the log line - if value_str[1:].rstrip().startswith('FILE:'): - value_bytes = expand_file_value (self.yaml_path, value_str) - value_str = bytes_to_bracket_str (value_bytes) - self.full_lines[-1] = line[:indent] + curr_line[:pos + 2] + value_str - - elif marker2 == ':': - child = OrderedDict() - key = curr_line[start:-1].strip() - if key == '$ACTION': - # special virtual nodes, rename to ensure unique key - key = '$ACTION_%04X' % self.index - self.index += 1 - if key in curr: - if key not in temp_chk: - # check for duplicated keys at same level - temp_chk[key] = 1 - else: - raise Exception ("Duplicated item '%s:%s' found !" % (parent_name, key)) - - curr[key] = child - if self.var_dict is None and key == CFG_YAML.VARIABLE: - self.var_dict = child - if self.tmp_tree is None and key == CFG_YAML.TEMPLATE: - self.tmp_tree = child - if self.var_dict: - for each in self.var_dict: - txt = self.var_dict[each] - if type(txt) is str: - self.def_dict['(%s)' % each] = txt - if self.tmp_tree and key == CFG_YAML.CONFIGS: - if not self.is_policy: - # apply template for the main configs - self.allow_template = True - child['Signature'] = OrderedDict() - child['Signature']['length'] = '0x04' - child['Signature']['value'] = "{'CFGD'}" - - child['HeaderLength'] = OrderedDict() - child['HeaderLength']['length'] = '0x01' - child['HeaderLength']['value'] = '0x10' - - child['Reserved'] = OrderedDict() - child['Reserved']['length'] = '0x03' - child['Reserved']['value'] = '{0,0,0}' - - child['UsedLength'] = OrderedDict() - child['UsedLength']['length'] = '0x04' - child['UsedLength']['value'] = '_LENGTH_' - - # This will be rounded up to 4KB aligned - child['TotalLength'] = OrderedDict() - child['TotalLength']['length'] = '0x04' - child['TotalLength']['value'] = '(_LENGTH_/0x1000 + 1)*0x1000' - else: - child = None - # - !include cfg_opt.yaml - if '!include ' in curr_line: - self.process_include (line) - - return curr - - - def load_yaml (self, opt_file): - self.var_dict = None - self.yaml_path = os.path.dirname (opt_file) - self.load_file (opt_file) - yaml_tree = self.parse () - self.tmp_tree = yaml_tree[CFG_YAML.TEMPLATE] - self.cfg_tree = yaml_tree[CFG_YAML.CONFIGS] - return self.cfg_tree - - - def expand_yaml (self, opt_file): - self.log_line = True - self.load_yaml (opt_file) - self.log_line = False - text = '\n'.join (self.full_lines) - self.full_lines = [] - return text - - -class DefTemplate(string.Template): - idpattern = '\([_A-Z][_A-Z0-9]*\)|[_A-Z][_A-Z0-9]*' - - -class CGenCfgData: - STRUCT = '$STRUCT' - bits_width = {'b':1, 'B':8, 'W':16, 'D':32, 'Q':64} - builtin_option = {'$EN_DIS' : [('0', 'Disable'), ('1', 'Enable')]} - exclude_struct = ['GPIO_GPP_*', 'GPIO_CFG_DATA', 'GpioConfPad*', 'GpioPinConfig', - 'BOOT_OPTION*', 'PLATFORMID_CFG_DATA', '\w+_Half[01]'] - include_tag = ['GPIO_CFG_DATA'] - keyword_set = set(['name', 'type', 'option', 'help', 'length', 'value', 'order', 'struct', 'condition', 'minver']) - - def __init__(self): - self.initialize () - - - def initialize (self): - self._cfg_tree = {} - self._tmp_tree = {} - self._cfg_list = [] - self._cfg_page = {'root': {'title': '', 'child': []}} - self._cur_page = '' - self._var_dict = {} - self._def_dict = {} - self._yaml_path = '' - - - @staticmethod - def deep_convert_dict (layer): - # convert OrderedDict to list + dict - new_list = layer - if isinstance(layer, OrderedDict): - new_list = list (layer.items()) - for idx, pair in enumerate (new_list): - new_node = CGenCfgData.deep_convert_dict (pair[1]) - new_list[idx] = dict({pair[0] : new_node}) - return new_list - - - @staticmethod - def deep_convert_list (layer): - if isinstance(layer, list): - od = OrderedDict({}) - for each in layer: - if isinstance(each, dict): - key = next(iter(each)) - od[key] = CGenCfgData.deep_convert_list(each[key]) - return od - else: - return layer - - - @staticmethod - def expand_include_files (file_path, cur_dir = ''): - if cur_dir == '': - cur_dir = os.path.dirname(file_path) - file_path = os.path.basename(file_path) - - input_file_path = os.path.join(cur_dir, file_path) - file = open(input_file_path, "r") - lines = file.readlines() - file.close() - - new_lines = [] - for line_num, line in enumerate(lines): - match = re.match("^!include\s*(.+)?$", line.strip()) - if match: - inc_path = match.group(1) - tmp_path = os.path.join(cur_dir, inc_path) - org_path = tmp_path - if not os.path.exists(tmp_path): - cur_dir = os.path.join(os.path.dirname (os.path.realpath(__file__)), "..", "..") - tmp_path = os.path.join(cur_dir, inc_path) - if not os.path.exists(tmp_path): - raise Exception ("ERROR: Cannot open include file '%s'." % org_path) - else: - new_lines.append (('# Included from file: %s\n' % inc_path, tmp_path, 0)) - new_lines.append (('# %s\n' % ('=' * 80), tmp_path, 0)) - new_lines.extend (CGenCfgData.expand_include_files (inc_path, cur_dir)) - else: - new_lines.append ((line, input_file_path, line_num)) - - return new_lines - - - @staticmethod - def format_struct_field_name (input, count = 0): - name = '' - cap = True - if '_' in input: - input = input.lower() - for each in input: - if each == '_': - cap = True - continue - elif cap: - each = each.upper() - cap = False - name = name + each - - if count > 1: - name = '%s[%d]' % (name, count) - - return name - - def get_last_error (self): - return '' - - - def get_variable (self, var, attr = 'value'): - if var in self._var_dict: - var = self._var_dict[var] - return var - - item = self.locate_cfg_item (var, False) - if item is None: - raise ValueError ("Cannot find variable '%s' !" % var) - - if item: - if 'indx' in item: - item = self.get_item_by_index (item['indx']) - if attr == 'offset': - var = item['offset'] - elif attr == 'length': - var = item['length'] - elif attr == 'value': - var = self.get_cfg_item_value (item) - else: - raise ValueError ("Unsupported variable attribute '%s' !" % attr) - return var - - - def eval (self, expr): - def _handler (pattern): - if pattern.group(1): - target = 1 - else: - target = 2 - result = self.get_variable(pattern.group(target)) - if result is None: - raise ValueError('Unknown variable $(%s) !' % pattern.group(target)) - return hex(result) - - expr_eval = ExpressionEval () - if '$' in expr: - # replace known variable first - expr = re.sub(r'\$\(([_a-zA-Z][\w\.]*)\)|\$([_a-zA-Z][\w\.]*)', _handler, expr) - return expr_eval.eval(expr, self.get_variable) - - - def get_cfg_list (self, page_id = None): - if page_id is None: - # return full list - return self._cfg_list - else: - # build a new list for items under a page ID - cfgs = [i for i in self._cfg_list if i['cname'] and (i['page'] == page_id)] - return cfgs - - - def get_cfg_page (self): - return self._cfg_page - - def get_cfg_item_length (self, item): - return item['length'] - - def get_cfg_item_value (self, item, array = False): - value_str = item['value'] - length = item['length'] - return self.get_value (value_str, length, array) - - - def format_value_to_str (self, value, bit_length, old_value = ''): - # value is always int - length = (bit_length + 7) // 8 - fmt = '' - if old_value.startswith ('0x'): - fmt = '0x' - elif old_value and (old_value[0] in ['"', "'", '{']): - fmt = old_value[0] - else: - fmt = '' - - bvalue = value_to_bytearray (value, length) - if fmt in ['"', "'"]: - svalue = bvalue.rstrip(b'\x00').decode() - value_str = fmt + svalue + fmt - elif fmt == "{": - value_str = '{ ' + ', '.join(['0x%02x' % i for i in bvalue]) + ' }' - elif fmt == '0x': - hex_len = length * 2 - if len(old_value) == hex_len + 2: - fstr = '0x%%0%dX' % hex_len - else: - fstr = '0x%X' - value_str = fstr % value - else: - if length <= 2: - value_str = '%d' % value - elif length <= 8: - value_str = '0x%x' % value - else: - value_str = '{ ' + ', '.join(['0x%02x' % i for i in bvalue]) + ' }' - return value_str - - - def reformat_value_str (self, value_str, bit_length, old_value = None): - value = self.parse_value (value_str, bit_length, False) - if old_value is None: - old_value = value_str - new_value = self.format_value_to_str (value, bit_length, old_value) - return new_value - - - def get_value (self, value_str, bit_length, array = True): - value_str = value_str.strip() - if len(value_str) == 0: - return 0 - if value_str[0] == "'" and value_str[-1] == "'" or \ - value_str[0] == '"' and value_str[-1] == '"': - value_str = value_str[1:-1] - bvalue = bytearray (value_str.encode()) - if len(bvalue) == 0: - bvalue = bytearray(b'\x00') - if array: - return bvalue - else: - return bytes_to_value (bvalue) - else: - if value_str[0] in '{' : - value_str = value_str[1:-1].strip() - value = 0 - for each in value_str.split(',')[::-1]: - each = each.strip() - value = (value << 8) | int(each, 0) - if array: - length = (bit_length + 7) // 8 - return value_to_bytearray (value, length) - else: - return value - - - def parse_value (self, value_str, bit_length, array = True): - length = (bit_length + 7) // 8 - if check_quote(value_str): - value_str = bytes_to_bracket_str(value_str[1:-1].encode()) - elif (',' in value_str) and (value_str[0] != '{'): - value_str = '{ %s }' % value_str - if value_str[0] == '{': - result = expand_file_value (self._yaml_path, value_str) - if len(result) == 0 : - bin_list = value_str[1:-1].split(',') - value = 0 - bit_len = 0 - unit_len = 1 - for idx, element in enumerate(bin_list): - each = element.strip() - if len(each) == 0: - continue - - in_bit_field = False - if each[0] in "'" + '"': - each_value = bytearray(each[1:-1], 'utf-8') - elif ':' in each: - match = re.match("^(.+):(\d+)([b|B|W|D|Q])$", each) - if match is None: - raise SystemExit("Exception: Invald value list format '%s' !" % each) - if match.group(1) == '0' and match.group(2) == '0': - unit_len = CGenCfgData.bits_width[match.group(3)] // 8 - cur_bit_len = int(match.group(2)) * CGenCfgData.bits_width[match.group(3)] - value += ((self.eval(match.group(1)) & (1< 0: - if bit_len % 8 != 0: - raise SystemExit("Exception: Invalid bit field alignment '%s' !" % value_str) - result.extend(value_to_bytes(value, bit_len // 8)) - value = 0 - bit_len = 0 - - result.extend(each_value) - - elif check_quote (value_str): - result = bytearray(value_str[1:-1], 'utf-8') # Excluding quotes - else: - result = value_to_bytearray (self.eval(value_str), length) - - if len(result) < length: - result.extend(b'\x00' * (length - len(result))) - elif len(result) > length: - raise SystemExit ("Exception: Value '%s' is too big to fit into %d bytes !" % (value_str, length)) - - if array: - return result - else: - return bytes_to_value(result) - - return result - - - def get_cfg_item_options (self, item): - tmp_list = [] - if item['type'] == "Combo": - if item['option'] in CGenCfgData.builtin_option: - for op_val, op_str in CGenCfgData.builtin_option[item['option']]: - tmp_list.append((op_val, op_str)) - else: - opt_list = item['option'].split(',') - for option in opt_list: - option = option.strip() - try: - (op_val, op_str) = option.split(':') - except: - raise SystemExit ("Exception: Invalid option format '%s' for item '%s' !" % (option, item['cname'])) - tmp_list.append((op_val, op_str)) - return tmp_list - - - def get_page_title(self, page_id, top = None): - if top is None: - top = self.get_cfg_page()['root'] - for node in top['child']: - page_key = next(iter(node)) - if page_id == page_key: - return node[page_key]['title'] - else: - result = self.get_page_title (page_id, node[page_key]) - if result is not None: - return result - return None - - - def print_pages(self, top=None, level=0): - if top is None: - top = self.get_cfg_page()['root'] - for node in top['child']: - page_id = next(iter(node)) - print('%s%s: %s' % (' ' * level, page_id, node[page_id]['title'])) - level += 1 - self.print_pages(node[page_id], level) - level -= 1 - - - def get_item_by_index (self, index): - return self._cfg_list[index] - - - def get_item_by_path (self, path): - node = self.locate_cfg_item (path) - if node: - return self.get_item_by_index (node['indx']) - else: - return None - - def locate_cfg_path (self, item): - def _locate_cfg_path (root, level = 0): - # config structure - if item is root: - return path - for key in root: - if type(root[key]) is OrderedDict: - level += 1 - path.append(key) - ret = _locate_cfg_path (root[key], level) - if ret: - return ret - path.pop() - return None - path = [] - return _locate_cfg_path (self._cfg_tree) - - - def locate_cfg_item (self, path, allow_exp = True): - def _locate_cfg_item (root, path, level = 0): - if len(path) == level: - return root - next_root = root.get(path[level], None) - if next_root is None: - if allow_exp: - raise Exception ('Not a valid CFG config option path: %s' % '.'.join(path[:level+1])) - else: - return None - return _locate_cfg_item (next_root, path, level + 1) - - path_nodes = path.split('.') - return _locate_cfg_item (self._cfg_tree, path_nodes) - - - def traverse_cfg_tree (self, handler, top = None): - def _traverse_cfg_tree (root, level = 0): - # config structure - for key in root: - if type(root[key]) is OrderedDict: - level += 1 - handler (key, root[key], level) - _traverse_cfg_tree (root[key], level) - level -= 1 - - if top is None: - top = self._cfg_tree - _traverse_cfg_tree (top) - - - def print_cfgs(self, root = None, short = True, print_level = 256): - def _print_cfgs (name, cfgs, level): - - if 'indx' in cfgs: - act_cfg = self.get_item_by_index (cfgs['indx']) - else: - offset = 0 - length = 0 - value = '' - path='' - if CGenCfgData.STRUCT in cfgs: - cfg = cfgs[CGenCfgData.STRUCT] - offset = int(cfg['offset']) - length = int(cfg['length']) - if 'value' in cfg: - value = cfg['value'] - if length == 0: - return - act_cfg = dict({'value' : value, 'offset' : offset, 'length' : length}) - value = act_cfg['value'] - bit_len = act_cfg['length'] - offset = (act_cfg['offset'] + 7) // 8 - if value != '': - try: - value = self.reformat_value_str (act_cfg['value'], act_cfg['length']) - except: - value = act_cfg['value'] - length = bit_len // 8 - bit_len = '(%db)' % bit_len if bit_len % 8 else '' * 4 - if level <= print_level: - if short and len(value) > 40: - value = '%s ... %s' % (value[:20] , value[-20:]) - print('%04X:%04X%-6s %s%s : %s' % (offset, length, bit_len, ' ' * level, name, value)) - - self.traverse_cfg_tree (_print_cfgs) - - - def get_cfg_tree(self): - return self._cfg_tree - - - def set_cfg_tree(self, cfg_tree): - self._cfg_tree = cfg_tree - - - def merge_cfg_tree(self, root, other_root): - ret = OrderedDict () - prev_key = None - for other_key in other_root: - if other_key not in root: - ret[other_key] = other_root[other_key] - else: - # this is a good time to check to see if we miss anything from previous root elements - found_last = False - for key in root: - if key == prev_key: - found_last = True - continue - if prev_key == None: - found_last = True - if found_last: - ret[key] = root[key] - if key == other_key: - prev_key = other_key - break - - if type(root[other_key]) is OrderedDict and type(other_root[other_key]) is OrderedDict: - # if they are both non-leaf, great, process recursively - ret[other_key] = self.merge_cfg_tree (root[other_key], other_root[other_key]) - elif type(root[other_key]) is OrderedDict or type(other_root[other_key]) is OrderedDict: - raise Exception ("Two yamls files have hierachy mismatch!!!") - else: - # this is duplicate value in from both roots, take original root as principal - ret[other_key] = root[other_key] - - # See if there is any leftovers - found_last = False - for key in root: - if key == prev_key: - found_last = True - continue - if prev_key == None: - found_last = True - if found_last: - ret[key] = root[key] - if key == other_key: - prev_key = other_key - break - return ret - - - def build_var_dict (self): - def _build_var_dict (name, cfgs, level): - if level <= 2: - if CGenCfgData.STRUCT in cfgs: - struct_info = cfgs[CGenCfgData.STRUCT] - self._var_dict['_LENGTH_%s_' % name] = struct_info['length'] // 8 - self._var_dict['_OFFSET_%s_' % name] = struct_info['offset'] // 8 - - self._var_dict = {} - self.traverse_cfg_tree (_build_var_dict) - self._var_dict['_LENGTH_'] = self._cfg_tree[CGenCfgData.STRUCT]['length'] // 8 - return 0 - - - def add_cfg_page(self, child, parent, title=''): - def _add_cfg_page(cfg_page, child, parent): - key = next(iter(cfg_page)) - if parent == key: - cfg_page[key]['child'].append({child: {'title': title, - 'child': []}}) - return True - else: - result = False - for each in cfg_page[key]['child']: - if _add_cfg_page(each, child, parent): - result = True - break - return result - - return _add_cfg_page(self._cfg_page, child, parent) - - - def set_cur_page(self, page_str): - if not page_str: - return - - if ',' in page_str: - page_list = page_str.split(',') - else: - page_list = [page_str] - for page_str in page_list: - parts = page_str.split(':') - if len(parts) in [1, 3]: - page = parts[0].strip() - if len(parts) == 3: - # it is a new page definition, add it into tree - parent = parts[1] if parts[1] else 'root' - parent = parent.strip() - if parts[2][0] == '"' and parts[2][-1] == '"': - parts[2] = parts[2][1:-1] - - if not self.add_cfg_page(page, parent, parts[2]): - raise SystemExit("Error: Cannot find parent page '%s'!" % parent) - else: - raise SystemExit("Error: Invalid page format '%s' !" % page_str) - self._cur_page = page - - - def extend_variable (self, line): - # replace all variables - if line == '': - return line - loop = 2 - while loop > 0: - line_after = DefTemplate(line).safe_substitute(self._def_dict) - if line == line_after: - break - loop -= 1 - line = line_after - return line_after - - def reformat_number_per_type (self, itype, value): - if check_quote(value) or value.startswith('{'): - return value - parts = itype.split(',') - if len(parts) > 3 and parts[0] == 'EditNum': - num_fmt = parts[1].strip() - else: - num_fmt = '' - if num_fmt == 'HEX' and not value.startswith('0x'): - value = '0x%X' % int(value, 10) - elif num_fmt == 'DEC' and value.startswith('0x'): - value = '%d' % int(value, 16) - return value - - def add_cfg_item(self, name, item, offset, path): - - self.set_cur_page (item.get('page', '')) - - if name[0] == '$': - # skip all virtual node - return 0 - - - if not set(item).issubset(CGenCfgData.keyword_set): - for each in list(item): - if each not in CGenCfgData.keyword_set: - raise Exception ("Invalid attribute '%s' for '%s'!" % (each, '.'.join(path))) - - length = item.get('length', 0) - if type(length) is str: - match = re.match("^(\d+)([b|B|W|D|Q])([B|W|D|Q]?)\s*$", length) - if match: - unit_len = CGenCfgData.bits_width[match.group(2)] - length = int(match.group(1), 10) * unit_len - else: - try: - length = int(length, 0) * 8 - except: - raise Exception ("Invalid length field '%s' for '%s' !" % (length, '.'.join(path))) - - if offset % 8 > 0: - raise Exception ("Invalid alignment for field '%s' for '%s' !" % (name, '.'.join(path))) - else: - # define is length in bytes - length = length * 8 - - if not name.isidentifier(): - raise Exception ("Invalid config name '%s' for '%s' !" % (name, '.'.join(path))) - - - itype = str(item.get('type', 'Reserved')) - value = str(item.get('value', '')) - if value: - if not (check_quote(value) or value.startswith('{')): - if ',' in value: - value = '{ %s }' % value - else: - value = self.reformat_number_per_type (itype, value) - - help = str(item.get('help', '')) - if '\n' in help: - help = ' '.join ([i.strip() for i in help.splitlines()]) - - option = str(item.get('option', '')) - if '\n' in option: - option = ' '.join ([i.strip() for i in option.splitlines()]) - - # extend variables for value and condition - condition = str(item.get('condition', '')) - if condition: - condition = self.extend_variable (condition) - value = self.extend_variable (value) - - order = str(item.get('order', '')) - if order: - if '.' in order: - (major, minor) = order.split('.') - order = int (major, 16) - else: - order = int (order, 16) - else: - order = offset - - cfg_item = dict() - cfg_item['length'] = length - cfg_item['offset'] = offset - cfg_item['value'] = value - cfg_item['type'] = itype - cfg_item['cname'] = str(name) - cfg_item['name'] = str(item.get('name', '')) - cfg_item['help'] = help - cfg_item['option'] = option - cfg_item['page'] = self._cur_page - cfg_item['order'] = order - cfg_item['path'] = '.'.join(path) - cfg_item['condition'] = condition - if 'struct' in item: - cfg_item['struct'] = item['struct'] - self._cfg_list.append(cfg_item) - - item['indx'] = len(self._cfg_list) - 1 - - # remove used info for reducing pkl size - item.pop('option', None) - item.pop('condition', None) - item.pop('help', None) - item.pop('name', None) - item.pop('page', None) - - return length - - - def build_cfg_list (self, cfg_name ='', top = None, path = [], info = {'offset': 0}): - if top is None: - top = self._cfg_tree - - start = info['offset'] - is_leaf = True - for key in top: - path.append(key) - if type(top[key]) is OrderedDict: - is_leaf = False - self.build_cfg_list(key, top[key], path, info) - path.pop() - - if is_leaf: - length = self.add_cfg_item(cfg_name, top, info['offset'], path) - info['offset'] += length - elif cfg_name == '' or (cfg_name and cfg_name[0] != '$'): - # check first element for struct - first = next(iter(top)) - struct_str = CGenCfgData.STRUCT - if first != struct_str: - struct_node = OrderedDict({}) - top[struct_str] = struct_node - top.move_to_end (struct_str, False) - else: - struct_node = top[struct_str] - struct_node['offset'] = start - if len(path) == 1: - # Round up first layer tree to be 4 Byte aligned - info['offset'] = (info['offset'] + 31) & (~31) - struct_node['length'] = (info['offset'] - start + 31) & (~31) - else: - struct_node['length'] = info['offset'] - start - if struct_node['length'] % 8 != 0: - raise SystemExit("Error: Bits length not aligned for %s !" % str(path)) - - - def get_field_value (self, top = None): - def _get_field_value (name, cfgs, level): - if 'indx' in cfgs: - act_cfg = self.get_item_by_index (cfgs['indx']) - if act_cfg['length'] == 0: - return - value = self.get_value (act_cfg['value'], act_cfg['length'], False) - set_bits_to_bytes (result, act_cfg['offset'] - struct_info['offset'], act_cfg['length'], value) - - if top is None: - top = self._cfg_tree - struct_info = top[CGenCfgData.STRUCT] - result = bytearray ((struct_info['length'] + 7) // 8) - self.traverse_cfg_tree (_get_field_value, top) - return result - - - def set_field_value (self, top, value_bytes, force = False): - def _set_field_value (name, cfgs, level): - if 'indx' not in cfgs: - return - act_cfg = self.get_item_by_index (cfgs['indx']) - if force or act_cfg['value'] == '': - value = get_bits_from_bytes (full_bytes, act_cfg['offset'] - struct_info['offset'], act_cfg['length']) - act_val = act_cfg['value'] - if act_val == '': - act_val = '%d' % value - act_val = self.reformat_number_per_type (act_cfg['type'], act_val) - act_cfg['value'] = self.format_value_to_str (value, act_cfg['length'], act_val) - - if 'indx' in top: - # it is config option - value = bytes_to_value (value_bytes) - act_cfg = self.get_item_by_index (top['indx']) - act_cfg['value'] = self.format_value_to_str (value, act_cfg['length'], act_cfg['value']) - else: - # it is structure - struct_info = top[CGenCfgData.STRUCT] - length = struct_info['length'] // 8 - full_bytes = bytearray(value_bytes[:length]) - if len(full_bytes) < length: - full_bytes.extend(bytearray(length - len(value_bytes))) - self.traverse_cfg_tree (_set_field_value, top) - - - def update_def_value (self): - def _update_def_value (name, cfgs, level): - if 'indx' in cfgs: - act_cfg = self.get_item_by_index (cfgs['indx']) - if act_cfg['value'] != '' and act_cfg['length'] > 0: - try: - act_cfg['value'] = self.reformat_value_str (act_cfg['value'], act_cfg['length']) - except: - raise Exception ("Invalid value expression '%s' for '%s' !" % (act_cfg['value'], act_cfg['path'])) - else: - if CGenCfgData.STRUCT in cfgs and 'value' in cfgs[CGenCfgData.STRUCT]: - curr = cfgs[CGenCfgData.STRUCT] - value_bytes = value_to_bytearray (self.eval(curr['value']), (curr['length'] + 7) // 8) - self.set_field_value (cfgs, value_bytes) - - self.traverse_cfg_tree (_update_def_value, self._cfg_tree) - - - def evaluate_condition (self, item): - expr = item['condition'] - result = self.parse_value (expr, 1, False) - return result - - - def load_default_from_bin (self, bin_data): - self.set_field_value(self._cfg_tree, bin_data, True) - - - def generate_binary_array (self): - return self.get_field_value() - - def generate_binary (self, bin_file_name): - bin_file = open(bin_file_name, "wb") - bin_file.write (self.generate_binary_array ()) - bin_file.close() - return 0 - - def write_delta_file (self, out_file, platform_id, out_lines): - dlt_fd = open (out_file, "w") - dlt_fd.write ("%s\n" % get_copyright_header('dlt', True)) - dlt_fd.write ('#\n') - dlt_fd.write ('# Delta configuration values for platform ID 0x%04X\n' % platform_id) - dlt_fd.write ('#\n\n') - for line in out_lines: - dlt_fd.write ('%s\n' % line) - dlt_fd.close() - - - def override_default_value(self, dlt_file): - error = 0 - dlt_lines = CGenCfgData.expand_include_files(dlt_file) - - platform_id = None - for line, file_path, line_num in dlt_lines: - line = line.strip() - if not line or line.startswith('#'): - continue - match = re.match("\s*([\w\.]+)\s*\|\s*(.+)", line) - if not match: - raise Exception("Unrecognized line '%s' (File:'%s' Line:%d) !" % - (line, file_path, line_num + 1)) - - path = match.group(1) - value_str = match.group(2) - top = self.locate_cfg_item (path) - if not top: - raise Exception( - "Invalid configuration '%s' (File:'%s' Line:%d) !" % - (path, file_path, line_num + 1)) - - if 'indx' in top: - act_cfg = self.get_item_by_index (top['indx']) - bit_len = act_cfg['length'] - else: - struct_info = top[CGenCfgData.STRUCT] - bit_len = struct_info['length'] - - value_bytes = self.parse_value (value_str, bit_len) - self.set_field_value (top, value_bytes, True) - - if path == 'PLATFORMID_CFG_DATA.PlatformId': - platform_id = value_str - - if platform_id is None: - platform_id = 0 - print("PLATFORMID_CFG_DATA.PlatformId is missing in file '%s' !" % (dlt_file)) - - return error - - - def generate_delta_file_from_bin (self, delta_file, old_data, new_data, full=False): - self.load_default_from_bin (new_data) - lines = [] - tag_name = '' - level = 0 - platform_id = None - def_platform_id = 0 - - for item in self._cfg_list: - old_val = get_bits_from_bytes (old_data, item['offset'], item['length']) - new_val = get_bits_from_bytes (new_data, item['offset'], item['length']) - - full_name = item['path'] - if 'PLATFORMID_CFG_DATA.PlatformId' == full_name: - def_platform_id = old_val - platform_id = new_val - elif item['type'] != 'Reserved' and ((new_val != old_val) or full): - val_str = self.reformat_value_str (item['value'], item['length']) - text = '%-40s | %s' % (full_name, val_str) - lines.append(text) - - if def_platform_id == platform_id: - platform_id = def_platform_id - - lines.insert(0, '%-40s | %s\n\n' % - ('PLATFORMID_CFG_DATA.PlatformId', '0x%04X' % platform_id)) - - if platform_id is None: - print ("Platform ID is not set and will be configured to 0") - platform_id = 0 - - self.write_delta_file (delta_file, platform_id, lines) - return 0 - - - def generate_delta_svd_from_bin (self, old_data, new_data): - self.load_default_from_bin (new_data) - lines = [] - tag_name = '' - level = 0 - platform_id = None - def_platform_id = 0 - items = [] - - for item in self._cfg_list: - old_val = get_bits_from_bytes (old_data, item['offset'], item['length']) - new_val = get_bits_from_bytes (new_data, item['offset'], item['length']) - - full_name = item['path'] - if 'PLATFORMID_CFG_DATA.PlatformId' == full_name: - def_platform_id = old_val - platform_id = new_val - elif item['type'] != 'Reserved' and (new_val != old_val): - val_str = self.reformat_value_str (item['value'], item['length']) - text = '%-40s | %s' % (full_name, val_str) - item = self.locate_cfg_item(item['path']) - if item is None: - raise Exception ("Failed to locate item from path: %s" % item['path']) - items.append(item) - - execs = [] - # The idea is that the 1st level tag content will be regenerated if changed - for item in items: - exec = self.locate_exec_from_item (item) - if exec == None: - raise Exception ("Failed to find the immediate executive tree for an item") - if exec not in execs: - execs.append (exec) - - bytes_array = [] - for exec in execs: - bytes = self.get_field_value (exec) - offset = 0 - offset += int(exec['CfgHeader']['length'], 0) - offset += int(exec['CondValue']['length'], 0) - bytes_array.append (bytes[offset:]) - - # self.write_delta_file (delta_file, platform_id, lines) - return (execs, bytes_array) - - def locate_exec_from_item (self, item): - - def _locate_exec_from_item (name, cfgs, level): - if level == 1: - exec[0] = cfgs - elif cfgs == item: - exec[1] = exec[0] - - exec = [None, None] - self.traverse_cfg_tree (_locate_exec_from_item, self._cfg_tree) - return exec[1] - - def locate_exec_from_tag (self, tag): - - def _locate_exec_from_tag (name, cfgs, level): - if level == 1: - exec[0] = cfgs - if CGenCfgData.STRUCT in cfgs: - cfghdr = self.get_item_by_index (cfgs['CfgHeader']['indx']) - tag_val = array_str_to_value(cfghdr['value']) >> 20 - if tag_val == tag: - exec[1] = exec[0] - - exec = [None, None] - self.traverse_cfg_tree (_locate_exec_from_tag, self._cfg_tree) - return exec[1] - - def generate_delta_file(self, delta_file, bin_file, bin_file2, full=False): - fd = open (bin_file, 'rb') - new_data = bytearray(fd.read()) - fd.close() - - if bin_file2 == '': - old_data = self.generate_binary_array() - else: - old_data = new_data - fd = open (bin_file2, 'rb') - new_data = bytearray(fd.read()) - fd.close() - - return self.generate_delta_file_from_bin (delta_file, old_data, new_data, full) - - - def prepare_marshal (self, is_save): - if is_save: - # Ordered dict is not marshallable, convert to list - self._cfg_tree = CGenCfgData.deep_convert_dict (self._cfg_tree) - else: - # Revert it back - self._cfg_tree = CGenCfgData.deep_convert_list (self._cfg_tree) - - def generate_yml_file (self, in_file, out_file): - cfg_yaml = CFG_YAML() - text = cfg_yaml.expand_yaml (in_file) - yml_fd = open(out_file, "w") - yml_fd.write (text) - yml_fd.close () - return 0 - - - def write_cfg_header_file (self, hdr_file_name, tag_mode, tag_dict, struct_list): - lines = [] - lines.append ('\n\n') - tag_list = sorted(list(tag_dict.items()), key=lambda x: x[1]) - for tagname, tagval in tag_list: - if (tag_mode == 0 and tagval >= 0x100) or (tag_mode == 1 and tagval < 0x100): - continue - lines.append ('#define %-30s 0x%03X\n' % ('CDATA_%s_TAG' % tagname[:-9], tagval)) - lines.append ('\n\n') - - name_dict = {} - new_dict = {} - for each in struct_list: - if (tag_mode == 0 and each['tag'] >= 0x100) or (tag_mode == 1 and each['tag'] < 0x100): - continue - new_dict[each['name']] = (each['alias'], each['count']) - if each['alias'] not in name_dict: - name_dict[each['alias']] = 1 - lines.extend(self.create_struct (each['alias'], each['node'], new_dict)) - - - self.write_header_file (lines, hdr_file_name) - - - def findMaxMinver (self, tree): - - if type(tree) is not OrderedDict: - raise Exception ("Incorrect tree type %s!!!" % type(tree)) - - # In-order tree traversal to make sure all minor versions are non-descending - try: - ver = int(tree["minver"], 0) - except: - ver = 0 - - parent_minver = ver - - max_minver = parent_minver - for value in tree: - if type(tree[value]) is OrderedDict: - temp_ver = self.findMaxMinver (tree[value]) - if temp_ver >= max_minver: - max_minver = temp_ver - else: - raise Exception ("Higher minor version detected %d between older fields at %s. New minor version fields should only be appended!!!\ - Consider append new fields, or remove the minor version and bump major version" % (temp_ver, max_minver, value)) - - return max_minver - - - def write_policy_header_file (self, hdr_file_name, tag_mode, struct_list): - lines = [] - max_minver = self.findMaxMinver(self._cfg_tree) - category = '' - - # Step 1: Macro definitions - for struct in struct_list: - if struct["name"] == "PolicyHeader": - category = struct['node']['category'] - lines.append ('#define %-30s 0x%016X\n' % ('PDATA_%s_SIGNATURE' % (category), int.from_bytes(bytes(struct['node']['signature']["value"].strip("'"), 'utf-8'), 'little'))) - lines.append ('#define %-30s 0x%02X\n' % ('PDATA_%s_MAJOR_VER' % (category), int(struct['node']['majver']["value"], 0))) - lines.append ('#define %-30s 0x%02X\n' % ('PDATA_%s_MINOR_VER' % (category), max_minver)) - lines.append ('\n') - - if category == '': - raise Exception ("No category field set in the Policy header!!!") - - # Step 2: Structure definitions - name_dict = {} - new_dict = {} - for each in struct_list: - if each['name'] == "PolicyHeader": - continue - if (tag_mode == 0 and each['tag'] >= 0x100) or (tag_mode == 1 and each['tag'] < 0x100): - continue - new_dict[each['name']] = (each['alias'], each['count']) - if each['alias'] not in name_dict: - name_dict[each['alias']] = 1 - lines.extend(self.create_struct (each['alias'], each['node'], new_dict)) - - # Step 3: Template verified policy header - for struct in struct_list: - if struct["name"] == "PolicyHeader": - lines.append ('STATIC CONST VERIFIED_POLICY_HEADER POLICY_%s_DESC = {\n' % (category)) - lines.append (' .Signature = %s,\n' % ('PDATA_%s_SIGNATURE' % (category))) - lines.append (' .MajorVersion = %s,\n' % ('PDATA_%s_MAJOR_VER' % (category))) - lines.append (' .MinorVersion = %s,\n' % ('PDATA_%s_MINOR_VER' % (category))) - lines.append (' .Size = 0x%02X,\n' % (self._var_dict[struct["node"]["size"]["value"]])) - lines.append ('};\n') - lines.append ('\n') - - # Step 4: Get/set accessors for each field per minor version - setter_def_all = [] - getter_def_all = [] - for struct in struct_list: - if struct["name"] == "PolicyHeader": - continue - for minver in range (max_minver + 1): - lines.append ('/* Get accessors for MIN_VER %d */\n' % minver) - (getter, getter_def) = self.traverse_struct (struct['node'], new_dict, minver, category, False) - lines.extend(getter) - getter_def_all.append(getter_def) - - lines.append ('/* Set accessors for MIN_VER %d */\n' % minver) - (setter, setter_def) = self.traverse_struct (struct['node'], new_dict, minver, category, True) - lines.extend(setter) - setter_def_all.append(setter_def) - - lines.append ('/* Set accessors for all fields of this structure */\n') - ''' - STATIC - VOID - EFIAPI - SET_%s_default ( - IN EFI_HANDLE _handle, - IN EFI_GUID *Guid - ) { - if ((VERIFIED_POLICY_DESCRIPTOR*)_handle)->MinorVersion >= 0x%x) {" - SET_%s_default (); - } - } - ''' - lines.append("inline\n" ) - lines.append("STATIC\n" ) - lines.append("VOID\n" ) - lines.append("EFIAPI\n" ) - lines.append("SET_%s_default (\n" % struct['name']) - lines.append(" IN EFI_HANDLE _handle,\n" ) - lines.append(" IN EFI_GUID *Guid\n" ) - lines.append(" ) {\n" ) - for idx in range(len(setter_def_all)): - lines.append(" if (((VERIFIED_POLICY_DESCRIPTOR*)_handle)->MinorVersion >= 0x%x) {\n"% idx) - for each in setter_def_all[idx]: - lines.append(" %s (_handle, Guid);\n" % each) - lines.append(" }\n") - lines.append("}\n\n") - - self.write_header_file (lines, hdr_file_name) - - - def write_header_file (self, txt_body, file_name, type = 'h'): - file_name_def = os.path.basename(file_name).replace ('.', '_') - file_name_def = re.sub('(.)([A-Z][a-z]+)', r'\1_\2', file_name_def) - file_name_def = re.sub('([a-z0-9])([A-Z])', r'\1_\2', file_name_def).upper() - - lines = [] - lines.append ("%s\n" % get_copyright_header(type)) - lines.append ("#ifndef __%s__\n" % file_name_def) - lines.append ("#define __%s__\n\n" % file_name_def) - if type == 'h': - lines.append ("#include \n\n") - lines.append ("#pragma pack(1)\n\n") - lines.extend (txt_body) - if type == 'h': - lines.append ("#pragma pack()\n\n") - lines.append ("#endif\n") - - # Don't rewrite if the contents are the same - create = True - if os.path.exists(file_name): - hdr_file = open(file_name, "r") - org_txt = hdr_file.read() - hdr_file.close() - - new_txt = ''.join(lines) - if org_txt == new_txt: - create = False - - if create: - hdr_file = open(file_name, "w") - hdr_file.write (''.join(lines)) - hdr_file.close() - - - def generate_data_inc_file (self, dat_inc_file_name, bin_file = None): - # Put a prefix GUID before CFGDATA so that it can be located later on - prefix = b'\xa7\xbd\x7f\x73\x20\x1e\x46\xd6\xbe\x8f\x64\x12\x05\x8d\x0a\xa8' - if bin_file: - fin = open (bin_file, 'rb') - bin_dat = prefix + bytearray(fin.read()) - fin.close() - else: - bin_dat = prefix + self.generate_binary_array () - - file_name = os.path.basename(dat_inc_file_name).upper() - file_name = file_name.replace('.', '_') - - txt_lines = [] - - txt_lines.append ("UINT8 mConfigDataBlob[%d] = {\n" % len(bin_dat)) - count = 0 - line = [' '] - for each in bin_dat: - line.append('0x%02X, ' % each) - count = count + 1 - if (count & 0x0F) == 0: - line.append('\n') - txt_lines.append (''.join(line)) - line = [' '] - if len(line) > 1: - txt_lines.append (''.join(line) + '\n') - - txt_lines.append ("};\n\n") - - self.write_header_file (txt_lines, dat_inc_file_name, 'inc') - - return 0 - - - def get_struct_array_info (self, input): - parts = input.split(':') - if len(parts) > 1: - var = parts[1] - input = parts[0] - else: - var = '' - array_str = input.split('[') - name = array_str[0] - if len(array_str) > 1: - num_str = ''.join(c for c in array_str[-1] if c.isdigit()) - num_str = '1000' if len(num_str) == 0 else num_str - array_num = int(num_str) - else: - array_num = 0 - return name, array_num, var - - - def process_multilines (self, string, max_char_length): - multilines = '' - string_length = len(string) - current_string_start = 0 - string_offset = 0 - break_line_dict = [] - if len(string) <= max_char_length: - while (string_offset < string_length): - if string_offset >= 1: - if string[string_offset - 1] == '\\' and string[string_offset] == 'n': - break_line_dict.append (string_offset + 1) - string_offset += 1 - if break_line_dict != []: - for each in break_line_dict: - multilines += " %s\n" % string[current_string_start:each].lstrip() - current_string_start = each - if string_length - current_string_start > 0: - multilines += " %s\n" % string[current_string_start:].lstrip() - else: - multilines = " %s\n" % string - else: - new_line_start = 0 - new_line_count = 0 - found_space_char = False - while (string_offset < string_length): - if string_offset >= 1: - if new_line_count >= max_char_length - 1: - if string[string_offset] == ' ' and string_length - string_offset > 10: - break_line_dict.append (new_line_start + new_line_count) - new_line_start = new_line_start + new_line_count - new_line_count = 0 - found_space_char = True - elif string_offset == string_length - 1 and found_space_char == False: - break_line_dict.append (0) - if string[string_offset - 1] == '\\' and string[string_offset] == 'n': - break_line_dict.append (string_offset + 1) - new_line_start = string_offset + 1 - new_line_count = 0 - string_offset += 1 - new_line_count += 1 - if break_line_dict != []: - break_line_dict.sort () - for each in break_line_dict: - if each > 0: - multilines += " %s\n" % string[current_string_start:each].lstrip() - current_string_start = each - if string_length - current_string_start > 0: - multilines += " %s\n" % string[current_string_start:].lstrip() - return multilines - - - def create_field (self, item, name, length, offset, struct, bsf_name, help, option, bits_length = None): - pos_name = 28 - pos_comment = 30 - name_line='' - help_line='' - option_line='' - - if length == 0 and name == 'dummy': - return '\n' - - if bits_length == 0: - return '\n' - - is_array = False - if length in [1,2,4,8]: - type = "UINT%d" % (length * 8) - else: - is_array = True - type = "UINT8" - - if item and item['value'].startswith('{'): - type = "UINT8" - is_array = True - - if struct != '': - struct_base = struct.rstrip('*') - name = '*' * (len(struct) - len(struct_base)) + name - struct = struct_base - type = struct - if struct in ['UINT8','UINT16','UINT32','UINT64']: - is_array = True - unit = int(type[4:]) // 8 - length = length / unit - else: - is_array = False - - if is_array: - name = name + '[%d]' % length - - if len(type) < pos_name: - space1 = pos_name - len(type) - else: - space1 = 1 - - if bsf_name != '': - name_line=" %s\n" % bsf_name - else: - name_line="N/A\n" - - if help != '': - help_line = self.process_multilines (help, 80) - - if option != '': - option_line = self.process_multilines (option, 80) - - if offset is None: - offset_str = '????' - else: - offset_str = '0x%04X' % offset - - if bits_length is None: - bits_length = '' - else: - bits_length = ' : %d' % bits_length - - #return "\n/** %s%s%s**/\n %s%s%s%s;\n" % (name_line, help_line, option_line, type, ' ' * space1, name, bits_length) - return "\n /* %s */\n %s%s%s%s;\n" % (name_line.strip(), type, ' ' * space1, name, bits_length) - - - def create_accessor (self, item, category, name, length, offset, struct, bsf_name, help, option, is_set, bits_length = None): - - if length == 0 and name == 'dummy': - return '\n' - - if bits_length == 0: - return '\n' - - is_array = False - if length in [1,2,4,8]: - type = "UINT%d" % (length * 8) - else: - is_array = True - type = "UINT8" - - if item and item['value'].startswith('{'): - type = "UINT8" - is_array = True - - if struct != '': - struct_base = struct.rstrip('*') - name = '*' * (len(struct) - len(struct_base)) + name - struct = struct_base - type = struct - if struct in ['UINT8','UINT16','UINT32','UINT64']: - is_array = True - unit = int(type[4:]) // 8 - length = length / unit - else: - is_array = False - - if is_array: - name = name + '[%d]' % length - - if bits_length is None: - bits_length = '' - else: - bits_length = ' : %d' % bits_length - - path = item['path'].split(".") - final_acs_list = [] - if is_set: - ''' - STATIC - VOID - EFIAPI - SET_%s ( - IN EFI_HANDLE _handle, - IN EFI_GUID *Guid, - IN %s val, - ) { - ((%s*)((UINTN)_handle + sizeof (VERIFIED_POLICY_DESCRIPTOR)))->%s = val; - ReportVerifiedPolicyAccess (_handle, Guid, offset, size, FALSE); - } - ''' - final_acs_list.append("inline" ) - final_acs_list.append("STATIC" ) - final_acs_list.append("VOID" ) - final_acs_list.append("EFIAPI" ) - final_acs_list.append("SET_%s (" % "_".join(path)) - final_acs_list.append(" IN EFI_HANDLE _handle," ) - final_acs_list.append(" IN EFI_GUID *Guid," ) - final_acs_list.append(" IN %s val" % type) - final_acs_list.append(" ) {" ) - final_acs_list.append(" ((%s*)((UINTN)_handle + sizeof (VERIFIED_POLICY_DESCRIPTOR)))->%s = val;" % (path[0], path[1])) - final_acs_list.append(" ReportVerifiedPolicyAccess (_handle, Guid, 0x%x, 0x%x, TRUE);" % (length, offset)) - final_acs_list.append("}\n\n") - - # Set default value - ''' - STATIC - VOID - EFIAPI - SET_%s_default ( - IN EFI_HANDLE _handle, - IN EFI_GUID *Guid - ) { - ((%s*)((UINTN)_handle + sizeof (VERIFIED_POLICY_DESCRIPTOR)))->%s = 0x%x; - ReportVerifiedPolicyAccess (_handle, Guid, offset, size, FALSE); - } - ''' - final_acs_list.append("inline" ) - final_acs_list.append("STATIC" ) - final_acs_list.append("VOID" ) - final_acs_list.append("EFIAPI" ) - acs_default = "SET_%s_default (" % "_".join(path) - final_acs_list.append(acs_default) - final_acs_list.append(" IN EFI_HANDLE _handle," ) - final_acs_list.append(" IN EFI_GUID *Guid" ) - final_acs_list.append(" ) {" ) - final_acs_list.append(" ((%s*)((UINTN)_handle + sizeof (VERIFIED_POLICY_DESCRIPTOR)))->%s = 0x%x;" % (path[0], path[1], int(item['value'], 0))) - final_acs_list.append(" ReportVerifiedPolicyAccess (_handle, Guid, 0x%x, 0x%x, TRUE);" % (length, offset)) - final_acs_list.append("}\n\n") - else: - ''' - STATIC - %s - EFIAPI - GET_%s ( - IN EFI_HANDLE _handle, - IN EFI_GUID *Guid - ) { - %s Temp; - if (((VERIFIED_POLICY_DESCRIPTOR*)_handle)->Size >= (OFFSET_OF(%s, %s) + (sizeof (((%s *)0)->%s)) { - Temp = ((%s*)((UINTN)_handle + sizeof (VERIFIED_POLICY_DESCRIPTOR)))->%s; - } else { - Temp = 0x%x; - } - ReportVerifiedPolicyAccess (_handle, Guid, offset, size, FALSE); - return Temp; - } - ''' - final_acs_list.append("inline" ) - final_acs_list.append("STATIC" ) - final_acs_list.append("%s" % type) - final_acs_list.append("EFIAPI" ) - final_acs_list.append("GET_%s (" % "_".join(path)) - final_acs_list.append(" IN EFI_HANDLE _handle," ) - final_acs_list.append(" IN EFI_GUID *Guid" ) - final_acs_list.append(" ) {" ) - final_acs_list.append(" %s Temp;" % type) - final_acs_list.append(" if (((VERIFIED_POLICY_DESCRIPTOR*)_handle)->Size >= (OFFSET_OF(%s, %s) + (sizeof (((%s*)0)->%s)))) {" % (path[0], path[1], path[0], path[1])) - final_acs_list.append(" Temp = ((%s*)((UINTN)_handle + sizeof (VERIFIED_POLICY_DESCRIPTOR)))->%s;" % (path[0], path[1])) - final_acs_list.append(" } else {" ) - final_acs_list.append(" Temp = 0x%x;" % int(item['value'], 0)) - final_acs_list.append(" }" ) - final_acs_list.append(" ReportVerifiedPolicyAccess (_handle, Guid, 0x%x, 0x%x, FALSE);" % (length, offset)) - final_acs_list.append(" return Temp;" ) - final_acs_list.append("}\n\n") - - # Get default value - ''' - STATIC - %s - EFIAPI - GET_%s_default ( - IN EFI_HANDLE _handle, - IN EFI_GUID *Guid - ) { - ReportVerifiedPolicyAccess (_handle, Guid, offset, size, FALSE); - return 0x%x; - } - ''' - final_acs_list.append("inline" ) - final_acs_list.append("STATIC" ) - final_acs_list.append("%s" % type) - final_acs_list.append("EFIAPI" ) - acs_default = "GET_%s_default (" % "_".join(path) - final_acs_list.append(acs_default) - final_acs_list.append(" IN EFI_HANDLE _handle," ) - final_acs_list.append(" IN EFI_GUID *Guid" ) - final_acs_list.append(" ) {" ) - final_acs_list.append(" ReportVerifiedPolicyAccess (_handle, Guid, 0x%x, 0x%x, FALSE);" % (length, offset)) - final_acs_list.append(" return 0x%x;" % int(item['value'], 0)) - final_acs_list.append("}\n\n") - - final_acs_str = "\n".join(final_acs_list) - return (final_acs_str, acs_default.rstrip (' (')) - - - def create_struct (self, cname, top, struct_dict): - index = 0 - last = '' - lines = [] - lines.append ('\ntypedef struct {\n') - for field in top: - if field[0] == '$': - continue - - index += 1 - - t_item = top[field] - if 'indx' not in t_item: - if CGenCfgData.STRUCT not in top[field]: - continue - - if struct_dict[field][1] == 0: - continue - - append = True - struct_info = top[field][CGenCfgData.STRUCT] - - if 'struct' in struct_info: - struct, array_num, var = self.get_struct_array_info (struct_info['struct']) - if array_num > 0: - if last == struct: - append = False - last = struct - if var == '': - var = field - - field = CGenCfgData.format_struct_field_name (var, struct_dict[field][1]) - else: - struct = struct_dict[field][0] - field = CGenCfgData.format_struct_field_name (field, struct_dict[field][1]) - - if append: - line = self.create_field (None, field, 0, 0, struct, '', '', '') - lines.append (' %s' % line) - last = struct - continue - - item = self.get_item_by_index (t_item['indx']) - if item['cname'] == 'CfgHeader' and index == 1 or (item['cname'] == 'CondValue' and index == 2): - continue - - bit_length = None - length = (item['length'] + 7) // 8 - match = re.match("^(\d+)([b|B|W|D|Q])([B|W|D|Q]?)", t_item['length']) - if match and match.group(2) == 'b': - bit_length = int(match.group(1)) - if match.group(3) != '': - length = CGenCfgData.bits_width[match.group(3)] // 8 - else: - length = 4 - offset = item['offset'] // 8 - struct = item.get('struct', '') - name = field - prompt = item['name'] - help = item['help'] - option = item['option'] - line = self.create_field (item, name, length, offset, struct, prompt, help, option, bit_length) - lines.append (' %s' % line) - last = struct - - lines.append ('\n} %s;\n\n' % cname) - - return lines - - - def traverse_struct (self, top, struct_dict, target_min_ver, category, is_set): - index = 0 - last = '' - lines = [] - defaults = [] - - for field in top: - if field[0] == '$': - continue - - index += 1 - - t_item = top[field] - - try: - minver = int(t_item['minver'], 0) - except: - minver = 0 - - if minver != target_min_ver: - continue - - if 'indx' not in t_item: - if CGenCfgData.STRUCT not in top[field]: - continue - - if struct_dict[field][1] == 0: - continue - - append = True - struct_info = top[field][CGenCfgData.STRUCT] - - if 'struct' in struct_info: - struct, array_num, var = self.get_struct_array_info (struct_info['struct']) - if array_num > 0: - if last == struct: - append = False - last = struct - if var == '': - var = field - - field = CGenCfgData.format_struct_field_name (var, struct_dict[field][1]) - else: - struct = struct_dict[field][0] - field = CGenCfgData.format_struct_field_name (field, struct_dict[field][1]) - - if append: - (line, default) = self.create_accessor (None, category, field, 0, 0, struct, '', '', '', is_set) - lines.append (' %s' % line) - defaults.append (default) - last = struct - continue - - item = self.get_item_by_index (t_item['indx']) - - bit_length = None - length = (item['length'] + 7) // 8 - match = re.match("^(\d+)([b|B|W|D|Q])([B|W|D|Q]?)", t_item['length']) - if match and match.group(2) == 'b': - bit_length = int(match.group(1)) - if match.group(3) != '': - length = CGenCfgData.bits_width[match.group(3)] // 8 - else: - length = 4 - offset = item['offset'] // 8 - struct = item.get('struct', '') - name = field - prompt = item['name'] - help = item['help'] - option = item['option'] - (line, default) = self.create_accessor (item, category, name, length, offset, struct, prompt, help, option, is_set, bit_length) - lines.append ('%s' % line) - defaults.append (default) - last = struct - - lines.append ('\n') - - return (lines, defaults) - - - def create_header_file (self, hdr_file_name, com_hdr_file_name = ''): - def _build_header_struct (name, cfgs, level): - if CGenCfgData.STRUCT in cfgs: - if 'CfgHeader' in cfgs: - # collect CFGDATA TAG IDs - cfghdr = self.get_item_by_index (cfgs['CfgHeader']['indx']) - tag_val = array_str_to_value(cfghdr['value']) >> 20 - tag_dict[name] = tag_val - if level == 1: - tag_curr[0] = tag_val - struct_dict[name] = (level, tag_curr[0], cfgs) - - tag_curr = [0] - tag_dict = {} - struct_dict = {} - self.traverse_cfg_tree (_build_header_struct) - - if tag_curr[0] == 0: - hdr_mode = 2 - else: - hdr_mode = 1 - - # filter out the items to be built for tags and structures - struct_list = [] - for each in struct_dict: - match = False - for check in CGenCfgData.exclude_struct: - if re.match (check, each): - match = True - if each in tag_dict: - if each not in CGenCfgData.include_tag: - del tag_dict[each] - break - if not match: - struct_list.append ({'name':each, 'alias':'', 'count' : 0, 'level':struct_dict[each][0], - 'tag':struct_dict[each][1], 'node':struct_dict[each][2]}) - - # sort by level so that the bottom level struct will be build first to satisfy dependencies - struct_list = sorted(struct_list, key=lambda x: x['level'], reverse=True) - - # Convert XXX_[0-9]+ to XXX as an array hint - for each in struct_list: - cfgs = each['node'] - if 'struct' in cfgs['$STRUCT']: - each['alias'], array_num, var = self.get_struct_array_info (cfgs['$STRUCT']['struct']) - else: - match = re.match('(\w+)(_\d+)', each['name']) - if match: - each['alias'] = match.group(1) - else: - each['alias'] = each['name'] - - # count items for array build - for idx, each in enumerate(struct_list): - if idx > 0: - last_struct = struct_list[idx-1]['node']['$STRUCT'] - curr_struct = each['node']['$STRUCT'] - if struct_list[idx-1]['alias'] == each['alias'] and \ - curr_struct['length'] == last_struct['length'] and \ - curr_struct['offset'] == last_struct['offset'] + last_struct['length']: - for idx2 in range (idx-1, -1, -1): - if struct_list[idx2]['count'] > 0: - struct_list[idx2]['count'] += 1 - break - continue - each['count'] = 1 - - # generate common header - if com_hdr_file_name: - self.write_cfg_header_file (com_hdr_file_name, 0, tag_dict, struct_list) - - # generate platform header - self.write_cfg_header_file (hdr_file_name, hdr_mode, tag_dict, struct_list) - - return 0 - - - def create_policy_header_file (self, hdr_file_name, com_hdr_file_name = ''): - def _build_header_struct (name, cfgs, level): - if CGenCfgData.STRUCT in cfgs: - if 'PolicyHeader' in cfgs: - # collect macro definitions - cfghdr = self.get_item_by_index (cfgs['PolicyHeader']['indx']) - tag_val = array_str_to_value(cfghdr['value']) >> 20 - tag_dict[name] = tag_val - if level == 1: - tag_curr[0] = tag_val - struct_dict[name] = (level, tag_curr[0], cfgs) - - tag_curr = [0] - tag_dict = {} - struct_dict = {} - self.traverse_cfg_tree (_build_header_struct) - - if tag_curr[0] == 0: - hdr_mode = 2 - else: - hdr_mode = 1 - - # filter out the items to be built for tags and structures - struct_list = [] - for each in struct_dict: - match = False - for check in CGenCfgData.exclude_struct: - if re.match (check, each): - match = True - if each in tag_dict: - if each not in CGenCfgData.include_tag: - del tag_dict[each] - break - if not match: - struct_list.append ({'name':each, 'alias':'', 'count' : 0, 'level':struct_dict[each][0], - 'tag':struct_dict[each][1], 'node':struct_dict[each][2]}) - - # sort by level so that the bottom level struct will be build first to satisfy dependencies - struct_list = sorted(struct_list, key=lambda x: x['level'], reverse=True) - - # Convert XXX_[0-9]+ to XXX as an array hint - for each in struct_list: - cfgs = each['node'] - if 'struct' in cfgs['$STRUCT']: - each['alias'], array_num, var = self.get_struct_array_info (cfgs['$STRUCT']['struct']) - else: - match = re.match('(\w+)(_\d+)', each['name']) - if match: - each['alias'] = match.group(1) - else: - each['alias'] = each['name'] - - # count items for array build - for idx, each in enumerate(struct_list): - if idx > 0: - last_struct = struct_list[idx-1]['node']['$STRUCT'] - curr_struct = each['node']['$STRUCT'] - if struct_list[idx-1]['alias'] == each['alias'] and \ - curr_struct['length'] == last_struct['length'] and \ - curr_struct['offset'] == last_struct['offset'] + last_struct['length']: - for idx2 in range (idx-1, -1, -1): - if struct_list[idx2]['count'] > 0: - struct_list[idx2]['count'] += 1 - break - continue - each['count'] = 1 - - # generate platform header - self.write_policy_header_file (hdr_file_name, hdr_mode, struct_list) - - return 0 - - - def load_yaml (self, cfg_file, shallow_load=False, is_policy=False): - cfg_yaml = CFG_YAML() - self.initialize () - self.is_policy = is_policy - self._cfg_tree = cfg_yaml.load_yaml (cfg_file) - self._def_dict = cfg_yaml.def_dict - self._yaml_path = os.path.dirname(cfg_file) - if not shallow_load: - self.build_cfg_list() - self.build_var_dict() - self.update_def_value() - return 0 - - -def usage(): - print ('\n'.join([ - "GenCfgData Version 0.50", - "Usage:", - " GenCfgData GENINC BinFile IncOutFile", - " GenCfgData GENPKL YamlFile PklOutFile", - " GenCfgData GENBIN YamlFile[;DltFile] BinOutFile", - " GenCfgData GENDLT YamlFile[;BinFile] DltOutFile", - " GenCfgData GENHDR YamlFile HdrOutFile" - ])) - - -def main(): - # Parse the options and args - argc = len(sys.argv) - if argc < 4 or argc > 5: - usage() - return 1 - - gen_cfg_data = CGenCfgData() - command = sys.argv[1].upper() - out_file = sys.argv[3] - - file_list = sys.argv[2].split(';') - if len(file_list) >= 2: - yml_file = file_list[0] - dlt_file = file_list[1] - elif len(file_list) == 1: - yml_file = file_list[0] - dlt_file = '' - else: - raise Exception ("ERROR: Invalid parameter '%s' !" % sys.argv[2]) - - if command == "GENDLT" and yml_file.endswith('.dlt'): - # It needs to expand an existing DLT file - dlt_file = yml_file - lines = gen_cfg_data.expand_include_files (dlt_file) - write_lines (lines, out_file) - return 0 - - bin_file = '' - if (yml_file.lower().endswith('.bin')) and (command == "GENINC"): - # It is binary file - bin_file = yml_file - yml_file = '' - - if bin_file: - gen_cfg_data.generate_data_inc_file(out_file, bin_file) - return 0 - - cfg_bin_file = '' - cfg_bin_file2 = '' - if dlt_file: - if command == "GENDLT": - cfg_bin_file = dlt_file - dlt_file = '' - if len(file_list) >= 3: - cfg_bin_file2 = file_list[2] - - if yml_file.lower().endswith('.pkl'): - with open(yml_file, "rb") as pkl_file: - gen_cfg_data.__dict__ = marshal.load(pkl_file) - gen_cfg_data.prepare_marshal (False) - else: - if command == 'GENHDR': - gen_cfg_data.load_yaml (yml_file, is_policy=True) - - if command == 'GENPKL': - gen_cfg_data.prepare_marshal (True) - with open(out_file, "wb") as pkl_file: - marshal.dump(gen_cfg_data.__dict__, pkl_file) - json_file = os.path.splitext(out_file)[0] + '.json' - fo = open (json_file, 'w') - path_list = [] - cfgs = {'_cfg_page' : gen_cfg_data._cfg_page, '_cfg_list':gen_cfg_data._cfg_list, '_path_list' : path_list} - # optimize to reduce size - path = None - for each in cfgs['_cfg_list']: - new_path = each['path'][:-len(each['cname'])-1] - if path != new_path: - path = new_path - each['path'] = path - path_list.append(path) - else: - del each['path'] - if each['order'] == each['offset']: - del each['order'] - del each['offset'] - - # value is just used to indicate display type - value = each['value'] - if value.startswith ('0x'): - hex_len = ((each['length'] + 7) // 8) * 2 - if len(value) == hex_len: - value = 'x%d' % hex_len - else: - value = 'x' - each['value'] = value - elif value and value[0] in ['"', "'", '{']: - each['value'] = value[0] - else: - del each['value'] - - fo.write(repr(cfgs)) - fo.close () - return 0 - - if dlt_file: - gen_cfg_data.override_default_value(dlt_file) - - if command == "GENBIN": - if len(file_list) == 3: - old_data = gen_cfg_data.generate_binary_array() - fi = open (file_list[2], 'rb') - new_data = bytearray (fi.read ()) - fi.close () - if len(new_data) != len(old_data): - raise Exception ("Binary file '%s' length does not match, ignored !" % file_list[2]) - else: - gen_cfg_data.load_default_from_bin (new_data) - gen_cfg_data.override_default_value(dlt_file) - - gen_cfg_data.generate_binary(out_file) - - elif command == "GENDLT": - gen_cfg_data.generate_delta_file (out_file, cfg_bin_file, cfg_bin_file2) - - elif command == "GENHDR": - out_files = out_file.strip("'").split(';') - brd_out_file = out_files[0].strip() - if len(out_files) > 1: - com_out_file = out_files[1].strip() - else: - com_out_file = '' - gen_cfg_data.create_policy_header_file(brd_out_file, com_out_file) - - elif command == "GENINC": - gen_cfg_data.generate_data_inc_file(out_file) - - elif command == "DEBUG": - gen_cfg_data.print_cfgs() - - else: - raise Exception ("Unsuported command '%s' !" % command) - - return 0 - - -if __name__ == '__main__': - sys.exit(main()) - +## @ GenCfgData.py +# +# Copyright (c) 2020, Intel Corporation. All rights reserved.
+# Copyright (c) Microsoft Corporation. +# SPDX-License-Identifier: BSD-2-Clause-Patent +# +## + +import os +import sys +import re +import struct +import marshal +import pprint +import string +import operator as op +import ast +import binascii +from typing import Type, final +from unicodedata import category +import uuid +from datetime import date +from collections import OrderedDict + +from CommonUtility import * + +# Generated file copyright header +__copyright_tmp__ = """/** @file + + Platform Configuration %s File. + + Copyright (c) %4d, Intel Corporation. All rights reserved.
+ Copyright (c) Microsoft Corporation. + SPDX-License-Identifier: BSD-2-Clause-Patent + + This file is automatically generated. Please do NOT modify !!! + +**/ +""" + +def get_copyright_header (file_type, allow_modify = False): + file_description = { + 'yaml': 'Boot Setting', + 'dlt' : 'Delta', + 'inc' : 'C Binary Blob', + 'h' : 'C Struct Header' + } + if file_type in ['yaml', 'dlt']: + comment_char = '#' + else: + comment_char = '' + lines = __copyright_tmp__.split('\n') + if allow_modify: + lines = [line for line in lines if 'Please do NOT modify' not in line] + copyright_hdr = '\n'.join('%s%s' % (comment_char, line) for line in lines)[:-1] + '\n' + return copyright_hdr % (file_description[file_type], date.today().year) + +def check_quote (text): + if (text[0] == "'" and text[-1] == "'") or (text[0] == '"' and text[-1] == '"'): + return True + return False + +def strip_quote (text): + new_text = text.strip() + if check_quote (new_text): + return new_text[1:-1] + return text + +def strip_delimiter (text, delim): + new_text = text.strip() + if new_text: + if new_text[0] == delim[0] and new_text[-1] == delim[-1]: + return new_text[1:-1] + return text + +def bytes_to_bracket_str (bytes): + return '{ %s }' % (', '.join('0x%02x' % i for i in bytes)) + +def array_str_to_value (val_str): + val_str = val_str.strip() + val_str = strip_delimiter (val_str, '{}') + val_str = strip_quote (val_str) + value = 0 + for each in val_str.split(',')[::-1]: + each = each.strip() + value = (value << 8) | int(each, 0) + return value + +def write_lines (lines, file): + fo = open(file, "w") + fo.write (''.join ([x[0] for x in lines])) + fo.close () + +def read_lines (file): + if not os.path.exists(file): + test_file = os.path.basename(file) + if os.path.exists(test_file): + file = test_file + fi = open (file, 'r') + lines = fi.readlines () + fi.close () + return lines + +def expand_file_value (path, value_str): + result = bytearray() + match = re.match("\{\s*FILE:(.+)\}", value_str) + if match: + file_list = match.group(1).split(',') + for file in file_list: + file = file.strip() + bin_path = os.path.join(path, file) + result.extend(bytearray(open(bin_path, 'rb').read())) + return result + +class ExpressionEval(ast.NodeVisitor): + operators = { + ast.Add: op.add, + ast.Sub: op.sub, + ast.Mult: op.mul, + ast.Div: op.floordiv, + ast.Mod: op.mod, + ast.Eq: op.eq, + ast.NotEq: op.ne, + ast.Gt: op.gt, + ast.Lt: op.lt, + ast.GtE: op.ge, + ast.LtE: op.le, + ast.BitXor: op.xor, + ast.BitAnd: op.and_, + ast.BitOr: op.or_, + ast.Invert: op.invert, + ast.USub: op.neg + } + + + def __init__(self): + self._debug = False + self._expression = '' + self._namespace = {} + self._get_variable = None + + def eval(self, expr, vars={}): + self._expression = expr + if type(vars) is dict: + self._namespace = vars + self._get_variable = None + else: + self._namespace = {} + self._get_variable = vars + node = ast.parse(self._expression, mode='eval') + result = self.visit(node.body) + if self._debug: + print ('EVAL [ %s ] = %s' % (expr, str(result))) + return result + + def visit_Name(self, node): + if self._get_variable is not None: + return self._get_variable(node.id) + else: + return self._namespace[node.id] + + def visit_Num(self, node): + return node.n + + def visit_NameConstant(self, node): + return node.value + + def visit_BoolOp(self, node): + result = False + if isinstance(node.op, ast.And): + for value in node.values: + result = self.visit(value) + if not result: + break + elif isinstance(node.op, ast.Or): + for value in node.values: + result = self.visit(value) + if result: + break + return True if result else False + + def visit_UnaryOp(self, node): + val = self.visit(node.operand) + return operators[type(node.op)](val) + + def visit_BinOp(self, node): + lhs = self.visit(node.left) + rhs = self.visit(node.right) + return ExpressionEval.operators[type(node.op)](lhs, rhs) + + def visit_Compare(self, node): + right = self.visit(node.left) + result = True + for operation, comp in zip(node.ops, node.comparators): + if not result: + break + left = right + right = self.visit(comp) + result = ExpressionEval.operators[type(operation)](left, right) + return result + + def visit_Call(self, node): + if node.func.id in ['ternary']: + condition = self.visit (node.args[0]) + val_true = self.visit (node.args[1]) + val_false = self.visit (node.args[2]) + return val_true if condition else val_false + elif node.func.id in ['offset', 'length']: + if self._get_variable is not None: + return self._get_variable(node.args[0].s, node.func.id) + else: + raise ValueError("Unsupported function: " + repr(node)) + + def generic_visit(self, node): + raise ValueError("malformed node or string: " + repr(node)) + + +class CFG_YAML(): + TEMPLATE = 'template' + CONFIGS = 'configs' + VARIABLE = 'variable' + + def __init__ (self, is_policy=False): + self.log_line = False + self.allow_template = False + self.cfg_tree = None + self.tmp_tree = None + self.var_dict = None + self.def_dict = {} + self.yaml_path = '' + self.lines = [] + self.full_lines = [] + self.index = 0 + self.is_policy = is_policy + self.re_expand = re.compile (r'(.+:\s+|\s*\-\s*)!expand\s+\{\s*(\w+_TMPL)\s*:\s*\[(.+)]\s*\}') + self.re_include = re.compile (r'(.+:\s+|\s*\-\s*)!include\s+(.+)') + + @staticmethod + def count_indent (line): + return next((i for i, c in enumerate(line) if not c.isspace()), len(line)) + + @staticmethod + def substitue_args (text, arg_dict): + for arg in arg_dict: + text = text.replace ('$' + arg, arg_dict[arg]) + return text + + @staticmethod + def dprint (*args): + pass + + def process_include (self, line, insert = True): + match = self.re_include.match (line) + if not match: + raise Exception ("Invalid !include format '%s' !" % line.strip()) + + prefix = match.group(1) + include = match.group(2) + if prefix.strip() == '-': + prefix = '' + adjust = 0 + else: + adjust = 2 + + include = strip_quote (include) + request = CFG_YAML.count_indent (line) + adjust + + if self.log_line: + # remove the include line itself + del self.full_lines[-1] + + inc_path = os.path.join (self.yaml_path, include) + if not os.path.exists(inc_path): + # try relative path to project root + try_path = os.path.join(os.path.dirname (os.path.realpath(__file__)), "../..", include) + if os.path.exists(try_path): + inc_path = try_path + else: + raise Exception ("ERROR: Cannot open file '%s'." % inc_path) + + lines = read_lines (inc_path) + + current = 0 + same_line = False + for idx, each in enumerate (lines): + start = each.lstrip() + if start == '' or start[0] == '#': + continue + + if start[0] == '>': + # append the content directly at the same line + same_line = True + + start = idx + current = CFG_YAML.count_indent (each) + break + + lines = lines[start+1:] if same_line else lines[start:] + leading = '' + if same_line: + request = len(prefix) + leading = '>' + + lines = [prefix + '%s\n' % leading] + [' ' * request + i[current:] for i in lines] + if insert: + self.lines = lines + self.lines + + return lines + + def process_expand (self, line): + match = self.re_expand.match(line) + if not match: + raise Exception ("Invalid !expand format '%s' !" % line.strip()) + lines = [] + prefix = match.group(1) + temp_name = match.group(2) + args = match.group(3) + + if prefix.strip() == '-': + indent = 0 + else: + indent = 2 + lines = self.process_expand_template (temp_name, prefix, args, indent) + self.lines = lines + self.lines + + + def process_expand_template (self, temp_name, prefix, args, indent = 2): + # expand text with arg substitution + if temp_name not in self.tmp_tree: + raise Exception ("Could not find template '%s' !" % temp_name) + parts = args.split(',') + parts = [i.strip() for i in parts] + num = len(parts) + arg_dict = dict(zip( ['(%d)' % (i + 1) for i in range(num)], parts)) + str_data = self.tmp_tree[temp_name] + text = DefTemplate(str_data).safe_substitute(self.def_dict) + text = CFG_YAML.substitue_args (text, arg_dict) + target = CFG_YAML.count_indent (prefix) + indent + current = CFG_YAML.count_indent (text) + padding = target * ' ' + if indent == 0: + leading = [] + else: + leading = [prefix + '\n'] + text = leading + [(padding + i + '\n')[current:] for i in text.splitlines()] + return text + + + def load_file (self, yaml_file): + self.index = 0 + self.lines = read_lines (yaml_file) + + + def peek_line (self): + if len(self.lines) == 0: + return None + else: + return self.lines[0] + + + def put_line (self, line): + self.lines.insert (0, line) + if self.log_line: + del self.full_lines[-1] + + + def get_line (self): + if len(self.lines) == 0: + return None + else: + line = self.lines.pop(0) + if self.log_line: + self.full_lines.append (line.rstrip()) + return line + + + def get_multiple_line (self, indent): + text = '' + newind = indent + 1 + while True: + line = self.peek_line () + if line is None: + break + sline = line.strip() + if sline != '': + newind = CFG_YAML.count_indent(line) + if newind <= indent: + break + self.get_line () + if sline != '': + text = text + line + return text + + + def traverse_cfg_tree (self, handler): + def _traverse_cfg_tree (root, level = 0): + # config structure + for key in root: + if type(root[key]) is OrderedDict: + level += 1 + handler (key, root[key], level) + _traverse_cfg_tree (root[key], level) + level -= 1 + _traverse_cfg_tree (self.cfg_tree) + + + def count (self): + def _count (name, cfgs, level): + num[0] += 1 + num = [0] + self.traverse_cfg_tree (_count) + return num[0] + + + def parse (self, parent_name = '', curr = None, level = 0): + child = None + last_indent = None + temp_chk = {} + + while True: + line = self.get_line () + if line is None: + break + + curr_line = line.strip() + if curr_line == '' or curr_line[0] == '#': + continue + + indent = CFG_YAML.count_indent(line) + if last_indent is None: + last_indent = indent + + if indent != last_indent: + # outside of current block, put the line back to queue + self.put_line (' ' * indent + curr_line) + + if curr_line.endswith (': >'): + # multiline marker + old_count = len(self.full_lines) + line = self.get_multiple_line (indent) + if self.log_line and not self.allow_template and '!include ' in line: + # expand include in template + new_lines = [] + lines = line.splitlines() + for idx, each in enumerate(lines): + if '!include ' in each: + new_line = ''.join(self.process_include (each, False)) + new_lines.append(new_line) + else: + new_lines.append(each) + self.full_lines = self.full_lines[:old_count] + new_lines + curr_line = curr_line + line + + if indent > last_indent: + # child nodes + if child is None: + raise Exception ('Unexpected format at line: %s' % (curr_line)) + + level += 1 + self.parse (key, child, level) + level -= 1 + + line = self.peek_line () + if line is not None: + curr_line = line.strip() + indent = CFG_YAML.count_indent(line) + if indent >= last_indent: + # consume the line + self.get_line () + else: + # end of file + indent = -1 + + if curr is None: + curr = OrderedDict() + + if indent < last_indent: + return curr + + marker1 = curr_line[0] + marker2 = curr_line[-1] + start = 1 if marker1 == '-' else 0 + pos = curr_line.find(': ') + if pos > 0: + child = None + key = curr_line[start:pos].strip() + if curr_line[pos + 2] == '>': + curr[key] = curr_line[pos + 3:] + else: + # XXXX: !include / !expand + if '!include ' in curr_line: + self.process_include (line) + elif '!expand ' in curr_line: + if self.allow_template and not self.log_line: + self.process_expand (line) + else: + value_str = curr_line[pos + 2:].strip() + if key == "IdTag" or key == "ArrayIdTag": + # Insert the headers corresponds to this ID tag from here, most contents are hardcoded for now + cfg_hdr = OrderedDict() + cfg_hdr['length'] = '0x04' + cfg_hdr['value'] = '{0x01:2b, (_LENGTH_%s_/4):10b, %d:4b, 0:4b, %s:12b}' % (parent_name, 0 if key == "IdTag" else 1, value_str) + curr['CfgHeader'] = cfg_hdr + + cnd_val = OrderedDict() + cnd_val['length'] = '0x04' + cnd_val['value'] = '0x00000000' + curr['CondValue'] = cnd_val + else: + curr[key] = value_str + if self.log_line and value_str[0] == '{': + # expand {FILE: xxxx} format in the log line + if value_str[1:].rstrip().startswith('FILE:'): + value_bytes = expand_file_value (self.yaml_path, value_str) + value_str = bytes_to_bracket_str (value_bytes) + self.full_lines[-1] = line[:indent] + curr_line[:pos + 2] + value_str + + elif marker2 == ':': + child = OrderedDict() + key = curr_line[start:-1].strip() + if key == '$ACTION': + # special virtual nodes, rename to ensure unique key + key = '$ACTION_%04X' % self.index + self.index += 1 + if key in curr: + if key not in temp_chk: + # check for duplicated keys at same level + temp_chk[key] = 1 + else: + raise Exception ("Duplicated item '%s:%s' found !" % (parent_name, key)) + + curr[key] = child + if self.var_dict is None and key == CFG_YAML.VARIABLE: + self.var_dict = child + if self.tmp_tree is None and key == CFG_YAML.TEMPLATE: + self.tmp_tree = child + if self.var_dict: + for each in self.var_dict: + txt = self.var_dict[each] + if type(txt) is str: + self.def_dict['(%s)' % each] = txt + if self.tmp_tree and key == CFG_YAML.CONFIGS: + if not self.is_policy: + # apply template for the main configs + self.allow_template = True + child['Signature'] = OrderedDict() + child['Signature']['length'] = '0x04' + child['Signature']['value'] = "{'CFGD'}" + + child['HeaderLength'] = OrderedDict() + child['HeaderLength']['length'] = '0x01' + child['HeaderLength']['value'] = '0x10' + + child['Reserved'] = OrderedDict() + child['Reserved']['length'] = '0x03' + child['Reserved']['value'] = '{0,0,0}' + + child['UsedLength'] = OrderedDict() + child['UsedLength']['length'] = '0x04' + child['UsedLength']['value'] = '_LENGTH_' + + # This will be rounded up to 4KB aligned + child['TotalLength'] = OrderedDict() + child['TotalLength']['length'] = '0x04' + child['TotalLength']['value'] = '(_LENGTH_/0x1000 + 1)*0x1000' + else: + child = None + # - !include cfg_opt.yaml + if '!include ' in curr_line: + self.process_include (line) + + return curr + + + def load_yaml (self, opt_file): + self.var_dict = None + self.yaml_path = os.path.dirname (opt_file) + self.load_file (opt_file) + yaml_tree = self.parse () + self.tmp_tree = yaml_tree[CFG_YAML.TEMPLATE] + self.cfg_tree = yaml_tree[CFG_YAML.CONFIGS] + return self.cfg_tree + + + def expand_yaml (self, opt_file): + self.log_line = True + self.load_yaml (opt_file) + self.log_line = False + text = '\n'.join (self.full_lines) + self.full_lines = [] + return text + + +class DefTemplate(string.Template): + idpattern = '\([_A-Z][_A-Z0-9]*\)|[_A-Z][_A-Z0-9]*' + + +class CGenCfgData: + STRUCT = '$STRUCT' + bits_width = {'b':1, 'B':8, 'W':16, 'D':32, 'Q':64} + builtin_option = {'$EN_DIS' : [('0', 'Disable'), ('1', 'Enable')]} + exclude_struct = ['GPIO_GPP_*', 'GPIO_CFG_DATA', 'GpioConfPad*', 'GpioPinConfig', + 'BOOT_OPTION*', 'PLATFORMID_CFG_DATA', '\w+_Half[01]'] + include_tag = ['GPIO_CFG_DATA'] + keyword_set = set(['name', 'type', 'option', 'help', 'length', 'value', 'order', 'struct', 'condition', 'minver']) + + def __init__(self): + self.initialize () + + + def initialize (self): + self._cfg_tree = {} + self._tmp_tree = {} + self._cfg_list = [] + self._cfg_page = {'root': {'title': '', 'child': []}} + self._cur_page = '' + self._var_dict = {} + self._def_dict = {} + self._yaml_path = '' + + + @staticmethod + def deep_convert_dict (layer): + # convert OrderedDict to list + dict + new_list = layer + if isinstance(layer, OrderedDict): + new_list = list (layer.items()) + for idx, pair in enumerate (new_list): + new_node = CGenCfgData.deep_convert_dict (pair[1]) + new_list[idx] = dict({pair[0] : new_node}) + return new_list + + + @staticmethod + def deep_convert_list (layer): + if isinstance(layer, list): + od = OrderedDict({}) + for each in layer: + if isinstance(each, dict): + key = next(iter(each)) + od[key] = CGenCfgData.deep_convert_list(each[key]) + return od + else: + return layer + + + @staticmethod + def expand_include_files (file_path, cur_dir = ''): + if cur_dir == '': + cur_dir = os.path.dirname(file_path) + file_path = os.path.basename(file_path) + + input_file_path = os.path.join(cur_dir, file_path) + file = open(input_file_path, "r") + lines = file.readlines() + file.close() + + new_lines = [] + for line_num, line in enumerate(lines): + match = re.match("^!include\s*(.+)?$", line.strip()) + if match: + inc_path = match.group(1) + tmp_path = os.path.join(cur_dir, inc_path) + org_path = tmp_path + if not os.path.exists(tmp_path): + cur_dir = os.path.join(os.path.dirname (os.path.realpath(__file__)), "..", "..") + tmp_path = os.path.join(cur_dir, inc_path) + if not os.path.exists(tmp_path): + raise Exception ("ERROR: Cannot open include file '%s'." % org_path) + else: + new_lines.append (('# Included from file: %s\n' % inc_path, tmp_path, 0)) + new_lines.append (('# %s\n' % ('=' * 80), tmp_path, 0)) + new_lines.extend (CGenCfgData.expand_include_files (inc_path, cur_dir)) + else: + new_lines.append ((line, input_file_path, line_num)) + + return new_lines + + + @staticmethod + def format_struct_field_name (input, count = 0): + name = '' + cap = True + if '_' in input: + input = input.lower() + for each in input: + if each == '_': + cap = True + continue + elif cap: + each = each.upper() + cap = False + name = name + each + + if count > 1: + name = '%s[%d]' % (name, count) + + return name + + def get_last_error (self): + return '' + + + def get_variable (self, var, attr = 'value'): + if var in self._var_dict: + var = self._var_dict[var] + return var + + item = self.locate_cfg_item (var, False) + if item is None: + raise ValueError ("Cannot find variable '%s' !" % var) + + if item: + if 'indx' in item: + item = self.get_item_by_index (item['indx']) + if attr == 'offset': + var = item['offset'] + elif attr == 'length': + var = item['length'] + elif attr == 'value': + var = self.get_cfg_item_value (item) + else: + raise ValueError ("Unsupported variable attribute '%s' !" % attr) + return var + + + def eval (self, expr): + def _handler (pattern): + if pattern.group(1): + target = 1 + else: + target = 2 + result = self.get_variable(pattern.group(target)) + if result is None: + raise ValueError('Unknown variable $(%s) !' % pattern.group(target)) + return hex(result) + + expr_eval = ExpressionEval () + if '$' in expr: + # replace known variable first + expr = re.sub(r'\$\(([_a-zA-Z][\w\.]*)\)|\$([_a-zA-Z][\w\.]*)', _handler, expr) + return expr_eval.eval(expr, self.get_variable) + + + def get_cfg_list (self, page_id = None): + if page_id is None: + # return full list + return self._cfg_list + else: + # build a new list for items under a page ID + cfgs = [i for i in self._cfg_list if i['cname'] and (i['page'] == page_id)] + return cfgs + + + def get_cfg_page (self): + return self._cfg_page + + def get_cfg_item_length (self, item): + return item['length'] + + def get_cfg_item_value (self, item, array = False): + value_str = item['value'] + length = item['length'] + return self.get_value (value_str, length, array) + + + def format_value_to_str (self, value, bit_length, old_value = ''): + # value is always int + length = (bit_length + 7) // 8 + fmt = '' + if old_value.startswith ('0x'): + fmt = '0x' + elif old_value and (old_value[0] in ['"', "'", '{']): + fmt = old_value[0] + else: + fmt = '' + + bvalue = value_to_bytearray (value, length) + if fmt in ['"', "'"]: + svalue = bvalue.rstrip(b'\x00').decode() + value_str = fmt + svalue + fmt + elif fmt == "{": + value_str = '{ ' + ', '.join(['0x%02x' % i for i in bvalue]) + ' }' + elif fmt == '0x': + hex_len = length * 2 + if len(old_value) == hex_len + 2: + fstr = '0x%%0%dX' % hex_len + else: + fstr = '0x%X' + value_str = fstr % value + else: + if length <= 2: + value_str = '%d' % value + elif length <= 8: + value_str = '0x%x' % value + else: + value_str = '{ ' + ', '.join(['0x%02x' % i for i in bvalue]) + ' }' + return value_str + + + def reformat_value_str (self, value_str, bit_length, old_value = None): + value = self.parse_value (value_str, bit_length, False) + if old_value is None: + old_value = value_str + new_value = self.format_value_to_str (value, bit_length, old_value) + return new_value + + + def get_value (self, value_str, bit_length, array = True): + value_str = value_str.strip() + if len(value_str) == 0: + return 0 + if value_str[0] == "'" and value_str[-1] == "'" or \ + value_str[0] == '"' and value_str[-1] == '"': + value_str = value_str[1:-1] + bvalue = bytearray (value_str.encode()) + if len(bvalue) == 0: + bvalue = bytearray(b'\x00') + if array: + return bvalue + else: + return bytes_to_value (bvalue) + else: + if value_str[0] in '{' : + value_str = value_str[1:-1].strip() + value = 0 + for each in value_str.split(',')[::-1]: + each = each.strip() + value = (value << 8) | int(each, 0) + if array: + length = (bit_length + 7) // 8 + return value_to_bytearray (value, length) + else: + return value + + + def parse_value (self, value_str, bit_length, array = True): + length = (bit_length + 7) // 8 + if check_quote(value_str): + value_str = bytes_to_bracket_str(value_str[1:-1].encode()) + elif (',' in value_str) and (value_str[0] != '{'): + value_str = '{ %s }' % value_str + if value_str[0] == '{': + result = expand_file_value (self._yaml_path, value_str) + if len(result) == 0 : + bin_list = value_str[1:-1].split(',') + value = 0 + bit_len = 0 + unit_len = 1 + for idx, element in enumerate(bin_list): + each = element.strip() + if len(each) == 0: + continue + + in_bit_field = False + if each[0] in "'" + '"': + each_value = bytearray(each[1:-1], 'utf-8') + elif ':' in each: + match = re.match("^(.+):(\d+)([b|B|W|D|Q])$", each) + if match is None: + raise SystemExit("Exception: Invald value list format '%s' !" % each) + if match.group(1) == '0' and match.group(2) == '0': + unit_len = CGenCfgData.bits_width[match.group(3)] // 8 + cur_bit_len = int(match.group(2)) * CGenCfgData.bits_width[match.group(3)] + value += ((self.eval(match.group(1)) & (1< 0: + if bit_len % 8 != 0: + raise SystemExit("Exception: Invalid bit field alignment '%s' !" % value_str) + result.extend(value_to_bytes(value, bit_len // 8)) + value = 0 + bit_len = 0 + + result.extend(each_value) + + elif check_quote (value_str): + result = bytearray(value_str[1:-1], 'utf-8') # Excluding quotes + else: + result = value_to_bytearray (self.eval(value_str), length) + + if len(result) < length: + result.extend(b'\x00' * (length - len(result))) + elif len(result) > length: + raise SystemExit ("Exception: Value '%s' is too big to fit into %d bytes !" % (value_str, length)) + + if array: + return result + else: + return bytes_to_value(result) + + return result + + + def get_cfg_item_options (self, item): + tmp_list = [] + if item['type'] == "Combo": + if item['option'] in CGenCfgData.builtin_option: + for op_val, op_str in CGenCfgData.builtin_option[item['option']]: + tmp_list.append((op_val, op_str)) + else: + opt_list = item['option'].split(',') + for option in opt_list: + option = option.strip() + try: + (op_val, op_str) = option.split(':') + except: + raise SystemExit ("Exception: Invalid option format '%s' for item '%s' !" % (option, item['cname'])) + tmp_list.append((op_val, op_str)) + return tmp_list + + + def get_page_title(self, page_id, top = None): + if top is None: + top = self.get_cfg_page()['root'] + for node in top['child']: + page_key = next(iter(node)) + if page_id == page_key: + return node[page_key]['title'] + else: + result = self.get_page_title (page_id, node[page_key]) + if result is not None: + return result + return None + + + def print_pages(self, top=None, level=0): + if top is None: + top = self.get_cfg_page()['root'] + for node in top['child']: + page_id = next(iter(node)) + print('%s%s: %s' % (' ' * level, page_id, node[page_id]['title'])) + level += 1 + self.print_pages(node[page_id], level) + level -= 1 + + + def get_item_by_index (self, index): + return self._cfg_list[index] + + + def get_item_by_path (self, path): + node = self.locate_cfg_item (path) + if node: + return self.get_item_by_index (node['indx']) + else: + return None + + def locate_cfg_path (self, item): + def _locate_cfg_path (root, level = 0): + # config structure + if item is root: + return path + for key in root: + if type(root[key]) is OrderedDict: + level += 1 + path.append(key) + ret = _locate_cfg_path (root[key], level) + if ret: + return ret + path.pop() + return None + path = [] + return _locate_cfg_path (self._cfg_tree) + + + def locate_cfg_item (self, path, allow_exp = True): + def _locate_cfg_item (root, path, level = 0): + if len(path) == level: + return root + next_root = root.get(path[level], None) + if next_root is None: + if allow_exp: + raise Exception ('Not a valid CFG config option path: %s' % '.'.join(path[:level+1])) + else: + return None + return _locate_cfg_item (next_root, path, level + 1) + + path_nodes = path.split('.') + return _locate_cfg_item (self._cfg_tree, path_nodes) + + + def traverse_cfg_tree (self, handler, top = None): + def _traverse_cfg_tree (root, level = 0): + # config structure + for key in root: + if type(root[key]) is OrderedDict: + level += 1 + handler (key, root[key], level) + _traverse_cfg_tree (root[key], level) + level -= 1 + + if top is None: + top = self._cfg_tree + _traverse_cfg_tree (top) + + + def print_cfgs(self, root = None, short = True, print_level = 256): + def _print_cfgs (name, cfgs, level): + + if 'indx' in cfgs: + act_cfg = self.get_item_by_index (cfgs['indx']) + else: + offset = 0 + length = 0 + value = '' + path='' + if CGenCfgData.STRUCT in cfgs: + cfg = cfgs[CGenCfgData.STRUCT] + offset = int(cfg['offset']) + length = int(cfg['length']) + if 'value' in cfg: + value = cfg['value'] + if length == 0: + return + act_cfg = dict({'value' : value, 'offset' : offset, 'length' : length}) + value = act_cfg['value'] + bit_len = act_cfg['length'] + offset = (act_cfg['offset'] + 7) // 8 + if value != '': + try: + value = self.reformat_value_str (act_cfg['value'], act_cfg['length']) + except: + value = act_cfg['value'] + length = bit_len // 8 + bit_len = '(%db)' % bit_len if bit_len % 8 else '' * 4 + if level <= print_level: + if short and len(value) > 40: + value = '%s ... %s' % (value[:20] , value[-20:]) + print('%04X:%04X%-6s %s%s : %s' % (offset, length, bit_len, ' ' * level, name, value)) + + self.traverse_cfg_tree (_print_cfgs) + + + def get_cfg_tree(self): + return self._cfg_tree + + + def set_cfg_tree(self, cfg_tree): + self._cfg_tree = cfg_tree + + + def merge_cfg_tree(self, root, other_root): + ret = OrderedDict () + prev_key = None + for other_key in other_root: + if other_key not in root: + ret[other_key] = other_root[other_key] + else: + # this is a good time to check to see if we miss anything from previous root elements + found_last = False + for key in root: + if key == prev_key: + found_last = True + continue + if prev_key == None: + found_last = True + if found_last: + ret[key] = root[key] + if key == other_key: + prev_key = other_key + break + + if type(root[other_key]) is OrderedDict and type(other_root[other_key]) is OrderedDict: + # if they are both non-leaf, great, process recursively + ret[other_key] = self.merge_cfg_tree (root[other_key], other_root[other_key]) + elif type(root[other_key]) is OrderedDict or type(other_root[other_key]) is OrderedDict: + raise Exception ("Two yamls files have hierachy mismatch!!!") + else: + # this is duplicate value in from both roots, take original root as principal + ret[other_key] = root[other_key] + + # See if there is any leftovers + found_last = False + for key in root: + if key == prev_key: + found_last = True + continue + if prev_key == None: + found_last = True + if found_last: + ret[key] = root[key] + if key == other_key: + prev_key = other_key + break + return ret + + + def build_var_dict (self): + def _build_var_dict (name, cfgs, level): + if level <= 2: + if CGenCfgData.STRUCT in cfgs: + struct_info = cfgs[CGenCfgData.STRUCT] + self._var_dict['_LENGTH_%s_' % name] = struct_info['length'] // 8 + self._var_dict['_OFFSET_%s_' % name] = struct_info['offset'] // 8 + + self._var_dict = {} + self.traverse_cfg_tree (_build_var_dict) + self._var_dict['_LENGTH_'] = self._cfg_tree[CGenCfgData.STRUCT]['length'] // 8 + return 0 + + + def add_cfg_page(self, child, parent, title=''): + def _add_cfg_page(cfg_page, child, parent): + key = next(iter(cfg_page)) + if parent == key: + cfg_page[key]['child'].append({child: {'title': title, + 'child': []}}) + return True + else: + result = False + for each in cfg_page[key]['child']: + if _add_cfg_page(each, child, parent): + result = True + break + return result + + return _add_cfg_page(self._cfg_page, child, parent) + + + def set_cur_page(self, page_str): + if not page_str: + return + + if ',' in page_str: + page_list = page_str.split(',') + else: + page_list = [page_str] + for page_str in page_list: + parts = page_str.split(':') + if len(parts) in [1, 3]: + page = parts[0].strip() + if len(parts) == 3: + # it is a new page definition, add it into tree + parent = parts[1] if parts[1] else 'root' + parent = parent.strip() + if parts[2][0] == '"' and parts[2][-1] == '"': + parts[2] = parts[2][1:-1] + + if not self.add_cfg_page(page, parent, parts[2]): + raise SystemExit("Error: Cannot find parent page '%s'!" % parent) + else: + raise SystemExit("Error: Invalid page format '%s' !" % page_str) + self._cur_page = page + + + def extend_variable (self, line): + # replace all variables + if line == '': + return line + loop = 2 + while loop > 0: + line_after = DefTemplate(line).safe_substitute(self._def_dict) + if line == line_after: + break + loop -= 1 + line = line_after + return line_after + + def reformat_number_per_type (self, itype, value): + if check_quote(value) or value.startswith('{'): + return value + parts = itype.split(',') + if len(parts) > 3 and parts[0] == 'EditNum': + num_fmt = parts[1].strip() + else: + num_fmt = '' + if num_fmt == 'HEX' and not value.startswith('0x'): + value = '0x%X' % int(value, 10) + elif num_fmt == 'DEC' and value.startswith('0x'): + value = '%d' % int(value, 16) + return value + + def add_cfg_item(self, name, item, offset, path): + + self.set_cur_page (item.get('page', '')) + + if name[0] == '$': + # skip all virtual node + return 0 + + + if not set(item).issubset(CGenCfgData.keyword_set): + for each in list(item): + if each not in CGenCfgData.keyword_set: + raise Exception ("Invalid attribute '%s' for '%s'!" % (each, '.'.join(path))) + + length = item.get('length', 0) + if type(length) is str: + match = re.match("^(\d+)([b|B|W|D|Q])([B|W|D|Q]?)\s*$", length) + if match: + unit_len = CGenCfgData.bits_width[match.group(2)] + length = int(match.group(1), 10) * unit_len + else: + try: + length = int(length, 0) * 8 + except: + raise Exception ("Invalid length field '%s' for '%s' !" % (length, '.'.join(path))) + + if offset % 8 > 0: + raise Exception ("Invalid alignment for field '%s' for '%s' !" % (name, '.'.join(path))) + else: + # define is length in bytes + length = length * 8 + + if not name.isidentifier(): + raise Exception ("Invalid config name '%s' for '%s' !" % (name, '.'.join(path))) + + + itype = str(item.get('type', 'Reserved')) + value = str(item.get('value', '')) + if value: + if not (check_quote(value) or value.startswith('{')): + if ',' in value: + value = '{ %s }' % value + else: + value = self.reformat_number_per_type (itype, value) + + help = str(item.get('help', '')) + if '\n' in help: + help = ' '.join ([i.strip() for i in help.splitlines()]) + + option = str(item.get('option', '')) + if '\n' in option: + option = ' '.join ([i.strip() for i in option.splitlines()]) + + # extend variables for value and condition + condition = str(item.get('condition', '')) + if condition: + condition = self.extend_variable (condition) + value = self.extend_variable (value) + + order = str(item.get('order', '')) + if order: + if '.' in order: + (major, minor) = order.split('.') + order = int (major, 16) + else: + order = int (order, 16) + else: + order = offset + + cfg_item = dict() + cfg_item['length'] = length + cfg_item['offset'] = offset + cfg_item['value'] = value + cfg_item['type'] = itype + cfg_item['cname'] = str(name) + cfg_item['name'] = str(item.get('name', '')) + cfg_item['help'] = help + cfg_item['option'] = option + cfg_item['page'] = self._cur_page + cfg_item['order'] = order + cfg_item['path'] = '.'.join(path) + cfg_item['condition'] = condition + if 'struct' in item: + cfg_item['struct'] = item['struct'] + self._cfg_list.append(cfg_item) + + item['indx'] = len(self._cfg_list) - 1 + + # remove used info for reducing pkl size + item.pop('option', None) + item.pop('condition', None) + item.pop('help', None) + item.pop('name', None) + item.pop('page', None) + + return length + + + def build_cfg_list (self, cfg_name ='', top = None, path = [], info = {'offset': 0}): + if top is None: + top = self._cfg_tree + + start = info['offset'] + is_leaf = True + for key in top: + path.append(key) + if type(top[key]) is OrderedDict: + is_leaf = False + self.build_cfg_list(key, top[key], path, info) + path.pop() + + if is_leaf: + length = self.add_cfg_item(cfg_name, top, info['offset'], path) + info['offset'] += length + elif cfg_name == '' or (cfg_name and cfg_name[0] != '$'): + # check first element for struct + first = next(iter(top)) + struct_str = CGenCfgData.STRUCT + if first != struct_str: + struct_node = OrderedDict({}) + top[struct_str] = struct_node + top.move_to_end (struct_str, False) + else: + struct_node = top[struct_str] + struct_node['offset'] = start + if len(path) == 1: + # Round up first layer tree to be 4 Byte aligned + info['offset'] = (info['offset'] + 31) & (~31) + struct_node['length'] = (info['offset'] - start + 31) & (~31) + else: + struct_node['length'] = info['offset'] - start + if struct_node['length'] % 8 != 0: + raise SystemExit("Error: Bits length not aligned for %s !" % str(path)) + + + def get_field_value (self, top = None): + def _get_field_value (name, cfgs, level): + if 'indx' in cfgs: + act_cfg = self.get_item_by_index (cfgs['indx']) + if act_cfg['length'] == 0: + return + value = self.get_value (act_cfg['value'], act_cfg['length'], False) + set_bits_to_bytes (result, act_cfg['offset'] - struct_info['offset'], act_cfg['length'], value) + + if top is None: + top = self._cfg_tree + struct_info = top[CGenCfgData.STRUCT] + result = bytearray ((struct_info['length'] + 7) // 8) + self.traverse_cfg_tree (_get_field_value, top) + return result + + + def set_field_value (self, top, value_bytes, force = False): + def _set_field_value (name, cfgs, level): + if 'indx' not in cfgs: + return + act_cfg = self.get_item_by_index (cfgs['indx']) + if force or act_cfg['value'] == '': + value = get_bits_from_bytes (full_bytes, act_cfg['offset'] - struct_info['offset'], act_cfg['length']) + act_val = act_cfg['value'] + if act_val == '': + act_val = '%d' % value + act_val = self.reformat_number_per_type (act_cfg['type'], act_val) + act_cfg['value'] = self.format_value_to_str (value, act_cfg['length'], act_val) + + if 'indx' in top: + # it is config option + value = bytes_to_value (value_bytes) + act_cfg = self.get_item_by_index (top['indx']) + act_cfg['value'] = self.format_value_to_str (value, act_cfg['length'], act_cfg['value']) + else: + # it is structure + struct_info = top[CGenCfgData.STRUCT] + length = struct_info['length'] // 8 + full_bytes = bytearray(value_bytes[:length]) + if len(full_bytes) < length: + full_bytes.extend(bytearray(length - len(value_bytes))) + self.traverse_cfg_tree (_set_field_value, top) + + + def update_def_value (self): + def _update_def_value (name, cfgs, level): + if 'indx' in cfgs: + act_cfg = self.get_item_by_index (cfgs['indx']) + if act_cfg['value'] != '' and act_cfg['length'] > 0: + try: + act_cfg['value'] = self.reformat_value_str (act_cfg['value'], act_cfg['length']) + except: + raise Exception ("Invalid value expression '%s' for '%s' !" % (act_cfg['value'], act_cfg['path'])) + else: + if CGenCfgData.STRUCT in cfgs and 'value' in cfgs[CGenCfgData.STRUCT]: + curr = cfgs[CGenCfgData.STRUCT] + value_bytes = value_to_bytearray (self.eval(curr['value']), (curr['length'] + 7) // 8) + self.set_field_value (cfgs, value_bytes) + + self.traverse_cfg_tree (_update_def_value, self._cfg_tree) + + + def evaluate_condition (self, item): + expr = item['condition'] + result = self.parse_value (expr, 1, False) + return result + + + def load_default_from_bin (self, bin_data): + self.set_field_value(self._cfg_tree, bin_data, True) + + + def generate_binary_array (self): + return self.get_field_value() + + def generate_binary (self, bin_file_name): + bin_file = open(bin_file_name, "wb") + bin_file.write (self.generate_binary_array ()) + bin_file.close() + return 0 + + def write_delta_file (self, out_file, platform_id, out_lines): + dlt_fd = open (out_file, "w") + dlt_fd.write ("%s\n" % get_copyright_header('dlt', True)) + dlt_fd.write ('#\n') + dlt_fd.write ('# Delta configuration values for platform ID 0x%04X\n' % platform_id) + dlt_fd.write ('#\n\n') + for line in out_lines: + dlt_fd.write ('%s\n' % line) + dlt_fd.close() + + + def override_default_value(self, dlt_file): + error = 0 + dlt_lines = CGenCfgData.expand_include_files(dlt_file) + + platform_id = None + for line, file_path, line_num in dlt_lines: + line = line.strip() + if not line or line.startswith('#'): + continue + match = re.match("\s*([\w\.]+)\s*\|\s*(.+)", line) + if not match: + raise Exception("Unrecognized line '%s' (File:'%s' Line:%d) !" % + (line, file_path, line_num + 1)) + + path = match.group(1) + value_str = match.group(2) + top = self.locate_cfg_item (path) + if not top: + raise Exception( + "Invalid configuration '%s' (File:'%s' Line:%d) !" % + (path, file_path, line_num + 1)) + + if 'indx' in top: + act_cfg = self.get_item_by_index (top['indx']) + bit_len = act_cfg['length'] + else: + struct_info = top[CGenCfgData.STRUCT] + bit_len = struct_info['length'] + + value_bytes = self.parse_value (value_str, bit_len) + self.set_field_value (top, value_bytes, True) + + if path == 'PLATFORMID_CFG_DATA.PlatformId': + platform_id = value_str + + if platform_id is None: + platform_id = 0 + print("PLATFORMID_CFG_DATA.PlatformId is missing in file '%s' !" % (dlt_file)) + + return error + + + def generate_delta_file_from_bin (self, delta_file, old_data, new_data, full=False): + self.load_default_from_bin (new_data) + lines = [] + tag_name = '' + level = 0 + platform_id = None + def_platform_id = 0 + + for item in self._cfg_list: + old_val = get_bits_from_bytes (old_data, item['offset'], item['length']) + new_val = get_bits_from_bytes (new_data, item['offset'], item['length']) + + full_name = item['path'] + if 'PLATFORMID_CFG_DATA.PlatformId' == full_name: + def_platform_id = old_val + platform_id = new_val + elif item['type'] != 'Reserved' and ((new_val != old_val) or full): + val_str = self.reformat_value_str (item['value'], item['length']) + text = '%-40s | %s' % (full_name, val_str) + lines.append(text) + + if def_platform_id == platform_id: + platform_id = def_platform_id + + lines.insert(0, '%-40s | %s\n\n' % + ('PLATFORMID_CFG_DATA.PlatformId', '0x%04X' % platform_id)) + + if platform_id is None: + print ("Platform ID is not set and will be configured to 0") + platform_id = 0 + + self.write_delta_file (delta_file, platform_id, lines) + return 0 + + + def generate_delta_svd_from_bin (self, old_data, new_data): + self.load_default_from_bin (new_data) + lines = [] + tag_name = '' + level = 0 + platform_id = None + def_platform_id = 0 + items = [] + + for item in self._cfg_list: + old_val = get_bits_from_bytes (old_data, item['offset'], item['length']) + new_val = get_bits_from_bytes (new_data, item['offset'], item['length']) + + full_name = item['path'] + if 'PLATFORMID_CFG_DATA.PlatformId' == full_name: + def_platform_id = old_val + platform_id = new_val + elif item['type'] != 'Reserved' and (new_val != old_val): + val_str = self.reformat_value_str (item['value'], item['length']) + text = '%-40s | %s' % (full_name, val_str) + item = self.locate_cfg_item(item['path']) + if item is None: + raise Exception ("Failed to locate item from path: %s" % item['path']) + items.append(item) + + execs = [] + # The idea is that the 1st level tag content will be regenerated if changed + for item in items: + exec = self.locate_exec_from_item (item) + if exec == None: + raise Exception ("Failed to find the immediate executive tree for an item") + if exec not in execs: + execs.append (exec) + + bytes_array = [] + for exec in execs: + bytes = self.get_field_value (exec) + offset = 0 + offset += int(exec['CfgHeader']['length'], 0) + offset += int(exec['CondValue']['length'], 0) + bytes_array.append (bytes[offset:]) + + # self.write_delta_file (delta_file, platform_id, lines) + return (execs, bytes_array) + + def locate_exec_from_item (self, item): + + def _locate_exec_from_item (name, cfgs, level): + if level == 1: + exec[0] = cfgs + elif cfgs == item: + exec[1] = exec[0] + + exec = [None, None] + self.traverse_cfg_tree (_locate_exec_from_item, self._cfg_tree) + return exec[1] + + def locate_exec_from_tag (self, tag): + + def _locate_exec_from_tag (name, cfgs, level): + if level == 1: + exec[0] = cfgs + if CGenCfgData.STRUCT in cfgs: + cfghdr = self.get_item_by_index (cfgs['CfgHeader']['indx']) + tag_val = array_str_to_value(cfghdr['value']) >> 20 + if tag_val == tag: + exec[1] = exec[0] + + exec = [None, None] + self.traverse_cfg_tree (_locate_exec_from_tag, self._cfg_tree) + return exec[1] + + def generate_delta_file(self, delta_file, bin_file, bin_file2, full=False): + fd = open (bin_file, 'rb') + new_data = bytearray(fd.read()) + fd.close() + + if bin_file2 == '': + old_data = self.generate_binary_array() + else: + old_data = new_data + fd = open (bin_file2, 'rb') + new_data = bytearray(fd.read()) + fd.close() + + return self.generate_delta_file_from_bin (delta_file, old_data, new_data, full) + + + def prepare_marshal (self, is_save): + if is_save: + # Ordered dict is not marshallable, convert to list + self._cfg_tree = CGenCfgData.deep_convert_dict (self._cfg_tree) + else: + # Revert it back + self._cfg_tree = CGenCfgData.deep_convert_list (self._cfg_tree) + + def generate_yml_file (self, in_file, out_file): + cfg_yaml = CFG_YAML() + text = cfg_yaml.expand_yaml (in_file) + yml_fd = open(out_file, "w") + yml_fd.write (text) + yml_fd.close () + return 0 + + + def write_cfg_header_file (self, hdr_file_name, tag_mode, tag_dict, struct_list): + lines = [] + lines.append ('\n\n') + tag_list = sorted(list(tag_dict.items()), key=lambda x: x[1]) + for tagname, tagval in tag_list: + if (tag_mode == 0 and tagval >= 0x100) or (tag_mode == 1 and tagval < 0x100): + continue + lines.append ('#define %-30s 0x%03X\n' % ('CDATA_%s_TAG' % tagname[:-9], tagval)) + lines.append ('\n\n') + + name_dict = {} + new_dict = {} + for each in struct_list: + if (tag_mode == 0 and each['tag'] >= 0x100) or (tag_mode == 1 and each['tag'] < 0x100): + continue + new_dict[each['name']] = (each['alias'], each['count']) + if each['alias'] not in name_dict: + name_dict[each['alias']] = 1 + lines.extend(self.create_struct (each['alias'], each['node'], new_dict)) + + + self.write_header_file (lines, hdr_file_name) + + + def findMaxMinver (self, tree): + + if type(tree) is not OrderedDict: + raise Exception ("Incorrect tree type %s!!!" % type(tree)) + + # In-order tree traversal to make sure all minor versions are non-descending + try: + ver = int(tree["minver"], 0) + except: + ver = 0 + + parent_minver = ver + + max_minver = parent_minver + for value in tree: + if type(tree[value]) is OrderedDict: + temp_ver = self.findMaxMinver (tree[value]) + if temp_ver >= max_minver: + max_minver = temp_ver + else: + raise Exception ("Higher minor version detected %d between older fields at %s. New minor version fields should only be appended!!!\ + Consider append new fields, or remove the minor version and bump major version" % (temp_ver, max_minver, value)) + + return max_minver + + + def write_policy_header_file (self, hdr_file_name, tag_mode, struct_list): + lines = [] + max_minver = self.findMaxMinver(self._cfg_tree) + category = '' + + # Step 1: Macro definitions + for struct in struct_list: + if struct["name"] == "PolicyHeader": + category = struct['node']['category'] + lines.append ('#define %-30s 0x%016X\n' % ('PDATA_%s_SIGNATURE' % (category), int.from_bytes(bytes(struct['node']['signature']["value"].strip("'"), 'utf-8'), 'little'))) + lines.append ('#define %-30s 0x%02X\n' % ('PDATA_%s_MAJOR_VER' % (category), int(struct['node']['majver']["value"], 0))) + lines.append ('#define %-30s 0x%02X\n' % ('PDATA_%s_MINOR_VER' % (category), max_minver)) + lines.append ('\n') + + if category == '': + raise Exception ("No category field set in the Policy header!!!") + + # Step 2: Structure definitions + name_dict = {} + new_dict = {} + for each in struct_list: + if each['name'] == "PolicyHeader": + continue + if (tag_mode == 0 and each['tag'] >= 0x100) or (tag_mode == 1 and each['tag'] < 0x100): + continue + new_dict[each['name']] = (each['alias'], each['count']) + if each['alias'] not in name_dict: + name_dict[each['alias']] = 1 + lines.extend(self.create_struct (each['alias'], each['node'], new_dict)) + + # Step 3: Template verified policy header + for struct in struct_list: + if struct["name"] == "PolicyHeader": + lines.append ('STATIC CONST VERIFIED_POLICY_HEADER POLICY_%s_DESC = {\n' % (category)) + lines.append (' .Signature = %s,\n' % ('PDATA_%s_SIGNATURE' % (category))) + lines.append (' .MajorVersion = %s,\n' % ('PDATA_%s_MAJOR_VER' % (category))) + lines.append (' .MinorVersion = %s,\n' % ('PDATA_%s_MINOR_VER' % (category))) + lines.append (' .Size = 0x%02X,\n' % (self._var_dict[struct["node"]["size"]["value"]])) + lines.append ('};\n') + lines.append ('\n') + + # Step 4: Get/set accessors for each field per minor version + setter_def_all = [] + getter_def_all = [] + for struct in struct_list: + if struct["name"] == "PolicyHeader": + continue + for minver in range (max_minver + 1): + lines.append ('/* Get accessors for MIN_VER %d */\n' % minver) + (getter, getter_def) = self.traverse_struct (struct['node'], new_dict, minver, category, False) + lines.extend(getter) + getter_def_all.append(getter_def) + + lines.append ('/* Set accessors for MIN_VER %d */\n' % minver) + (setter, setter_def) = self.traverse_struct (struct['node'], new_dict, minver, category, True) + lines.extend(setter) + setter_def_all.append(setter_def) + + lines.append ('/* Set accessors for all fields of this structure */\n') + ''' + STATIC + VOID + EFIAPI + SET_%s_default ( + IN EFI_HANDLE _handle, + IN EFI_GUID *Guid + ) { + if ((VERIFIED_POLICY_DESCRIPTOR*)_handle)->MinorVersion >= 0x%x) {" + SET_%s_default (); + } + } + ''' + lines.append("inline\n" ) + lines.append("STATIC\n" ) + lines.append("VOID\n" ) + lines.append("EFIAPI\n" ) + lines.append("SET_%s_default (\n" % struct['name']) + lines.append(" IN EFI_HANDLE _handle,\n" ) + lines.append(" IN EFI_GUID *Guid\n" ) + lines.append(" ) {\n" ) + for idx in range(len(setter_def_all)): + lines.append(" if (((VERIFIED_POLICY_DESCRIPTOR*)_handle)->MinorVersion >= 0x%x) {\n"% idx) + for each in setter_def_all[idx]: + lines.append(" %s (_handle, Guid);\n" % each) + lines.append(" }\n") + lines.append("}\n\n") + + self.write_header_file (lines, hdr_file_name) + + + def write_header_file (self, txt_body, file_name, type = 'h'): + file_name_def = os.path.basename(file_name).replace ('.', '_') + file_name_def = re.sub('(.)([A-Z][a-z]+)', r'\1_\2', file_name_def) + file_name_def = re.sub('([a-z0-9])([A-Z])', r'\1_\2', file_name_def).upper() + + lines = [] + lines.append ("%s\n" % get_copyright_header(type)) + lines.append ("#ifndef __%s__\n" % file_name_def) + lines.append ("#define __%s__\n\n" % file_name_def) + if type == 'h': + lines.append ("#include \n\n") + lines.append ("#pragma pack(1)\n\n") + lines.extend (txt_body) + if type == 'h': + lines.append ("#pragma pack()\n\n") + lines.append ("#endif\n") + + # Don't rewrite if the contents are the same + create = True + if os.path.exists(file_name): + hdr_file = open(file_name, "r") + org_txt = hdr_file.read() + hdr_file.close() + + new_txt = ''.join(lines) + if org_txt == new_txt: + create = False + + if create: + hdr_file = open(file_name, "w") + hdr_file.write (''.join(lines)) + hdr_file.close() + + + def generate_data_inc_file (self, dat_inc_file_name, bin_file = None): + # Put a prefix GUID before CFGDATA so that it can be located later on + prefix = b'\xa7\xbd\x7f\x73\x20\x1e\x46\xd6\xbe\x8f\x64\x12\x05\x8d\x0a\xa8' + if bin_file: + fin = open (bin_file, 'rb') + bin_dat = prefix + bytearray(fin.read()) + fin.close() + else: + bin_dat = prefix + self.generate_binary_array () + + file_name = os.path.basename(dat_inc_file_name).upper() + file_name = file_name.replace('.', '_') + + txt_lines = [] + + txt_lines.append ("UINT8 mConfigDataBlob[%d] = {\n" % len(bin_dat)) + count = 0 + line = [' '] + for each in bin_dat: + line.append('0x%02X, ' % each) + count = count + 1 + if (count & 0x0F) == 0: + line.append('\n') + txt_lines.append (''.join(line)) + line = [' '] + if len(line) > 1: + txt_lines.append (''.join(line) + '\n') + + txt_lines.append ("};\n\n") + + self.write_header_file (txt_lines, dat_inc_file_name, 'inc') + + return 0 + + + def get_struct_array_info (self, input): + parts = input.split(':') + if len(parts) > 1: + var = parts[1] + input = parts[0] + else: + var = '' + array_str = input.split('[') + name = array_str[0] + if len(array_str) > 1: + num_str = ''.join(c for c in array_str[-1] if c.isdigit()) + num_str = '1000' if len(num_str) == 0 else num_str + array_num = int(num_str) + else: + array_num = 0 + return name, array_num, var + + + def process_multilines (self, string, max_char_length): + multilines = '' + string_length = len(string) + current_string_start = 0 + string_offset = 0 + break_line_dict = [] + if len(string) <= max_char_length: + while (string_offset < string_length): + if string_offset >= 1: + if string[string_offset - 1] == '\\' and string[string_offset] == 'n': + break_line_dict.append (string_offset + 1) + string_offset += 1 + if break_line_dict != []: + for each in break_line_dict: + multilines += " %s\n" % string[current_string_start:each].lstrip() + current_string_start = each + if string_length - current_string_start > 0: + multilines += " %s\n" % string[current_string_start:].lstrip() + else: + multilines = " %s\n" % string + else: + new_line_start = 0 + new_line_count = 0 + found_space_char = False + while (string_offset < string_length): + if string_offset >= 1: + if new_line_count >= max_char_length - 1: + if string[string_offset] == ' ' and string_length - string_offset > 10: + break_line_dict.append (new_line_start + new_line_count) + new_line_start = new_line_start + new_line_count + new_line_count = 0 + found_space_char = True + elif string_offset == string_length - 1 and found_space_char == False: + break_line_dict.append (0) + if string[string_offset - 1] == '\\' and string[string_offset] == 'n': + break_line_dict.append (string_offset + 1) + new_line_start = string_offset + 1 + new_line_count = 0 + string_offset += 1 + new_line_count += 1 + if break_line_dict != []: + break_line_dict.sort () + for each in break_line_dict: + if each > 0: + multilines += " %s\n" % string[current_string_start:each].lstrip() + current_string_start = each + if string_length - current_string_start > 0: + multilines += " %s\n" % string[current_string_start:].lstrip() + return multilines + + + def create_field (self, item, name, length, offset, struct, bsf_name, help, option, bits_length = None): + pos_name = 28 + pos_comment = 30 + name_line='' + help_line='' + option_line='' + + if length == 0 and name == 'dummy': + return '\n' + + if bits_length == 0: + return '\n' + + is_array = False + if length in [1,2,4,8]: + type = "UINT%d" % (length * 8) + else: + is_array = True + type = "UINT8" + + if item and item['value'].startswith('{'): + type = "UINT8" + is_array = True + + if struct != '': + struct_base = struct.rstrip('*') + name = '*' * (len(struct) - len(struct_base)) + name + struct = struct_base + type = struct + if struct in ['UINT8','UINT16','UINT32','UINT64']: + is_array = True + unit = int(type[4:]) // 8 + length = length / unit + else: + is_array = False + + if is_array: + name = name + '[%d]' % length + + if len(type) < pos_name: + space1 = pos_name - len(type) + else: + space1 = 1 + + if bsf_name != '': + name_line=" %s\n" % bsf_name + else: + name_line="N/A\n" + + if help != '': + help_line = self.process_multilines (help, 80) + + if option != '': + option_line = self.process_multilines (option, 80) + + if offset is None: + offset_str = '????' + else: + offset_str = '0x%04X' % offset + + if bits_length is None: + bits_length = '' + else: + bits_length = ' : %d' % bits_length + + #return "\n/** %s%s%s**/\n %s%s%s%s;\n" % (name_line, help_line, option_line, type, ' ' * space1, name, bits_length) + return "\n /* %s */\n %s%s%s%s;\n" % (name_line.strip(), type, ' ' * space1, name, bits_length) + + + def create_accessor (self, item, category, name, length, offset, struct, bsf_name, help, option, is_set, bits_length = None): + + if length == 0 and name == 'dummy': + return '\n' + + if bits_length == 0: + return '\n' + + is_array = False + if length in [1,2,4,8]: + type = "UINT%d" % (length * 8) + else: + is_array = True + type = "UINT8" + + if item and item['value'].startswith('{'): + type = "UINT8" + is_array = True + + if struct != '': + struct_base = struct.rstrip('*') + name = '*' * (len(struct) - len(struct_base)) + name + struct = struct_base + type = struct + if struct in ['UINT8','UINT16','UINT32','UINT64']: + is_array = True + unit = int(type[4:]) // 8 + length = length / unit + else: + is_array = False + + if is_array: + name = name + '[%d]' % length + + if bits_length is None: + bits_length = '' + else: + bits_length = ' : %d' % bits_length + + path = item['path'].split(".") + final_acs_list = [] + if is_set: + ''' + STATIC + VOID + EFIAPI + SET_%s ( + IN EFI_HANDLE _handle, + IN EFI_GUID *Guid, + IN %s val, + ) { + ((%s*)((UINTN)_handle + sizeof (VERIFIED_POLICY_DESCRIPTOR)))->%s = val; + ReportVerifiedPolicyAccess (_handle, Guid, offset, size, FALSE); + } + ''' + final_acs_list.append("inline" ) + final_acs_list.append("STATIC" ) + final_acs_list.append("VOID" ) + final_acs_list.append("EFIAPI" ) + final_acs_list.append("SET_%s (" % "_".join(path)) + final_acs_list.append(" IN EFI_HANDLE _handle," ) + final_acs_list.append(" IN EFI_GUID *Guid," ) + final_acs_list.append(" IN %s val" % type) + final_acs_list.append(" ) {" ) + final_acs_list.append(" ((%s*)((UINTN)_handle + sizeof (VERIFIED_POLICY_DESCRIPTOR)))->%s = val;" % (path[0], path[1])) + final_acs_list.append(" ReportVerifiedPolicyAccess (_handle, Guid, 0x%x, 0x%x, TRUE);" % (length, offset)) + final_acs_list.append("}\n\n") + + # Set default value + ''' + STATIC + VOID + EFIAPI + SET_%s_default ( + IN EFI_HANDLE _handle, + IN EFI_GUID *Guid + ) { + ((%s*)((UINTN)_handle + sizeof (VERIFIED_POLICY_DESCRIPTOR)))->%s = 0x%x; + ReportVerifiedPolicyAccess (_handle, Guid, offset, size, FALSE); + } + ''' + final_acs_list.append("inline" ) + final_acs_list.append("STATIC" ) + final_acs_list.append("VOID" ) + final_acs_list.append("EFIAPI" ) + acs_default = "SET_%s_default (" % "_".join(path) + final_acs_list.append(acs_default) + final_acs_list.append(" IN EFI_HANDLE _handle," ) + final_acs_list.append(" IN EFI_GUID *Guid" ) + final_acs_list.append(" ) {" ) + final_acs_list.append(" ((%s*)((UINTN)_handle + sizeof (VERIFIED_POLICY_DESCRIPTOR)))->%s = 0x%x;" % (path[0], path[1], int(item['value'], 0))) + final_acs_list.append(" ReportVerifiedPolicyAccess (_handle, Guid, 0x%x, 0x%x, TRUE);" % (length, offset)) + final_acs_list.append("}\n\n") + else: + ''' + STATIC + %s + EFIAPI + GET_%s ( + IN EFI_HANDLE _handle, + IN EFI_GUID *Guid + ) { + %s Temp; + if (((VERIFIED_POLICY_DESCRIPTOR*)_handle)->Size >= (OFFSET_OF(%s, %s) + (sizeof (((%s *)0)->%s)) { + Temp = ((%s*)((UINTN)_handle + sizeof (VERIFIED_POLICY_DESCRIPTOR)))->%s; + } else { + Temp = 0x%x; + } + ReportVerifiedPolicyAccess (_handle, Guid, offset, size, FALSE); + return Temp; + } + ''' + final_acs_list.append("inline" ) + final_acs_list.append("STATIC" ) + final_acs_list.append("%s" % type) + final_acs_list.append("EFIAPI" ) + final_acs_list.append("GET_%s (" % "_".join(path)) + final_acs_list.append(" IN EFI_HANDLE _handle," ) + final_acs_list.append(" IN EFI_GUID *Guid" ) + final_acs_list.append(" ) {" ) + final_acs_list.append(" %s Temp;" % type) + final_acs_list.append(" if (((VERIFIED_POLICY_DESCRIPTOR*)_handle)->Size >= (OFFSET_OF(%s, %s) + (sizeof (((%s*)0)->%s)))) {" % (path[0], path[1], path[0], path[1])) + final_acs_list.append(" Temp = ((%s*)((UINTN)_handle + sizeof (VERIFIED_POLICY_DESCRIPTOR)))->%s;" % (path[0], path[1])) + final_acs_list.append(" } else {" ) + final_acs_list.append(" Temp = 0x%x;" % int(item['value'], 0)) + final_acs_list.append(" }" ) + final_acs_list.append(" ReportVerifiedPolicyAccess (_handle, Guid, 0x%x, 0x%x, FALSE);" % (length, offset)) + final_acs_list.append(" return Temp;" ) + final_acs_list.append("}\n\n") + + # Get default value + ''' + STATIC + %s + EFIAPI + GET_%s_default ( + IN EFI_HANDLE _handle, + IN EFI_GUID *Guid + ) { + ReportVerifiedPolicyAccess (_handle, Guid, offset, size, FALSE); + return 0x%x; + } + ''' + final_acs_list.append("inline" ) + final_acs_list.append("STATIC" ) + final_acs_list.append("%s" % type) + final_acs_list.append("EFIAPI" ) + acs_default = "GET_%s_default (" % "_".join(path) + final_acs_list.append(acs_default) + final_acs_list.append(" IN EFI_HANDLE _handle," ) + final_acs_list.append(" IN EFI_GUID *Guid" ) + final_acs_list.append(" ) {" ) + final_acs_list.append(" ReportVerifiedPolicyAccess (_handle, Guid, 0x%x, 0x%x, FALSE);" % (length, offset)) + final_acs_list.append(" return 0x%x;" % int(item['value'], 0)) + final_acs_list.append("}\n\n") + + final_acs_str = "\n".join(final_acs_list) + return (final_acs_str, acs_default.rstrip (' (')) + + + def create_struct (self, cname, top, struct_dict): + index = 0 + last = '' + lines = [] + lines.append ('\ntypedef struct {\n') + for field in top: + if field[0] == '$': + continue + + index += 1 + + t_item = top[field] + if 'indx' not in t_item: + if CGenCfgData.STRUCT not in top[field]: + continue + + if struct_dict[field][1] == 0: + continue + + append = True + struct_info = top[field][CGenCfgData.STRUCT] + + if 'struct' in struct_info: + struct, array_num, var = self.get_struct_array_info (struct_info['struct']) + if array_num > 0: + if last == struct: + append = False + last = struct + if var == '': + var = field + + field = CGenCfgData.format_struct_field_name (var, struct_dict[field][1]) + else: + struct = struct_dict[field][0] + field = CGenCfgData.format_struct_field_name (field, struct_dict[field][1]) + + if append: + line = self.create_field (None, field, 0, 0, struct, '', '', '') + lines.append (' %s' % line) + last = struct + continue + + item = self.get_item_by_index (t_item['indx']) + if item['cname'] == 'CfgHeader' and index == 1 or (item['cname'] == 'CondValue' and index == 2): + continue + + bit_length = None + length = (item['length'] + 7) // 8 + match = re.match("^(\d+)([b|B|W|D|Q])([B|W|D|Q]?)", t_item['length']) + if match and match.group(2) == 'b': + bit_length = int(match.group(1)) + if match.group(3) != '': + length = CGenCfgData.bits_width[match.group(3)] // 8 + else: + length = 4 + offset = item['offset'] // 8 + struct = item.get('struct', '') + name = field + prompt = item['name'] + help = item['help'] + option = item['option'] + line = self.create_field (item, name, length, offset, struct, prompt, help, option, bit_length) + lines.append (' %s' % line) + last = struct + + lines.append ('\n} %s;\n\n' % cname) + + return lines + + + def traverse_struct (self, top, struct_dict, target_min_ver, category, is_set): + index = 0 + last = '' + lines = [] + defaults = [] + + for field in top: + if field[0] == '$': + continue + + index += 1 + + t_item = top[field] + + try: + minver = int(t_item['minver'], 0) + except: + minver = 0 + + if minver != target_min_ver: + continue + + if 'indx' not in t_item: + if CGenCfgData.STRUCT not in top[field]: + continue + + if struct_dict[field][1] == 0: + continue + + append = True + struct_info = top[field][CGenCfgData.STRUCT] + + if 'struct' in struct_info: + struct, array_num, var = self.get_struct_array_info (struct_info['struct']) + if array_num > 0: + if last == struct: + append = False + last = struct + if var == '': + var = field + + field = CGenCfgData.format_struct_field_name (var, struct_dict[field][1]) + else: + struct = struct_dict[field][0] + field = CGenCfgData.format_struct_field_name (field, struct_dict[field][1]) + + if append: + (line, default) = self.create_accessor (None, category, field, 0, 0, struct, '', '', '', is_set) + lines.append (' %s' % line) + defaults.append (default) + last = struct + continue + + item = self.get_item_by_index (t_item['indx']) + + bit_length = None + length = (item['length'] + 7) // 8 + match = re.match("^(\d+)([b|B|W|D|Q])([B|W|D|Q]?)", t_item['length']) + if match and match.group(2) == 'b': + bit_length = int(match.group(1)) + if match.group(3) != '': + length = CGenCfgData.bits_width[match.group(3)] // 8 + else: + length = 4 + offset = item['offset'] // 8 + struct = item.get('struct', '') + name = field + prompt = item['name'] + help = item['help'] + option = item['option'] + (line, default) = self.create_accessor (item, category, name, length, offset, struct, prompt, help, option, is_set, bit_length) + lines.append ('%s' % line) + defaults.append (default) + last = struct + + lines.append ('\n') + + return (lines, defaults) + + + def create_header_file (self, hdr_file_name, com_hdr_file_name = ''): + def _build_header_struct (name, cfgs, level): + if CGenCfgData.STRUCT in cfgs: + if 'CfgHeader' in cfgs: + # collect CFGDATA TAG IDs + cfghdr = self.get_item_by_index (cfgs['CfgHeader']['indx']) + tag_val = array_str_to_value(cfghdr['value']) >> 20 + tag_dict[name] = tag_val + if level == 1: + tag_curr[0] = tag_val + struct_dict[name] = (level, tag_curr[0], cfgs) + + tag_curr = [0] + tag_dict = {} + struct_dict = {} + self.traverse_cfg_tree (_build_header_struct) + + if tag_curr[0] == 0: + hdr_mode = 2 + else: + hdr_mode = 1 + + # filter out the items to be built for tags and structures + struct_list = [] + for each in struct_dict: + match = False + for check in CGenCfgData.exclude_struct: + if re.match (check, each): + match = True + if each in tag_dict: + if each not in CGenCfgData.include_tag: + del tag_dict[each] + break + if not match: + struct_list.append ({'name':each, 'alias':'', 'count' : 0, 'level':struct_dict[each][0], + 'tag':struct_dict[each][1], 'node':struct_dict[each][2]}) + + # sort by level so that the bottom level struct will be build first to satisfy dependencies + struct_list = sorted(struct_list, key=lambda x: x['level'], reverse=True) + + # Convert XXX_[0-9]+ to XXX as an array hint + for each in struct_list: + cfgs = each['node'] + if 'struct' in cfgs['$STRUCT']: + each['alias'], array_num, var = self.get_struct_array_info (cfgs['$STRUCT']['struct']) + else: + match = re.match('(\w+)(_\d+)', each['name']) + if match: + each['alias'] = match.group(1) + else: + each['alias'] = each['name'] + + # count items for array build + for idx, each in enumerate(struct_list): + if idx > 0: + last_struct = struct_list[idx-1]['node']['$STRUCT'] + curr_struct = each['node']['$STRUCT'] + if struct_list[idx-1]['alias'] == each['alias'] and \ + curr_struct['length'] == last_struct['length'] and \ + curr_struct['offset'] == last_struct['offset'] + last_struct['length']: + for idx2 in range (idx-1, -1, -1): + if struct_list[idx2]['count'] > 0: + struct_list[idx2]['count'] += 1 + break + continue + each['count'] = 1 + + # generate common header + if com_hdr_file_name: + self.write_cfg_header_file (com_hdr_file_name, 0, tag_dict, struct_list) + + # generate platform header + self.write_cfg_header_file (hdr_file_name, hdr_mode, tag_dict, struct_list) + + return 0 + + + def create_policy_header_file (self, hdr_file_name, com_hdr_file_name = ''): + def _build_header_struct (name, cfgs, level): + if CGenCfgData.STRUCT in cfgs: + if 'PolicyHeader' in cfgs: + # collect macro definitions + cfghdr = self.get_item_by_index (cfgs['PolicyHeader']['indx']) + tag_val = array_str_to_value(cfghdr['value']) >> 20 + tag_dict[name] = tag_val + if level == 1: + tag_curr[0] = tag_val + struct_dict[name] = (level, tag_curr[0], cfgs) + + tag_curr = [0] + tag_dict = {} + struct_dict = {} + self.traverse_cfg_tree (_build_header_struct) + + if tag_curr[0] == 0: + hdr_mode = 2 + else: + hdr_mode = 1 + + # filter out the items to be built for tags and structures + struct_list = [] + for each in struct_dict: + match = False + for check in CGenCfgData.exclude_struct: + if re.match (check, each): + match = True + if each in tag_dict: + if each not in CGenCfgData.include_tag: + del tag_dict[each] + break + if not match: + struct_list.append ({'name':each, 'alias':'', 'count' : 0, 'level':struct_dict[each][0], + 'tag':struct_dict[each][1], 'node':struct_dict[each][2]}) + + # sort by level so that the bottom level struct will be build first to satisfy dependencies + struct_list = sorted(struct_list, key=lambda x: x['level'], reverse=True) + + # Convert XXX_[0-9]+ to XXX as an array hint + for each in struct_list: + cfgs = each['node'] + if 'struct' in cfgs['$STRUCT']: + each['alias'], array_num, var = self.get_struct_array_info (cfgs['$STRUCT']['struct']) + else: + match = re.match('(\w+)(_\d+)', each['name']) + if match: + each['alias'] = match.group(1) + else: + each['alias'] = each['name'] + + # count items for array build + for idx, each in enumerate(struct_list): + if idx > 0: + last_struct = struct_list[idx-1]['node']['$STRUCT'] + curr_struct = each['node']['$STRUCT'] + if struct_list[idx-1]['alias'] == each['alias'] and \ + curr_struct['length'] == last_struct['length'] and \ + curr_struct['offset'] == last_struct['offset'] + last_struct['length']: + for idx2 in range (idx-1, -1, -1): + if struct_list[idx2]['count'] > 0: + struct_list[idx2]['count'] += 1 + break + continue + each['count'] = 1 + + # generate platform header + self.write_policy_header_file (hdr_file_name, hdr_mode, struct_list) + + return 0 + + + def load_yaml (self, cfg_file, shallow_load=False, is_policy=False): + cfg_yaml = CFG_YAML() + self.initialize () + self.is_policy = is_policy + self._cfg_tree = cfg_yaml.load_yaml (cfg_file) + self._def_dict = cfg_yaml.def_dict + self._yaml_path = os.path.dirname(cfg_file) + if not shallow_load: + self.build_cfg_list() + self.build_var_dict() + self.update_def_value() + return 0 + + +def usage(): + print ('\n'.join([ + "GenCfgData Version 0.50", + "Usage:", + " GenCfgData GENINC BinFile IncOutFile", + " GenCfgData GENPKL YamlFile PklOutFile", + " GenCfgData GENBIN YamlFile[;DltFile] BinOutFile", + " GenCfgData GENDLT YamlFile[;BinFile] DltOutFile", + " GenCfgData GENHDR YamlFile HdrOutFile" + ])) + + +def main(): + # Parse the options and args + argc = len(sys.argv) + if argc < 4 or argc > 5: + usage() + return 1 + + gen_cfg_data = CGenCfgData() + command = sys.argv[1].upper() + out_file = sys.argv[3] + + file_list = sys.argv[2].split(';') + if len(file_list) >= 2: + yml_file = file_list[0] + dlt_file = file_list[1] + elif len(file_list) == 1: + yml_file = file_list[0] + dlt_file = '' + else: + raise Exception ("ERROR: Invalid parameter '%s' !" % sys.argv[2]) + + if command == "GENDLT" and yml_file.endswith('.dlt'): + # It needs to expand an existing DLT file + dlt_file = yml_file + lines = gen_cfg_data.expand_include_files (dlt_file) + write_lines (lines, out_file) + return 0 + + bin_file = '' + if (yml_file.lower().endswith('.bin')) and (command == "GENINC"): + # It is binary file + bin_file = yml_file + yml_file = '' + + if bin_file: + gen_cfg_data.generate_data_inc_file(out_file, bin_file) + return 0 + + cfg_bin_file = '' + cfg_bin_file2 = '' + if dlt_file: + if command == "GENDLT": + cfg_bin_file = dlt_file + dlt_file = '' + if len(file_list) >= 3: + cfg_bin_file2 = file_list[2] + + if yml_file.lower().endswith('.pkl'): + with open(yml_file, "rb") as pkl_file: + gen_cfg_data.__dict__ = marshal.load(pkl_file) + gen_cfg_data.prepare_marshal (False) + else: + if command == 'GENHDR': + gen_cfg_data.load_yaml (yml_file, is_policy=True) + + if command == 'GENPKL': + gen_cfg_data.prepare_marshal (True) + with open(out_file, "wb") as pkl_file: + marshal.dump(gen_cfg_data.__dict__, pkl_file) + json_file = os.path.splitext(out_file)[0] + '.json' + fo = open (json_file, 'w') + path_list = [] + cfgs = {'_cfg_page' : gen_cfg_data._cfg_page, '_cfg_list':gen_cfg_data._cfg_list, '_path_list' : path_list} + # optimize to reduce size + path = None + for each in cfgs['_cfg_list']: + new_path = each['path'][:-len(each['cname'])-1] + if path != new_path: + path = new_path + each['path'] = path + path_list.append(path) + else: + del each['path'] + if each['order'] == each['offset']: + del each['order'] + del each['offset'] + + # value is just used to indicate display type + value = each['value'] + if value.startswith ('0x'): + hex_len = ((each['length'] + 7) // 8) * 2 + if len(value) == hex_len: + value = 'x%d' % hex_len + else: + value = 'x' + each['value'] = value + elif value and value[0] in ['"', "'", '{']: + each['value'] = value[0] + else: + del each['value'] + + fo.write(repr(cfgs)) + fo.close () + return 0 + + if dlt_file: + gen_cfg_data.override_default_value(dlt_file) + + if command == "GENBIN": + if len(file_list) == 3: + old_data = gen_cfg_data.generate_binary_array() + fi = open (file_list[2], 'rb') + new_data = bytearray (fi.read ()) + fi.close () + if len(new_data) != len(old_data): + raise Exception ("Binary file '%s' length does not match, ignored !" % file_list[2]) + else: + gen_cfg_data.load_default_from_bin (new_data) + gen_cfg_data.override_default_value(dlt_file) + + gen_cfg_data.generate_binary(out_file) + + elif command == "GENDLT": + gen_cfg_data.generate_delta_file (out_file, cfg_bin_file, cfg_bin_file2) + + elif command == "GENHDR": + out_files = out_file.strip("'").split(';') + brd_out_file = out_files[0].strip() + if len(out_files) > 1: + com_out_file = out_files[1].strip() + else: + com_out_file = '' + gen_cfg_data.create_policy_header_file(brd_out_file, com_out_file) + + elif command == "GENINC": + gen_cfg_data.generate_data_inc_file(out_file) + + elif command == "DEBUG": + gen_cfg_data.print_cfgs() + + else: + raise Exception ("Unsuported command '%s' !" % command) + + return 0 + + +if __name__ == '__main__': + sys.exit(main()) + diff --git a/RepoDetails.md b/RepoDetails.md index 6af3d3f1d1..e3ff0ea164 100644 --- a/RepoDetails.md +++ b/RepoDetails.md @@ -1,110 +1,110 @@ -# Project Mu Basecore Repository - -??? info "Git Details" - Repository Url: {{mu_basecore.url}} - Branch: {{mu_basecore.branch}} - Commit: [{{mu_basecore.commit}}]({{mu_basecore.commitlink}}) - Commit Date: {{mu_basecore.date}} - -This repository is considered foundational and fundamental to Project Mu. The -guiding philosophy is that this any code within this repository should be one or -more of the following - -* Part of the build system -* Common to any silicon architecture -* Part of the "API layer" that contains protocol and library definitions - including - * Industry Standards - * UEFI Specifications - * ACPI Specifications -* Part of the "PI" layer that contains driver dispatch logic, event/signaling - logic, or memory management logic - * This can also include central technologies like variable services - -## More Info - -Please see the Project Mu docs () for more -information. - -This project has adopted the [Microsoft Open Source Code of -Conduct](https://opensource.microsoft.com/codeofconduct/). - -For more information see the [Code of Conduct -FAQ](https://opensource.microsoft.com/codeofconduct/faq/) or contact -[opencode@microsoft.com](mailto:opencode@microsoft.com) with any additional -questions or comments. - -## Issues - -Please open any issues in the Project Mu GitHub tracker. [More -Details](https://microsoft.github.io/mu/How/contributing/) - -## Contributing Code or Docs - -Please follow the general Project Mu Pull Request process. [More -Details](https://microsoft.github.io/mu/How/contributing/) - -* [Code Requirements](https://microsoft.github.io/mu/CodeDevelopment/requirements/) -* [Doc Requirements](https://microsoft.github.io/mu/DeveloperDocs/requirements/) - -## Builds - -Please follow the steps in the Project Mu docs to build for CI and local -testing. [More Details](https://microsoft.github.io/mu/CodeDevelopment/compile/) - -## Copyright & License - -Copyright (C) Microsoft Corporation -SPDX-License-Identifier: BSD-2-Clause-Patent - -### Upstream License (TianoCore) - -Copyright (c) 2019, TianoCore and contributors. All rights reserved. - -SPDX-License-Identifier: BSD-2-Clause-Patent - -Redistribution and use in source and binary forms, with or without modification, -are permitted provided that the following conditions are met: - -1. Redistributions of source code must retain the above copyright notice, this - list of conditions and the following disclaimer. - -2. Redistributions in binary form must reproduce the above copyright notice, - this list of conditions and the following disclaimer in the documentation - and/or other materials provided with the distribution. - -Subject to the terms and conditions of this license, each copyright holder and -contributor hereby grants to those receiving rights under this license a -perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable -(except for failure to satisfy the conditions of this license) patent license to -make, have made, use, offer to sell, sell, import, and otherwise transfer this -software, where such license applies only to those patent claims, already -acquired or hereafter acquired, licensable by such copyright holder or -contributor that are necessarily infringed by: - -(a) their Contribution(s) (the licensed copyrights of copyright holders and - non-copyrightable additions of contributors, in source or binary form) - alone; or - -(b) combination of their Contribution(s) with the work of authorship to which - such Contribution(s) was added by such copyright holder or contributor, if, - at the time the Contribution is added, such addition causes such combination - to be necessarily infringed. The patent license shall not apply to any other - combinations which include the Contribution. - -Except as expressly stated above, no rights or licenses from any copyright -holder or contributor is granted under this license, whether expressly, by -implication, estoppel or otherwise. - -DISCLAIMER - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE -FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL -DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER -CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR -TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF -THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# Project Mu Basecore Repository + +??? info "Git Details" + Repository Url: {{mu_basecore.url}} + Branch: {{mu_basecore.branch}} + Commit: [{{mu_basecore.commit}}]({{mu_basecore.commitlink}}) + Commit Date: {{mu_basecore.date}} + +This repository is considered foundational and fundamental to Project Mu. The +guiding philosophy is that this any code within this repository should be one or +more of the following + +* Part of the build system +* Common to any silicon architecture +* Part of the "API layer" that contains protocol and library definitions + including + * Industry Standards + * UEFI Specifications + * ACPI Specifications +* Part of the "PI" layer that contains driver dispatch logic, event/signaling + logic, or memory management logic + * This can also include central technologies like variable services + +## More Info + +Please see the Project Mu docs () for more +information. + +This project has adopted the [Microsoft Open Source Code of +Conduct](https://opensource.microsoft.com/codeofconduct/). + +For more information see the [Code of Conduct +FAQ](https://opensource.microsoft.com/codeofconduct/faq/) or contact +[opencode@microsoft.com](mailto:opencode@microsoft.com) with any additional +questions or comments. + +## Issues + +Please open any issues in the Project Mu GitHub tracker. [More +Details](https://microsoft.github.io/mu/How/contributing/) + +## Contributing Code or Docs + +Please follow the general Project Mu Pull Request process. [More +Details](https://microsoft.github.io/mu/How/contributing/) + +* [Code Requirements](https://microsoft.github.io/mu/CodeDevelopment/requirements/) +* [Doc Requirements](https://microsoft.github.io/mu/DeveloperDocs/requirements/) + +## Builds + +Please follow the steps in the Project Mu docs to build for CI and local +testing. [More Details](https://microsoft.github.io/mu/CodeDevelopment/compile/) + +## Copyright & License + +Copyright (C) Microsoft Corporation +SPDX-License-Identifier: BSD-2-Clause-Patent + +### Upstream License (TianoCore) + +Copyright (c) 2019, TianoCore and contributors. All rights reserved. + +SPDX-License-Identifier: BSD-2-Clause-Patent + +Redistribution and use in source and binary forms, with or without modification, +are permitted provided that the following conditions are met: + +1. Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. + +2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + +Subject to the terms and conditions of this license, each copyright holder and +contributor hereby grants to those receiving rights under this license a +perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable +(except for failure to satisfy the conditions of this license) patent license to +make, have made, use, offer to sell, sell, import, and otherwise transfer this +software, where such license applies only to those patent claims, already +acquired or hereafter acquired, licensable by such copyright holder or +contributor that are necessarily infringed by: + +(a) their Contribution(s) (the licensed copyrights of copyright holders and + non-copyrightable additions of contributors, in source or binary form) + alone; or + +(b) combination of their Contribution(s) with the work of authorship to which + such Contribution(s) was added by such copyright holder or contributor, if, + at the time the Contribution is added, such addition causes such combination + to be necessarily infringed. The patent license shall not apply to any other + combinations which include the Contribution. + +Except as expressly stated above, no rights or licenses from any copyright +holder or contributor is granted under this license, whether expressly, by +implication, estoppel or otherwise. + +DISCLAIMER + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR +TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF +THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/StandaloneMmPkg/Library/StandaloneMmCoreEntryPointNull/StandaloneMmCoreEntryPointNull.inf b/StandaloneMmPkg/Library/StandaloneMmCoreEntryPointNull/StandaloneMmCoreEntryPointNull.inf index 6e5e2c8db1..4fd80a5c08 100644 --- a/StandaloneMmPkg/Library/StandaloneMmCoreEntryPointNull/StandaloneMmCoreEntryPointNull.inf +++ b/StandaloneMmPkg/Library/StandaloneMmCoreEntryPointNull/StandaloneMmCoreEntryPointNull.inf @@ -1,32 +1,32 @@ -## @file -# Module entry point library for DXE core. -# -# Copyright (c) 2017 - 2021, Arm Ltd. All rights reserved.
-# -# SPDX-License-Identifier: BSD-2-Clause-Patent -# -# -## - -[Defines] - INF_VERSION = 0x0001001A - BASE_NAME = StandaloneMmCoreEntryPointNull - FILE_GUID = 5E28E9FA-67DC-4408-A177-05F72CD7E248 - MODULE_TYPE = MM_CORE_STANDALONE - VERSION_STRING = 1.0 - PI_SPECIFICATION_VERSION = 0x00010032 - LIBRARY_CLASS = StandaloneMmCoreEntryPoint|MM_CORE_STANDALONE - -# -# VALID_ARCHITECTURES = IA32 X64 IPF EBC (EBC is for build only) -# - -[Sources] - StandaloneMmCoreEntryPointNull.c - -[Packages] - MdePkg/MdePkg.dec - -[LibraryClasses] - BaseLib - DebugLib +## @file +# Module entry point library for DXE core. +# +# Copyright (c) 2017 - 2021, Arm Ltd. All rights reserved.
+# +# SPDX-License-Identifier: BSD-2-Clause-Patent +# +# +## + +[Defines] + INF_VERSION = 0x0001001A + BASE_NAME = StandaloneMmCoreEntryPointNull + FILE_GUID = 5E28E9FA-67DC-4408-A177-05F72CD7E248 + MODULE_TYPE = MM_CORE_STANDALONE + VERSION_STRING = 1.0 + PI_SPECIFICATION_VERSION = 0x00010032 + LIBRARY_CLASS = StandaloneMmCoreEntryPoint|MM_CORE_STANDALONE + +# +# VALID_ARCHITECTURES = IA32 X64 IPF EBC (EBC is for build only) +# + +[Sources] + StandaloneMmCoreEntryPointNull.c + +[Packages] + MdePkg/MdePkg.dec + +[LibraryClasses] + BaseLib + DebugLib diff --git a/edk2_core_path_env.json b/edk2_core_path_env.json index 6a3d0fe4cd..58c8fbff3c 100644 --- a/edk2_core_path_env.json +++ b/edk2_core_path_env.json @@ -1,5 +1,5 @@ -{ - "scope": "global", - "flags": ["set_shell_var"], - "var_name": "EDK2_CORE_PATH" +{ + "scope": "global", + "flags": ["set_shell_var"], + "var_name": "EDK2_CORE_PATH" } \ No newline at end of file