Merge branch 'master' into sdmmc-override

This commit is contained in:
MattP 2026-08-16 22:35:36 -04:00 committed by GitHub
commit faaf1a1285
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
784 changed files with 74850 additions and 17340 deletions

View file

@ -22,7 +22,7 @@ Focused on building a single target platform and confirming functionality on tha
* Top level CI files should be named `<host os>-<tool_chain>.yml`
* The pipeline YAML file name is referenced in Azure Pipelines. To allow flexibility for toolchain updates in the
YAML file without necessitating changes in Azure Pipelines, the toolchain version is not included in the filename.
For example, `Windows-VS.yml` is used instead of `Windows-VS2022.yml`.
For example, `Windows-VS.yml` is used instead of `Windows-VS2026.yml`.
## Links

View file

@ -25,7 +25,7 @@ variables:
jobs:
- template: templates/pr-gate-build-job.yml
parameters:
tool_chain_tag: 'VS2022'
tool_chain_tag: 'VS2026'
vm_image: ${{ variables.default_windows_vm }}
arch_list: "IA32,X64"
usePythonVersion: ${{ variables.default_python_version }}

View file

@ -11,4 +11,4 @@ variables:
default_python_version: "3.12"
default_linux_container: "ghcr.io/tianocore/containers/fedora-43-test:b562821"
default_linux_vm: "ubuntu-24.04"
default_windows_vm: "windows-2022"
default_windows_vm: "windows-2025-vs2026"

View file

@ -117,7 +117,7 @@ jobs:
container: ${{ parameters.container }}
steps:
# Strip test targets for CI toolchains other than GCC and VS2022, as these
# Strip test targets for CI toolchains other than GCC and VS2026, as these
# cannot run them and would be duplicating work during CI if they could.
# Note: Within PR gate CI, NOOPT is only used for building tests.
- bash: |
@ -147,7 +147,7 @@ jobs:
clean: all
pool:
vmImage: 'windows-2022'
vmImage: 'windows-2025-vs2026'
steps:
- checkout: self

View file

@ -0,0 +1,32 @@
# TianoCore edk2 GitHub Breaking Change Deprecation Issue Template
#
# Copyright (c) Microsoft Corporation.
# SPDX-License-Identifier: BSD-2-Clause-Patent
#
name: 💥 Breaking Change (Deprecation)
description: Subissue tracking the start of the deprecation active period for a breaking change
title: "[Breaking Change Deprecation]: <title>"
labels: ["impact:breaking-change", "deprecation:active"]
body:
- type: markdown
attributes:
value: |
👋 This is a subissue of a breaking change Tracking Issue, following the
[Breaking Change and Release Process for EDK II](https://raw.githubusercontent.com/tianocore/tianocore-wiki.github.io/refs/heads/main/rfc/text/0003-edk2-breaking-change-and-release-process.md).
It tracks the start of the deprecation active period. It is closed when the deprecation PR merges and the
compatibility window opens. Detailed documentation for the change lives only in the `BREAKING-CHANGES.md`
entry.
- type: textarea
id: special_notes
attributes:
label: Special Notes
description: |
Any special notes about the deprecation portion of the process (for example, details about how the affected
item is marked as deprecated). If there are no special notes, enter exactly: `Breaking change process issue.`
value: "Breaking change process issue."
validations:
required: true

View file

@ -0,0 +1,31 @@
# TianoCore edk2 GitHub Breaking Change Removal Issue Template
#
# Copyright (c) Microsoft Corporation.
# SPDX-License-Identifier: BSD-2-Clause-Patent
#
name: 💥 Breaking Change (Removal)
description: Subissue tracking the eventual removal of a deprecated item
title: "[Breaking Change Removal]: <title>"
labels: ["impact:breaking-change", "deprecation:removal"]
body:
- type: markdown
attributes:
value: |
👋 This is a subissue of a breaking change Tracking Issue, following the
[Breaking Change and Release Process for EDK II](https://raw.githubusercontent.com/tianocore/tianocore-wiki.github.io/refs/heads/main/rfc/text/0003-edk2-breaking-change-and-release-process.md).
It tracks the eventual removal of the deprecated item. It is closed when the item is removed from the
codebase. Detailed documentation for the change lives only in the `BREAKING-CHANGES.md` entry.
- type: textarea
id: special_notes
attributes:
label: Special Notes
description: |
Any special notes about the removal portion of the process. If there are no special notes, enter exactly:
`Breaking change process issue.`
value: "Breaking change process issue."
validations:
required: true

View file

@ -0,0 +1,51 @@
# TianoCore edk2 GitHub Breaking Change Tracking Issue Template
#
# Copyright (c) Microsoft Corporation.
# SPDX-License-Identifier: BSD-2-Clause-Patent
#
name: 💥 Breaking Change (Tracking)
description: Central tracking issue for a breaking change
title: "[Breaking Change Tracking]: <title>"
labels: ["impact:breaking-change", "deprecation:tracking"]
body:
- type: markdown
attributes:
value: |
👋 Use this issue to track a breaking change following the
[Breaking Change and Release Process for EDK II](https://raw.githubusercontent.com/tianocore/tianocore-wiki.github.io/refs/heads/main/rfc/text/0003-edk2-breaking-change-and-release-process.md).
**Read that process before filing this issue.**
This is the central Tracking Issue. The Deprecation Issue and Removal Issue (when applicable) are created as
subissues of this one. The detailed documentation for the change (motivation, what replaces it, migration
guidance, removal target, etc.) is described in the `BREAKING-CHANGES.md` entry and should not be duplicated
here.
- type: textarea
id: summary
attributes:
label: Summary
description: A high-level summary of the breaking change (a few sentences).
validations:
required: true
- type: input
id: breaking_changes_entry
attributes:
label: BREAKING-CHANGES.md Entry
description: Link to the corresponding entry in `BREAKING-CHANGES.md`. May be updated after issue creation.
placeholder: https://github.com/tianocore/edk2/blob/master/BREAKING-CHANGES.md#<anchor>
validations:
required: true
- type: textarea
id: additional_info
attributes:
label: Additional Information
description: |
Any other relevant information that is not already captured in the `BREAKING-CHANGES.md` entry. Do not
duplicate content from that entry here.
validations:
required: false

View file

@ -129,7 +129,7 @@ body:
description: |
Examples:
- **OS**: Ubuntu 24.04 or Windows 11...
- **Tool Chain**: GCC or VS2022 or CLANGPDB...
- **Tool Chain**: GCC or VS2026 or CLANGPDB...
value: |
- OS(s):
- Tool Chain(s):

View file

@ -11,6 +11,7 @@
- [ ] Breaking change?
- **Breaking change** - Does this PR cause a break in build or boot behavior?
- Examples: Does it add a new library class or move a module to a different repo.
- If checked, follow the [Breaking Change and Release Process](https://raw.githubusercontent.com/tianocore/tianocore-wiki.github.io/refs/heads/main/rfc/text/0003-edk2-breaking-change-and-release-process.md).
- [ ] Impacts security?
- **Security** - Does this PR have a direct security impact?
- Examples: Crypto algorithm change or buffer overflow fix.

View file

@ -65,7 +65,7 @@ jobs:
steps:
- name: Checkout
uses: actions/checkout@v6
uses: actions/checkout@v7
- run: |
git config --global --add safe.directory '*'

View file

@ -25,7 +25,7 @@ on:
jobs:
analyze:
name: Analyze
runs-on: windows-2022
runs-on: windows-2025
permissions:
actions: read
contents: read
@ -76,7 +76,7 @@ jobs:
steps:
- name: Checkout repository
uses: actions/checkout@v6
uses: actions/checkout@v7
- name: Install Python
uses: actions/setup-python@v6
@ -149,7 +149,7 @@ jobs:
- name: Setup
if: steps.get_ci_file_operations.outputs.setup_supported == 'true'
run: stuart_setup -c .pytool/CISettings.py -t DEBUG -a ${{ matrix.ArchList }} TOOL_CHAIN_TAG=VS2022
run: stuart_setup -c .pytool/CISettings.py -t DEBUG -a ${{ matrix.ArchList }} TOOL_CHAIN_TAG=VS2026
- name: Upload Setup Log As An Artifact
uses: actions/upload-artifact@v7
@ -163,7 +163,7 @@ jobs:
- name: CI Setup
if: steps.get_ci_file_operations.outputs.ci_setup_supported == 'true'
run: stuart_ci_setup -c .pytool/CISettings.py -t DEBUG -a ${{ matrix.ArchList }} TOOL_CHAIN_TAG=VS2022
run: stuart_ci_setup -c .pytool/CISettings.py -t DEBUG -a ${{ matrix.ArchList }} TOOL_CHAIN_TAG=VS2026
- name: Upload CI Setup Log As An Artifact
uses: actions/upload-artifact@v7
@ -176,7 +176,7 @@ jobs:
if-no-files-found: ignore
- name: Update
run: stuart_update -c .pytool/CISettings.py -t DEBUG -a ${{ matrix.ArchList }} TOOL_CHAIN_TAG=VS2022
run: stuart_update -c .pytool/CISettings.py -t DEBUG -a ${{ matrix.ArchList }} TOOL_CHAIN_TAG=VS2026
- name: Upload Update Log As An Artifact
uses: actions/upload-artifact@v7
@ -189,7 +189,7 @@ jobs:
if-no-files-found: ignore
- name: Build Tools From Source
run: python BaseTools/Edk2ToolsBuild.py -t VS2022
run: python BaseTools/Edk2ToolsBuild.py -t VS2026
- name: Find CodeQL Plugin Directory
id: find_dir
@ -246,7 +246,7 @@ jobs:
- name: Download CodeQL CLI
if: steps.codeqlcli_cache.outputs.cache-hit != 'true'
run: stuart_update -c .pytool/CISettings.py -t DEBUG -a ${{ matrix.ArchList }} TOOL_CHAIN_TAG=VS2022 --codeql
run: stuart_update -c .pytool/CISettings.py -t DEBUG -a ${{ matrix.ArchList }} TOOL_CHAIN_TAG=VS2026 --codeql
- name: Remove CI Plugins Irrelevant to CodeQL
shell: python
@ -269,7 +269,7 @@ jobs:
- name: CI Build
env:
STUART_CODEQL_PATH: ${{ steps.cache_key_gen.outputs.codeql_cli_ext_dep_dir }}
run: stuart_ci_build -c .pytool/CISettings.py -t DEBUG -p ${{ matrix.Package }} -a ${{ matrix.ArchList }} TOOL_CHAIN_TAG=VS2022 --codeql
run: stuart_ci_build -c .pytool/CISettings.py -t DEBUG -p ${{ matrix.Package }} -a ${{ matrix.ArchList }} TOOL_CHAIN_TAG=VS2026 --codeql
- name: Build Cleanup
id: build_cleanup

View file

@ -21,7 +21,7 @@ jobs:
issues: write
steps:
- uses: actions/checkout@v6
- uses: actions/checkout@v7
- name: Remove Labels
env:

View file

@ -30,7 +30,7 @@ jobs:
issues: write
steps:
- uses: actions/checkout@v6
- uses: actions/checkout@v7
- name: Parse Issue Form
uses: stefanbuck/github-issue-parser@v3

View file

@ -37,7 +37,7 @@ jobs:
# Reduce checkout time with sparse-checkout
- name: Checkout repository
uses: actions/checkout@v6
uses: actions/checkout@v7
with:
fetch-depth: 1
sparse-checkout: |

View file

@ -44,7 +44,7 @@ jobs:
# - BaseTools/Scripts: Contains the GetMaintainer.py script
# - Maintainers.txt: Contains the list of maintainers for the repository
- name: Checkout repository
uses: actions/checkout@v6
uses: actions/checkout@v7
with:
fetch-depth: 1
sparse-checkout: |

View file

@ -14,15 +14,15 @@ on:
branches: ['master']
jobs:
build_vs2022:
build_vs2026:
strategy:
matrix:
os: [windows-latest]
os: [windows-2025]
python-version: ['3.12']
tool-chain: ['VS2022']
tool-chain: ['VS2026']
target: ['DEBUG']
extra-build-args: ['FIT_BUILD=TRUE', 'FIT_BUILD=FALSE']
name: Build UPL VS2022
name: Build UPL VS2026
uses: ./.github/workflows/BuildPlatform.yml
with:
runs-on: ${{ matrix.os }}

View file

@ -34,7 +34,7 @@ queue_rules:
- label=push
merge_method: rebase
update_bot_account: tianocore-issues
update_method: rebase
update_method: merge
pull_request_rules:
- name: Automatically merge a PR when all required checks pass and 'push' label is present
@ -52,3 +52,7 @@ pull_request_rules:
actions:
comment:
message: PR can not be merged due to conflict. Please rebase and resubmit
merge_protections_settings:
reporting_method: check-runs

View file

@ -34,6 +34,10 @@ class EccCheck(ICiBuildPlugin):
LineScopePattern = (r'@@ -\d*\,*\d* \+\d*\,*\d* @@.*')
LineNumRange = re.compile(r'@@ -\d*\,*\d* \+(\d*)\,*(\d*) @@.*')
# Sub-directory of the workspace where the package under review is copied
# and scanned by ECC.
BuildTempSubDir = os.path.join('Build', '.pytool', 'Plugin', 'EccCheck')
def GetTestName(self, packagename: str, environment: VarDict) -> tuple:
""" Provide the testcase name and classname for use in reporting
testclassname: a descriptive string for the testcase can include whitespace
@ -77,7 +81,7 @@ class EccCheck(ICiBuildPlugin):
return 0
# Create temp directory
temp_path = os.path.join(workspace_path, 'Build', '.pytool', 'Plugin', 'EccCheck')
temp_path = os.path.join(workspace_path, self.BuildTempSubDir)
try:
# Delete temp directory
if os.path.exists(temp_path):
@ -327,6 +331,8 @@ class EccCheck(ICiBuildPlugin):
for i in ecc_diff_range[modify_file]:
line_no = int(row[4])
if i[0] <= line_no <= i[1] and row[1] not in ignore_error_code:
row[3] = modify_file
row[5] = row[5].replace(self.BuildTempSubDir + os.sep, '')
row[0] = '\nEFI coding style error'
row[1] = 'Error code: ' + row[1]
row[3] = 'file: ' + row[3]

View file

@ -0,0 +1,180 @@
# @file MarkdownLintCheck.py
#
# An edk2-pytool based plugin wrapper for markdownlint
#
# Copyright (c) Microsoft Corporation.
# SPDX-License-Identifier: BSD-2-Clause-Patent
##
import logging
from io import StringIO
import os
from typing import List
from edk2toolext.environment.plugintypes.ci_build_plugin import ICiBuildPlugin
from edk2toollib.utility_functions import RunCmd
from edk2toolext.environment.var_dict import VarDict
from edk2toolext.environment import version_aggregator
class MarkdownLintCheck(ICiBuildPlugin):
"""
A CiBuildPlugin that uses the markdownlint-cli node module to scan the files
from the package being tested for linter errors.
The linter config file (.markdownlint.yaml) must be present in one of the defined
locations otherwise the test will be skipped. These locations were picked to also
align with how editors and tools will find the config file.
1st priority location - At the package root
2nd Priority location - At the workspace root of the build (suggested location unless override needed)
Configuration options:
"MarkdownLintCheck": {
"AuditOnly": False, # If True, log all errors and then mark as skipped
"IgnoreFiles": [] # package root relative file, folder, or glob pattern to ignore
}
"""
CONFIG_FILE_NAME = ".markdownlint.yaml"
def GetTestName(self, packagename: str, environment: VarDict) -> tuple:
""" Provide the testcase name and classname for use in reporting
Args:
packagename: string containing name of package to build
environment: The VarDict for the test to run in
Returns:
a tuple containing the testcase name and the classname
(testcasename, classname)
testclassname: a descriptive string for the testcase can include whitespace
classname: should be patterned <packagename>.<plugin>.<optionally any unique condition>
"""
return ("Lint Markdown files in " + packagename, packagename + ".markdownlint")
##
# External function of plugin. This function is used to perform the task of the CiBuild Plugin
#
# - package is the edk2 path to package. This means workspace/packagepath relative.
# - edk2path object configured with workspace and packages path
# - PkgConfig Object (dict) for the pkg
# - EnvConfig Object
# - Plugin Manager Instance
# - Plugin Helper Obj Instance
# - Junit Logger
# - output_stream the StringIO output stream from this plugin via logging
def RunBuildPlugin(self, packagename, Edk2pathObj, pkgconfig, environment, PLM, PLMHelper, tc, output_stream=None):
abs_pkg_path = Edk2pathObj.GetAbsolutePathOnThisSystemFromEdk2RelativePath(
packagename)
if abs_pkg_path is None:
tc.SetSkipped()
tc.LogStdError("No package {0}".format(packagename))
return -1
# check for node
return_buffer = StringIO()
ret = RunCmd("node", "--version", outstream=return_buffer)
if ret != 0:
tc.SetSkipped()
tc.LogStdError("NodeJs not installed. Test can't run")
logging.warning("NodeJs not installed. Test can't run")
return -1
node_version = return_buffer.getvalue().strip() # format vXX.XX.XX
tc.LogStdOut(f"Node version: {node_version}")
# Check for markdownlint-cli
return_buffer = StringIO()
ret = RunCmd("markdownlint", "--version", outstream=return_buffer)
if ret != 0:
tc.SetSkipped()
tc.LogStdError("markdownlint not installed. Test can't run")
logging.warning("markdownlint not installed. Test can't run")
return -1
mdl_version = return_buffer.getvalue().strip() # format XX.XX.XX
tc.LogStdOut(f"MarkdownLint version: {mdl_version}")
version_aggregator.GetVersionAggregator().ReportVersion(
"MarkDownLint", mdl_version, version_aggregator.VersionTypes.INFO)
# Get relative path for the root of package to use with ignore and path parameters
relpath = os.path.relpath(abs_pkg_path)
# Newer versions of markdownlint don't understand backslashes
relpath = relpath.replace(os.path.sep, '/')
#
# check for any package specific ignore patterns defined by package config
#
Ignores = []
if "IgnoreFiles" in pkgconfig:
for i in pkgconfig["IgnoreFiles"]:
Ignores.append(f"{relpath}/{i}")
#
# Make the path string to check
#
path_to_check = f'{relpath}/**/*.md'
# get path to config file -
# Currently there is support for two different config files
# If the config file is not found then the test case is skipped
#
# 1st - At the package root
# 2nd - At the workspace root of the build
config_file_path = None
# 1st check to see if the config file is at package root
if os.path.isfile(os.path.join(abs_pkg_path, MarkdownLintCheck.CONFIG_FILE_NAME)):
config_file_path = os.path.join(abs_pkg_path, MarkdownLintCheck.CONFIG_FILE_NAME)
# 2nd check to see if at workspace root
elif os.path.isfile(os.path.join(Edk2pathObj.WorkspacePath, MarkdownLintCheck.CONFIG_FILE_NAME)):
config_file_path = os.path.join(Edk2pathObj.WorkspacePath, MarkdownLintCheck.CONFIG_FILE_NAME)
# If not found - skip test
else:
tc.SetSkipped()
tc.LogStdError(f"{MarkdownLintCheck.CONFIG_FILE_NAME} not found. Skipping test")
logging.warning(f"{MarkdownLintCheck.CONFIG_FILE_NAME} not found. Skipping test")
return -1
# Run the linter
results = self._check_markdown(path_to_check, config_file_path, Ignores)
for r in results:
tc.LogStdError(r.strip())
# add result to test case
overall_status = len(results)
if overall_status != 0:
if "AuditOnly" in pkgconfig and pkgconfig["AuditOnly"]:
# set as skipped if AuditOnly
tc.SetSkipped()
return -1
else:
tc.SetFailed("Markdown Lint Check {0} Failed. Errors {1}".format(
packagename, overall_status), "CHECK_FAILED")
else:
tc.SetSuccess()
return overall_status
def _check_markdown(self, rel_file_to_check: os.PathLike, abs_config_file_to_use: os.PathLike, Ignores: List[str]) -> List[str]:
""" Run markdownlint against the given path and return any errors found.
Args:
rel_file_to_check: package root relative glob pattern of markdown files to check
abs_config_file_to_use: absolute path to the .markdownlint.yaml config file to use
Ignores: list of package root relative file, folder, or glob patterns to ignore
Returns:
a list of error strings reported by markdownlint. Empty if no errors found.
"""
output = StringIO()
param = f"--config {abs_config_file_to_use}"
for a in Ignores:
param += f' --ignore "{a}"'
param += f' "{rel_file_to_check}"'
ret = RunCmd("markdownlint", param, outstream=output)
if ret == 0:
return []
else:
return output.getvalue().strip().splitlines()

View file

@ -0,0 +1,11 @@
## @file
# CiBuildPlugin used to lint repository documentation in markdown files
#
# Copyright (c) Microsoft Corporation.
# SPDX-License-Identifier: BSD-2-Clause-Patent
##
{
"scope": "cibuild",
"name": "Markdown Lint Test",
"module": "MarkdownLintCheck"
}

View file

@ -0,0 +1,61 @@
# Markdown Lint Plugin
This CiBuildPlugin scans all the markdown files in a given package and checks for linter errors.
## Requirements
The test case in this plugin will be skipped if the requirements are not met.
1. NodeJs installed and on your path
2. `markdownlint-cli` NodeJs package installed
3. A `.markdownlint.yaml` config file either at your repository root or package root.
- NodeJS: <https://nodejs.org/en/>
- markdownlint-cli: <https://www.npmjs.com/package/markdownlint-cli>
- Source repository: <https://github.com/igorshubovych/markdownlint-cli>
## Configuration
It is desired to use standard configuration methods so that both local editors and CI process leverage the same
configuration. This mostly works but for ignoring files there is currently a small discrepancy.
First there is/can be a `.markdownlintignore` file at root of the repository. This file much like a `.gitignore` is
great for broadly ignoring files with patterns. This works for both usage in a local editor and CI.
For the CI plugin, you can use the `IgnoreFiles` configuration option described in the Plugin Configuration.
## Plugin Configuration
The plugin has only minimal configuration options to support the UEFI codebase.
``` yaml
"MarkdownLintCheck": {
"AuditOnly": False, # If True, log all errors and then mark as skipped
"IgnoreFiles": [] # Package root relative file, folder, or glob pattern to ignore
}
```
### AuditOnly
- `Boolean` - Default is `False`.
If `True` run the test in an Audit only mode which will log all errors but instead of failing the build it will set the
test as skipped. This allows visibility into the failures without breaking the build.
### IgnoreFiles
This supports package relative files, folders, and glob patterns to ignore. These are passed to the markdownlint-cli
tool as quoted `-i` parameters.
## Linter Configuration
All configuration options available to the linter can be set in `.markdownlint.yaml`. This includes customizing
rule options and enforcement.
- Markdownlint configuration options: <https://github.com/DavidAnson/markdownlint#configuration>
- Linter rules: <https://github.com/DavidAnson/markdownlint/blob/main/doc/Rules.md>
## Rule Overrides
There are times when a certain rule should not apply to part of a markdown file. Markdownlint has numerous ways
to configure this. See the in-file configuration options described in the links above.

View file

@ -6,9 +6,9 @@
##
{
"version": "0.1",
"language": "en",
"language": "en,en-GB",
"dictionaries": [
"companies ",
"companies",
"softwareTerms",
"python",
"cpp"

View file

@ -13,7 +13,7 @@ By default, an Uncrustify configuration file named "uncrustify.cfg" located in t
used. The value can be overridden to a package-specific path with the `ConfigFilePath` configuration file option.
* Uncrustify source code and documentation: https://github.com/uncrustify/uncrustify
* Project Mu Uncrustify fork source code and documentation: https://dev.azure.com/projectmu/Uncrustify
* TianoCore Uncrustify fork source code and documentation: https://github.com/tianocore/uncrustify
## Files Checked in a Package

View file

@ -22,9 +22,10 @@ from edk2toolext.environment.var_dict import VarDict
from edk2toollib.gitignore_parser import parse_gitignore_lines
from edk2toollib.log.junit_report_format import JunitReportTestCase
from edk2toollib.uefi.edk2.path_utilities import Edk2Path
from edk2toollib.utility_functions import RunCmd
from edk2toollib.utility_functions import RunCmd
from io import StringIO
from typing import Any, Dict, List, Tuple
from typing import Any, Dict, List, Optional, Tuple
#
# Provide more user friendly messages for certain scenarios
@ -59,19 +60,11 @@ class UncrustifyInputFileCreationErrorException(UncrustifyException):
def __init__(self, message):
super().__init__(message, -121)
class UncrustifyInvalidIgnoreStandardPathsException(UncrustifyException):
def __init__(self, message):
super().__init__(message, -122)
class UncrustifyGitIgnoreFileException(UncrustifyException):
def __init__(self, message):
super().__init__(message, -140)
class UncrustifyGitSubmoduleException(UncrustifyException):
def __init__(self, message):
super().__init__(message, -141)
class UncrustifyCheck(ICiBuildPlugin):
"""
@ -100,7 +93,8 @@ class UncrustifyCheck(ICiBuildPlugin):
# Note: Values specified via "ConfigFilePath" are relative to the package
#
DEFAULT_CONFIG_FILE_PATH = os.path.join(
pathlib.Path(__file__).parent.resolve(), "uncrustify.cfg")
pathlib.Path(__file__).parent.resolve(), "uncrustify.cfg"
)
#
# The extension used for formatted files produced by this plugin
@ -119,20 +113,33 @@ class UncrustifyCheck(ICiBuildPlugin):
UNCRUSTIFY_PATH_ENV_KEY = "UNCRUSTIFY_CI_PATH"
def GetTestName(self, packagename: str, environment: VarDict) -> Tuple:
""" Provide the testcase name and classname for use in reporting
"""Provide the testcase name and classname for use in reporting
Args:
packagename: string containing name of package to build
environment: The VarDict for the test to run in
Returns:
A tuple containing the testcase name and the classname
(testcasename, classname)
testclassname: a descriptive string for the testcase can include whitespace
classname: should be patterned <packagename>.<plugin>.<optionally any unique condition>
Args:
packagename: string containing name of package to build
environment: The VarDict for the test to run in
Returns:
A tuple containing the testcase name and the classname
(testcasename, classname)
testclassname: a descriptive string for the testcase can include whitespace
classname: should be patterned <packagename>.<plugin>.<optionally any unique condition>
"""
return ("Check file coding standard compliance in " + packagename, packagename + ".UncrustifyCheck")
return (
"Check file coding standard compliance in " + packagename,
packagename + ".UncrustifyCheck",
)
def RunBuildPlugin(self, package_rel_path: str, edk2_path: Edk2Path, package_config: Dict[str, List[str]], environment_config: Any, plugin_manager: PluginManager, plugin_manager_helper: HelperFunctions, tc: JunitReportTestCase, output_stream=None) -> int:
def RunBuildPlugin(
self,
package_rel_path: str,
edk2_path: Edk2Path,
package_config: Dict[str, List[str]],
environment_config: Any,
plugin_manager: PluginManager,
plugin_manager_helper: HelperFunctions,
tc: JunitReportTestCase,
output_stream=None,
) -> int:
"""
External function of plugin. This function is used to perform the task of the CiBuild Plugin.
@ -155,7 +162,8 @@ class UncrustifyCheck(ICiBuildPlugin):
# Initialize plugin and check pre-requisites.
self._env = environment_config
self._initialize_environment_info(
package_rel_path, edk2_path, package_config, tc)
package_rel_path, edk2_path, package_config, tc
)
self._initialize_configuration()
self._check_for_preexisting_formatted_files()
@ -176,20 +184,21 @@ class UncrustifyCheck(ICiBuildPlugin):
except UncrustifyException as e:
self._tc.LogStdError(
f"Uncrustify error {e.exit_code}. Details:\n\n{str(e)}")
logging.warning(
f"Uncrustify error {e.exit_code}. Details:\n\n{str(e)}")
f"Uncrustify error {e.exit_code}. Details:\n\n{str(e)}"
)
logging.warning(f"Uncrustify error {e.exit_code}. Details:\n\n{str(e)}")
return -1
else:
if self._formatted_file_error_count > 0:
if self._audit_only_mode:
logging.info(
"Setting test as skipped since AuditOnly is enabled")
logging.info("Setting test as skipped since AuditOnly is enabled")
self._tc.SetSkipped()
return -1
else:
self._tc.SetFailed(
f"{self._plugin_name} failed due to {self._formatted_file_error_count} incorrectly formatted files.", "CHECK_FAILED")
f"{self._plugin_name} failed due to {self._formatted_file_error_count} incorrectly formatted files.",
"CHECK_FAILED",
)
else:
self._tc.SetSuccess()
return self._formatted_file_error_count
@ -214,11 +223,18 @@ class UncrustifyCheck(ICiBuildPlugin):
from an error that occurred during a previous run or a premature exit from a debug scenario. In any case, the package should be clean before starting a new run.
"""
pre_existing_formatted_file_count = len(
[str(path.resolve()) for path in pathlib.Path(self._abs_package_path).rglob(f'*{UncrustifyCheck.FORMATTED_FILE_EXTENSION}')])
[
str(path.resolve())
for path in pathlib.Path(self._abs_package_path).rglob(
f"*{UncrustifyCheck.FORMATTED_FILE_EXTENSION}"
)
]
)
if pre_existing_formatted_file_count > 0:
raise UncrustifyStalePluginFormattedFilesException(
f"{pre_existing_formatted_file_count} formatted files already exist. To prevent overwriting these files, please remove them before running this plugin.")
f"{pre_existing_formatted_file_count} formatted files already exist. To prevent overwriting these files, please remove them before running this plugin."
)
def _cleanup_temporary_directory(self) -> None:
"""
@ -226,7 +242,7 @@ class UncrustifyCheck(ICiBuildPlugin):
This removes the directory and all files created during this instance.
"""
if hasattr(self, '_working_dir'):
if hasattr(self, "_working_dir"):
self._remove_tree(self._working_dir)
def _cleanup_temporary_formatted_files(self) -> None:
@ -236,9 +252,13 @@ class UncrustifyCheck(ICiBuildPlugin):
This will recursively remove all formatted files generated by Uncrustify
during this execution instance.
"""
if hasattr(self, '_abs_package_path'):
formatted_files = [str(path.resolve()) for path in pathlib.Path(
self._abs_package_path).rglob(f'*{UncrustifyCheck.FORMATTED_FILE_EXTENSION}')]
if hasattr(self, "_abs_package_path"):
formatted_files = [
str(path.resolve())
for path in pathlib.Path(self._abs_package_path).rglob(
f"*{UncrustifyCheck.FORMATTED_FILE_EXTENSION}"
)
]
for formatted_file in formatted_files:
os.remove(formatted_file)
@ -248,22 +268,29 @@ class UncrustifyCheck(ICiBuildPlugin):
Creates the temporary directory used for this execution instance.
"""
self._working_dir = os.path.join(
self._abs_workspace_path, "Build", ".pytool", "Plugin", f"{self._plugin_name}")
self._abs_workspace_path,
"Build",
".pytool",
"Plugin",
f"{self._plugin_name}",
)
try:
pathlib.Path(self._working_dir).mkdir(parents=True, exist_ok=True)
except OSError as e:
raise UncrustifyInputFileCreationErrorException(
f"Error creating plugin directory {self._working_dir}.\n\n{repr(e)}.")
f"Error creating plugin directory {self._working_dir}.\n\n{repr(e)}."
)
def _create_uncrustify_file_list_file(self) -> None:
"""
Creates the file with the list of source files for Uncrustify to process.
"""
self._app_input_file_path = os.path.join(
self._working_dir, "uncrustify_file_list.txt")
self._working_dir, "uncrustify_file_list.txt"
)
with open(self._app_input_file_path, 'w', encoding='utf8') as f:
with open(self._app_input_file_path, "w", encoding="utf8") as f:
f.writelines(f"\n".join(self._abs_file_paths_to_format))
def _execute_uncrustify(self) -> None:
@ -271,21 +298,18 @@ class UncrustifyCheck(ICiBuildPlugin):
Executes Uncrustify with the initialized configuration.
"""
output = StringIO()
params = ['-c', self._app_config_file]
params += ['-F', self._app_input_file_path]
params += ['--if-changed']
params = ["-c", self._app_config_file]
params += ["-F", self._app_input_file_path]
params += ["--if-changed"]
if self._env.GetValue("UNCRUSTIFY_IN_PLACE", "FALSE") == "TRUE":
params += ['--replace', '--no-backup']
params += ["--replace", "--no-backup"]
else:
params += ['--suffix', UncrustifyCheck.FORMATTED_FILE_EXTENSION]
self._app_exit_code = RunCmd(
self._app_path,
" ".join(params),
outstream=output)
params += ["--suffix", UncrustifyCheck.FORMATTED_FILE_EXTENSION]
self._app_exit_code = RunCmd(self._app_path, " ".join(params), outstream=output)
self._app_output = output.getvalue().strip().splitlines()
def _get_files_ignored_in_config(self):
""""
""" "
Returns a function that returns true if a given file string path is ignored in the plugin configuration file and false otherwise.
"""
ignored_files = []
@ -300,59 +324,111 @@ class UncrustifyCheck(ICiBuildPlugin):
# This information is only used for reporting (not used here) and
# the ignore lines are being passed directly as they are given to
# this plugin.
return parse_gitignore_lines(ignored_files, "Package configuration file", self._abs_package_path)
return parse_gitignore_lines(
ignored_files, "Package configuration file", self._abs_package_path
)
def _get_git_ignored_paths(self) -> List[str]:
""""
"""
Returns a list of file absolute path strings to all files ignored in this git repository.
If git is not found, an empty list will be returned.
If the package's git repository could not be determined, or the command otherwise
fails, an empty list is returned instead.
"""
if not shutil.which("git"):
logging.warning(
"Git is not found on this system. Git submodule paths will not be considered.")
if self._abs_git_repo_path is None:
return []
outstream_buffer = StringIO()
exit_code = RunCmd("git", "ls-files --other",
workingdir=self._abs_workspace_path, outstream=outstream_buffer, logging_level=logging.NOTSET)
if (exit_code != 0):
raise UncrustifyGitIgnoreFileException(
f"An error occurred reading git ignore settings. This will prevent Uncrustify from running against the expected set of files.")
exit_code = RunCmd(
"git",
"ls-files --other",
workingdir=self._abs_git_repo_path,
outstream=outstream_buffer,
logging_level=logging.NOTSET,
)
if exit_code != 0:
logging.warning(
"An error occurred reading git ignore settings. Git ignored paths will not be considered."
)
return []
# Note: This will potentially be a large list, but at least sorted
rel_paths = outstream_buffer.getvalue().strip().splitlines()
abs_paths = []
for path in rel_paths:
abs_paths.append(
os.path.normpath(os.path.join(self._abs_workspace_path, path)))
os.path.normpath(os.path.join(self._abs_git_repo_path, path))
)
return abs_paths
def _get_git_submodule_paths(self) -> List[str]:
def _get_git_repo_path(self) -> Optional[str]:
"""
Returns a list of directory absolute path strings to the root of each submodule in the workspace repository.
Returns the absolute path to the root of the git repository that contains the package
currently being checked. This is not necessarily the edk2 repository, since the package
may belong to a different repository combined into the workspace (e.g. via
PACKAGES_PATH).
If git is not found, an empty list will be returned.
Returns None if git is not found or the package is not within a git workspace.
"""
if not shutil.which("git"):
logging.warning(
"Git is not found on this system. Git submodule paths will not be considered.")
"Git is not found on this system. Git exclusions will not be considered."
)
return None
outstream_buffer = StringIO()
exit_code = RunCmd(
"git",
"rev-parse --show-toplevel",
workingdir=self._abs_package_path,
outstream=outstream_buffer,
logging_level=logging.NOTSET,
)
if exit_code != 0:
logging.warning(
f"{self._package_name} does not appear to be in a git workspace. Git exclusions will not be considered."
)
return None
return os.path.normpath(outstream_buffer.getvalue().strip())
def _get_git_submodule_paths(self) -> List[str]:
"""
Returns a list of directory absolute path strings to the root of each submodule in the
package's git repository.
If the package's git repository could not be determined, there is no .gitmodules file,
or the command otherwise fails, an empty list is returned instead.
"""
if self._abs_git_repo_path is None:
return []
if os.path.isfile(os.path.join(self._abs_workspace_path, ".gitmodules")):
if os.path.isfile(os.path.join(self._abs_git_repo_path, ".gitmodules")):
logging.info(
f".gitmodules file found. Excluding submodules in {self._package_name}.")
f".gitmodules file found. Excluding submodules in {self._package_name}."
)
outstream_buffer = StringIO()
exit_code = RunCmd("git", "config --file .gitmodules --get-regexp path", workingdir=self._abs_workspace_path, outstream=outstream_buffer, logging_level=logging.NOTSET)
if (exit_code != 0):
raise UncrustifyGitSubmoduleException(
f".gitmodule file detected but an error occurred reading the file. Cannot proceed with unknown submodule paths.")
exit_code = RunCmd(
"git",
"config --file .gitmodules --get-regexp path",
workingdir=self._abs_git_repo_path,
outstream=outstream_buffer,
logging_level=logging.NOTSET,
)
if exit_code != 0:
logging.warning(
".gitmodules file detected but an error occurred reading it. Git submodule paths will not be considered."
)
return []
submodule_paths = []
for line in outstream_buffer.getvalue().strip().splitlines():
submodule_paths.append(
os.path.normpath(os.path.join(self._abs_workspace_path, line.split()[1])))
os.path.normpath(
os.path.join(self._abs_git_repo_path, line.split()[1])
)
)
return submodule_paths
else:
@ -370,7 +446,7 @@ class UncrustifyCheck(ICiBuildPlugin):
# Allow no value to allow "set" statements in the config file which do
# not specify value assignment
parser = configparser.ConfigParser(allow_no_value=True)
with open(self._app_config_file, 'r') as cf:
with open(self._app_config_file, "r") as cf:
parser.read_string("[dummy_section]\n" + cf.read())
try:
@ -379,7 +455,9 @@ class UncrustifyCheck(ICiBuildPlugin):
file_template_path = pathlib.Path(file_template_name)
if not file_template_path.is_file():
file_template_path = pathlib.Path(os.path.join(self._plugin_path, file_template_name))
file_template_path = pathlib.Path(
os.path.join(self._plugin_path, file_template_name)
)
self._file_template_contents = file_template_path.read_text()
except KeyError:
logging.info("A file header template is not specified in the config file.")
@ -391,10 +469,14 @@ class UncrustifyCheck(ICiBuildPlugin):
func_template_path = pathlib.Path(func_template_name)
if not func_template_path.is_file():
func_template_path = pathlib.Path(os.path.join(self._plugin_path, func_template_name))
func_template_path = pathlib.Path(
os.path.join(self._plugin_path, func_template_name)
)
self._func_template_contents = func_template_path.read_text()
except KeyError:
logging.info("A function header template is not specified in the config file.")
logging.info(
"A function header template is not specified in the config file."
)
except FileNotFoundError:
logging.info("The specified function header template file was not found.")
@ -407,32 +489,39 @@ class UncrustifyCheck(ICiBuildPlugin):
# Verify Uncrustify is specified in the environment.
if UncrustifyCheck.UNCRUSTIFY_PATH_ENV_KEY not in os.environ:
raise UncrustifyAppEnvVarNotFoundException(
f"Uncrustify environment variable {UncrustifyCheck.UNCRUSTIFY_PATH_ENV_KEY} is not present.")
f"Uncrustify environment variable {UncrustifyCheck.UNCRUSTIFY_PATH_ENV_KEY} is not present."
)
self._app_path = shutil.which('uncrustify', path=os.environ[UncrustifyCheck.UNCRUSTIFY_PATH_ENV_KEY])
self._app_path = shutil.which(
"uncrustify", path=os.environ[UncrustifyCheck.UNCRUSTIFY_PATH_ENV_KEY]
)
if self._app_path is None:
raise FileNotFoundError(
errno.ENOENT, os.strerror(errno.ENOENT), self._app_path)
errno.ENOENT, os.strerror(errno.ENOENT), self._app_path
)
self._app_path = os.path.normcase(os.path.normpath(self._app_path))
if not os.path.isfile(self._app_path):
raise FileNotFoundError(
errno.ENOENT, os.strerror(errno.ENOENT), self._app_path)
errno.ENOENT, os.strerror(errno.ENOENT), self._app_path
)
# Verify Uncrustify is present at the expected path.
return_buffer = StringIO()
ret = RunCmd(self._app_path, "--version", outstream=return_buffer)
if (ret != 0):
if ret != 0:
raise UncrustifyAppVersionErrorException(
f"Error occurred executing --version: {ret}.")
f"Error occurred executing --version: {ret}."
)
# Log Uncrustify version information.
self._app_version = return_buffer.getvalue().strip()
self._tc.LogStdOut(f"Uncrustify version: {self._app_version}")
version_aggregator.GetVersionAggregator().ReportVersion(
"Uncrustify", self._app_version, version_aggregator.VersionTypes.INFO)
"Uncrustify", self._app_version, version_aggregator.VersionTypes.INFO
)
def _initialize_config_file_info(self) -> None:
"""
@ -445,22 +534,30 @@ class UncrustifyCheck(ICiBuildPlugin):
self._app_config_file = self._package_config["ConfigFilePath"].strip()
self._app_config_file = os.path.normpath(
os.path.join(self._abs_package_path, self._app_config_file))
os.path.join(self._abs_package_path, self._app_config_file)
)
if not os.path.isfile(self._app_config_file):
raise FileNotFoundError(
errno.ENOENT, os.strerror(errno.ENOENT), self._app_config_file)
errno.ENOENT, os.strerror(errno.ENOENT), self._app_config_file
)
def _initialize_environment_info(self, package_rel_path: str, edk2_path: Edk2Path, package_config: Dict[str, List[str]], tc: JunitReportTestCase) -> None:
def _initialize_environment_info(
self,
package_rel_path: str,
edk2_path: Edk2Path,
package_config: Dict[str, List[str]],
tc: JunitReportTestCase,
) -> None:
"""
Initializes plugin environment information.
"""
self._abs_package_path = edk2_path.GetAbsolutePathOnThisSystemFromEdk2RelativePath(
package_rel_path)
self._abs_package_path = (
edk2_path.GetAbsolutePathOnThisSystemFromEdk2RelativePath(package_rel_path)
)
self._abs_workspace_path = edk2_path.WorkspacePath
self._package_config = package_config
self._package_name = os.path.basename(
os.path.normpath(package_rel_path))
self._package_name = os.path.basename(os.path.normpath(package_rel_path))
self._plugin_name = self.__class__.__name__
self._plugin_path = os.path.dirname(os.path.realpath(__file__))
self._rel_package_path = package_rel_path
@ -471,67 +568,93 @@ class UncrustifyCheck(ICiBuildPlugin):
Forms the list of source files for Uncrustify to process.
"""
# Create a list of all the package relative file paths in the package to run against Uncrustify.
rel_file_paths_to_format = list(
UncrustifyCheck.STANDARD_PLUGIN_DEFINED_PATHS)
rel_file_paths_to_format = list(UncrustifyCheck.STANDARD_PLUGIN_DEFINED_PATHS)
# Allow the ci.yaml to remove any of the pre-defined standard paths
if "IgnoreStandardPaths" in self._package_config:
for a in self._package_config["IgnoreStandardPaths"]:
if a.strip() in rel_file_paths_to_format:
self._tc.LogStdOut(
f"Ignoring standard path due to ci.yaml ignore: {a}")
f"Ignoring standard path due to ci.yaml ignore: {a}"
)
rel_file_paths_to_format.remove(a.strip())
else:
raise UncrustifyInvalidIgnoreStandardPathsException(f"Invalid IgnoreStandardPaths value: {a}")
raise UncrustifyInvalidIgnoreStandardPathsException(
f"Invalid IgnoreStandardPaths value: {a}"
)
# Allow the ci.yaml to specify additional include paths for this package
if "AdditionalIncludePaths" in self._package_config:
rel_file_paths_to_format.extend(
self._package_config["AdditionalIncludePaths"])
self._package_config["AdditionalIncludePaths"]
)
self._abs_file_paths_to_format = []
for path in rel_file_paths_to_format:
self._abs_file_paths_to_format.extend(
[str(path.resolve()) for path in pathlib.Path(self._abs_package_path).rglob(path)])
[
str(path.resolve())
for path in pathlib.Path(self._abs_package_path).rglob(path)
]
)
# Remove files ignore in the plugin configuration file
plugin_ignored_files = list(filter(self._get_files_ignored_in_config(), self._abs_file_paths_to_format))
plugin_ignored_files = list(
filter(self._get_files_ignored_in_config(), self._abs_file_paths_to_format)
)
if plugin_ignored_files:
logging.info(
f"{self._package_name} file count before plugin ignore file exclusion: {len(self._abs_file_paths_to_format)}")
f"{self._package_name} file count before plugin ignore file exclusion: {len(self._abs_file_paths_to_format)}"
)
for path in plugin_ignored_files:
if path in self._abs_file_paths_to_format:
logging.info(f" File ignored in plugin config file: {path}")
self._abs_file_paths_to_format.remove(path)
logging.info(
f"{self._package_name} file count after plugin ignore file exclusion: {len(self._abs_file_paths_to_format)}")
f"{self._package_name} file count after plugin ignore file exclusion: {len(self._abs_file_paths_to_format)}"
)
if (
not "SkipGitExclusions" in self._package_config
or not self._package_config["SkipGitExclusions"]
):
# Determine the git repository that contains this package. This is not necessarily
# the edk2 repository if the package is in a different repo (e.g. PACKAGES_PATH).
self._abs_git_repo_path = self._get_git_repo_path()
if not "SkipGitExclusions" in self._package_config or not self._package_config["SkipGitExclusions"]:
# Remove files ignored by git
logging.info(
f"{self._package_name} file count before git ignore file exclusion: {len(self._abs_file_paths_to_format)}")
f"{self._package_name} file count before git ignore file exclusion: {len(self._abs_file_paths_to_format)}"
)
ignored_paths = self._get_git_ignored_paths()
self._abs_file_paths_to_format = list(
set(self._abs_file_paths_to_format).difference(ignored_paths))
set(self._abs_file_paths_to_format).difference(ignored_paths)
)
logging.info(
f"{self._package_name} file count after git ignore file exclusion: {len(self._abs_file_paths_to_format)}")
f"{self._package_name} file count after git ignore file exclusion: {len(self._abs_file_paths_to_format)}"
)
# Remove files in submodules
logging.info(
f"{self._package_name} file count before submodule exclusion: {len(self._abs_file_paths_to_format)}")
f"{self._package_name} file count before submodule exclusion: {len(self._abs_file_paths_to_format)}"
)
submodule_paths = tuple(self._get_git_submodule_paths())
for path in submodule_paths:
logging.info(f" submodule path: {path}")
self._abs_file_paths_to_format = [
f for f in self._abs_file_paths_to_format if not f.startswith(submodule_paths)]
f
for f in self._abs_file_paths_to_format
if not f.startswith(submodule_paths)
]
logging.info(
f"{self._package_name} file count after submodule exclusion: {len(self._abs_file_paths_to_format)}")
f"{self._package_name} file count after submodule exclusion: {len(self._abs_file_paths_to_format)}"
)
# Sort the files for more consistent results
self._abs_file_paths_to_format.sort()
@ -546,7 +669,10 @@ class UncrustifyCheck(ICiBuildPlugin):
if "AuditOnly" in self._package_config and self._package_config["AuditOnly"]:
self._audit_only_mode = True
if "OutputFileDiffs" in self._package_config and not self._package_config["OutputFileDiffs"]:
if (
"OutputFileDiffs" in self._package_config
and not self._package_config["OutputFileDiffs"]
):
self._output_file_diffs = False
def _log_uncrustify_app_info(self) -> None:
@ -555,10 +681,10 @@ class UncrustifyCheck(ICiBuildPlugin):
"""
self._tc.LogStdOut(f"Found Uncrustify at {self._app_path}")
self._tc.LogStdOut(f"Uncrustify version: {self._app_version}")
self._tc.LogStdOut('\n')
self._tc.LogStdOut("\n")
logging.info(f"Found Uncrustify at {self._app_path}")
logging.info(f"Uncrustify version: {self._app_version}")
logging.info('\n')
logging.info("\n")
def _process_uncrustify_results(self) -> None:
"""
@ -566,55 +692,90 @@ class UncrustifyCheck(ICiBuildPlugin):
Determines whether formatting errors are present and logs failures.
"""
formatted_files = [str(path.resolve()) for path in pathlib.Path(
self._abs_package_path).rglob(f'*{UncrustifyCheck.FORMATTED_FILE_EXTENSION}')]
formatted_files = [
str(path.resolve())
for path in pathlib.Path(self._abs_package_path).rglob(
f"*{UncrustifyCheck.FORMATTED_FILE_EXTENSION}"
)
]
self._formatted_file_error_count = len(formatted_files)
if self._formatted_file_error_count > 0:
logging.error(f'Uncrustify found {self._formatted_file_error_count} files with formatting errors\n')
self._tc.LogStdError(f"Uncrustify found {self._formatted_file_error_count} files with formatting errors:\n")
logging.error(
f"Uncrustify found {self._formatted_file_error_count} files with formatting errors\n"
)
self._tc.LogStdError(
f"Uncrustify found {self._formatted_file_error_count} files with formatting errors:\n"
)
logging.warning(
"Visit the following instructions to learn "
"more about uncrustify setup instructions and CI:"
"https://www.tianocore.org/tianocore-wiki.github.io/development/coding-standards/edk_ii_code_formatting.html\n")
"https://www.tianocore.org/tianocore-wiki.github.io/development/coding-standards/edk_ii_code_formatting.html\n"
)
if self._output_file_diffs:
logging.info("Calculating file diffs. This might take a while...")
for formatted_file in formatted_files:
pre_formatted_file = formatted_file[:-len(UncrustifyCheck.FORMATTED_FILE_EXTENSION)]
pre_formatted_file = formatted_file[
: -len(UncrustifyCheck.FORMATTED_FILE_EXTENSION)
]
logging.error(f"Formatting errors in {os.path.relpath(pre_formatted_file, self._abs_package_path)}")
self._tc.LogStdError(f"Formatting errors in {os.path.relpath(pre_formatted_file, self._abs_package_path)}\n")
logging.error(
f"Formatting errors in {os.path.relpath(pre_formatted_file, self._abs_package_path)}"
)
self._tc.LogStdError(
f"Formatting errors in {os.path.relpath(pre_formatted_file, self._abs_package_path)}\n"
)
if (self._output_file_diffs or
self._file_template_contents is not None or
self._func_template_contents is not None):
if (
self._output_file_diffs
or self._file_template_contents is not None
or self._func_template_contents is not None
):
with open(formatted_file) as ff:
formatted_file_text = ff.read()
if (self._file_template_contents is not None and
self._file_template_contents in formatted_file_text):
logging.info(f"File header is missing in {os.path.relpath(pre_formatted_file, self._abs_package_path)}")
self._tc.LogStdError(f"File header is missing in {os.path.relpath(pre_formatted_file, self._abs_package_path)}\n")
if (
self._file_template_contents is not None
and self._file_template_contents in formatted_file_text
):
logging.info(
f"File header is missing in {os.path.relpath(pre_formatted_file, self._abs_package_path)}"
)
self._tc.LogStdError(
f"File header is missing in {os.path.relpath(pre_formatted_file, self._abs_package_path)}\n"
)
if (self._func_template_contents is not None and
self._func_template_contents in formatted_file_text):
logging.info(f"A function header is missing in {os.path.relpath(pre_formatted_file, self._abs_package_path)}")
self._tc.LogStdError(f"A function header is missing in {os.path.relpath(pre_formatted_file, self._abs_package_path)}\n")
if (
self._func_template_contents is not None
and self._func_template_contents in formatted_file_text
):
logging.info(
f"A function header is missing in {os.path.relpath(pre_formatted_file, self._abs_package_path)}"
)
self._tc.LogStdError(
f"A function header is missing in {os.path.relpath(pre_formatted_file, self._abs_package_path)}\n"
)
if self._output_file_diffs:
with open(pre_formatted_file) as pf:
pre_formatted_file_text = pf.read()
for line in difflib.unified_diff(pre_formatted_file_text.split('\n'), formatted_file_text.split('\n'), fromfile=pre_formatted_file, tofile=formatted_file, n=3):
for line in difflib.unified_diff(
pre_formatted_file_text.split("\n"),
formatted_file_text.split("\n"),
fromfile=pre_formatted_file,
tofile=formatted_file,
n=3,
):
logging.error(line)
self._tc.LogStdError(line)
logging.error('\n')
self._tc.LogStdError('\n')
logging.error("\n")
self._tc.LogStdError("\n")
def _remove_tree(self, dir_path: str, ignore_errors: bool = False) -> None:
"""
@ -644,7 +805,9 @@ class UncrustifyCheck(ICiBuildPlugin):
for _ in range(3): # retry up to 3 times
try:
shutil.rmtree(dir_path, ignore_errors=ignore_errors, onerror=_remove_readonly)
shutil.rmtree(
dir_path, ignore_errors=ignore_errors, onerror=_remove_readonly
)
except OSError as err:
logging.warning(f"Failed to fully remove {dir_path}: {err}")
else:
@ -668,4 +831,5 @@ class UncrustifyCheck(ICiBuildPlugin):
if self._app_exit_code != 0 and self._app_exit_code != 1:
raise UncrustifyAppExecutionException(
f"Error {str(self._app_exit_code)} returned from Uncrustify:\n\n{str(self._app_output)}")
f"Error {str(self._app_exit_code)} returned from Uncrustify:\n\n{str(self._app_output)}"
)

View file

@ -9,7 +9,7 @@ on the TianoCore wiki.
## Basic Status
| Package | Windows VS2022 (IA32/X64)| Ubuntu GCC (IA32/X64/AARCH64) | Known Issues |
| Package | Windows VS2026 (IA32/X64)| Ubuntu GCC (IA32/X64/AARCH64) | Known Issues |
| :---- | :----- | :---- | :--- |
| ArmPkg | | :heavy_check_mark: |
| ArmPlatformPkg | | :heavy_check_mark: |

View file

@ -241,5 +241,11 @@
],
"AdditionalIncludePaths": [] # Additional paths to spell check
# (wildcards supported)
},
## options defined .pytool/Plugin/MarkdownLintCheck
"MarkdownLintCheck": {
"AuditOnly": True, # If True, log all errors and then mark as skipped
"IgnoreFiles": [] # package root relative file, folder, or glob pattern to ignore
}
}

View file

@ -2,7 +2,7 @@
# ARM processor package.
#
# Copyright (c) 2009 - 2010, Apple Inc. All rights reserved.<BR>
# Copyright (c) 2011 - 2023, ARM Limited. All rights reserved.
# Copyright (c) 2011 - 2026, ARM Limited. All rights reserved.
# Copyright (c) 2021, Ampere Computing LLC. All rights reserved.
#
# SPDX-License-Identifier: BSD-2-Clause-Patent
@ -51,6 +51,11 @@
#
ArmMonitorLib|Include/Library/ArmMonitorLib.h
## @libraryclass Provides access to the Arm SMCCC Architecture SoC ID
# interface.
#
ArmSmcccSocIdLib|Include/Library/ArmSmcccSocIdLib.h
## @libraryclass Provides an interface to query miscellaneous OEM
# information.
#
@ -166,6 +171,7 @@
gArmTokenSpaceGuid.PcdProcessorSerialNumber|L""|VOID*|0x30000073
gArmTokenSpaceGuid.PcdProcessorAssetTag|L""|VOID*|0x30000074
gArmTokenSpaceGuid.PcdProcessorPartNumber|L""|VOID*|0x30000075
gArmTokenSpaceGuid.PcdProcessorSocketType|L""|VOID*|0x30000076
#
# ARM L2x0 PCDs

View file

@ -2,7 +2,7 @@
# ARM processor package.
#
# Copyright (c) 2009 - 2010, Apple Inc. All rights reserved.<BR>
# Copyright (c) 2011 - 2021, Arm Limited. All rights reserved.<BR>
# Copyright (c) 2011 - 2026, Arm Limited. All rights reserved.<BR>
# Copyright (c) 2016, Linaro Ltd. All rights reserved.<BR>
# Copyright (c) Microsoft Corporation.<BR>
# Copyright (c) 2021, Ampere Computing LLC. All rights reserved.
@ -37,6 +37,7 @@
!include MdePkg/MdeLibs.dsc.inc
[LibraryClasses.common]
ArmSmcccSocIdLib|ArmPkg/Library/ArmSmcccSocIdLib/ArmSmcccSocIdLib.inf
BaseLib|MdePkg/Library/BaseLib/BaseLib.inf
BaseMemoryLib|MdePkg/Library/BaseMemoryLib/BaseMemoryLib.inf
BootLogoLib|MdeModulePkg/Library/BootLogoLib/BootLogoLib.inf
@ -111,6 +112,7 @@
[Components.common]
ArmPkg/Library/ArmCacheMaintenanceLib/ArmCacheMaintenanceLib.inf
ArmPkg/Library/ArmPsciResetSystemLib/ArmPsciResetSystemLib.inf
ArmPkg/Library/ArmSmcccSocIdLib/ArmSmcccSocIdLib.inf
ArmPkg/Library/DebugAgentSymbolsBaseLib/DebugAgentSymbolsBaseLib.inf
ArmPkg/Library/DebugPeCoffExtraActionLib/DebugPeCoffExtraActionLib.inf
ArmPkg/Library/SemiHostingDebugLib/SemiHostingDebugLib.inf

View file

@ -285,10 +285,18 @@ CpuSetMemoryAttributes (
// stale cache lines are written back and invalidated. If this is not done,
// depending on the caching behavior of the platform, dirty cache lines may
// be written back corrupting data in the future, or stale cache lines may
// persist if caching is enabled later.
// persist if caching is enabled later. In scenarios where the caller didn't
// explicitly change the cacheability, ignore this. This could still lead to
// unexpected caches, but this is a necessary concession to incorrect behavior
// in higher-level components.
//
FlushCache = FALSE;
if (!EFI_ERROR (Status) && IsArmAttributeCacheable (RegionArmAttributes) && !IsArmAttributeCacheable (ArmAttributes)) {
if (!EFI_ERROR (Status) &&
((EfiAttributes & EFI_MEMORY_RP) == 0) &&
((EfiAttributes & EFI_MEMORY_CACHETYPE_MASK) != 0) &&
IsArmAttributeCacheable (RegionArmAttributes) &&
!IsArmAttributeCacheable (ArmAttributes))
{
FlushCache = TRUE;
}

View file

@ -29,10 +29,14 @@
#define COMM_BUFFER_ATTRS (EFI_MEMORY_WB | EFI_MEMORY_XP | EFI_MEMORY_RUNTIME)
// This an absurdly high number. The timer cannot be used reliably at runtime so having some upper bound is necessary.
// This number is chosen with back-of-the-envelope calculations where the rough time to get a BUSY response it around
// 10 microseconds, so 500,000 retries is roughly 5 seconds.
#define MAX_BUSY_RETRIES 500000
//
// Partition ID if FF-A support is enabled
//
STATIC UINT16 mPartId;
STATIC UINT16 mStMmPartId;
//
@ -65,20 +69,35 @@ SendFfaMmCommunicate (
{
EFI_STATUS Status;
DIRECT_MSG_ARGS CommunicateArgs;
UINT64 Retries;
ZeroMem (&CommunicateArgs, sizeof (DIRECT_MSG_ARGS));
Retries = 0;
while (TRUE) {
ZeroMem (&CommunicateArgs, sizeof (DIRECT_MSG_ARGS));
CommunicateArgs.Arg0 = (UINTN)mNsCommBuffMemRegion.PhysicalBase;
CommunicateArgs.Arg0 = (UINTN)mNsCommBuffMemRegion.PhysicalBase;
Status = ArmFfaLibMsgSendDirectReq (
mStMmPartId,
0,
&CommunicateArgs
);
Status = ArmFfaLibMsgSendDirectReq (
mStMmPartId,
0,
&CommunicateArgs
);
if (Status == EFI_NO_RESPONSE) {
// Only try for so long before just failing.
if (Retries >= MAX_BUSY_RETRIES) {
return EFI_TIMEOUT;
}
Retries++;
continue;
}
break;
}
while (Status == EFI_INTERRUPT_PENDING) {
// We are assuming vCPU0 of the StMM SP since it is UP.
Status = ArmFfaLibRun (mStMmPartId, 0x00, NULL);
Status = ArmFfaLibRun (GET_SOURCE_PARTITION_ID (CommunicateArgs.Header.x1), 0x00, &CommunicateArgs);
}
return Status;
@ -549,16 +568,6 @@ InitializeFfaCommunication (
EFI_STATUS Status;
EFI_FFA_PART_INFO_DESC StmmPartInfo;
Status = ArmFfaLibPartitionIdGet (&mPartId);
if (EFI_ERROR (Status)) {
DEBUG ((
DEBUG_ERROR,
"Failed to get partition id. Status: %r\n",
Status
));
return Status;
}
Status = ArmFfaLibGetPartitionInfo (&gEfiMmCommunication2ProtocolGuid, &StmmPartInfo);
if (EFI_ERROR (Status)) {
DEBUG ((

View file

@ -26,7 +26,6 @@
//
// Partition ID if FF-A support is enabled
//
STATIC UINT16 mPartId;
STATIC UINT16 mStMmPartId;
/**
@ -139,16 +138,6 @@ InitializeFfaCommunication (
EFI_STATUS Status;
EFI_FFA_PART_INFO_DESC StmmPartInfo;
Status = ArmFfaLibPartitionIdGet (&mPartId);
if (EFI_ERROR (Status)) {
DEBUG ((
DEBUG_ERROR,
"Failed to get partition id. Status: %r\n",
Status
));
return Status;
}
Status = ArmFfaLibGetPartitionInfo (&gEfiMmCommunication2ProtocolGuid, &StmmPartInfo);
if (EFI_ERROR (Status)) {
DEBUG ((
@ -163,14 +152,12 @@ InitializeFfaCommunication (
if ((StmmPartInfo.PartitionProps & FFA_PART_PROP_RECV_DIRECT_REQ) == 0x00) {
Status = EFI_UNSUPPORTED;
DEBUG ((DEBUG_ERROR, "StandaloneMm doesn't receive DIRECT_MSG_REQ...\n"));
goto ErrorHandler;
return Status;
}
mStMmPartId = StmmPartInfo.PartitionId;
ErrorHandler:
ArmFfaLibRxRelease (mPartId);
return Status;
return EFI_SUCCESS;
}
/**
@ -230,7 +217,7 @@ SendFfaMmCommunicate (
while (Status == EFI_INTERRUPT_PENDING) {
// We are assuming vCPU0 of the StMM SP since it is UP.
Status = ArmFfaLibRun (mStMmPartId, 0x00, NULL);
Status = ArmFfaLibRun (GET_SOURCE_PARTITION_ID (CommunicateArgs.Header.x1), 0x00, &CommunicateArgs);
}
return Status;

View file

@ -0,0 +1,39 @@
/** @file
Arm SMCCC SoC ID library.
Copyright (c) 2026, Arm Limited. All rights reserved.<BR>
SPDX-License-Identifier: BSD-2-Clause-Patent
**/
#pragma once
/**
Check whether the SMCCC Architecture SoC ID interface is supported.
@retval TRUE The SMCCC Architecture SoC ID interface is supported.
@retval FALSE The SMCCC Architecture SoC ID interface is not supported.
**/
BOOLEAN
ArmSmcccSocIdIsSupported (
VOID
);
/**
Get the JEP106 identification code and SoC revision using the SMCCC
Architecture SoC ID interface.
@param[out] Jep106Code Pointer to the JEP106 identification code.
@param[out] SocRevision Pointer to the SoC revision.
@retval EFI_SUCCESS The SoC identification information was
returned successfully.
@retval EFI_INVALID_PARAMETER A required output parameter is NULL.
@retval EFI_UNSUPPORTED The SMCCC Architecture SoC ID interface is
unsupported or an SoC ID call failed.
**/
EFI_STATUS
ArmSmcccGetSocId (
OUT UINT32 *Jep106Code,
OUT UINT32 *SocRevision
);

View file

@ -58,13 +58,13 @@ typedef struct ServiceTableEntry {
*/
typedef struct {
/// Service guid
EFI_GUID HeaderGuid;
EFI_GUID HeaderGuid;
/// Length of Message. In case of misc service, sizeof (EventSvcArgs)
UINTN MessageLength;
UINTN MessageLength;
/// Delivered register values.
DIRECT_MSG_ARGS DirectMsgArgs;
ARM_FFA_ARGS FfaArgs;
} MISC_MM_COMMUNICATE_BUFFER;
typedef struct {

View file

@ -60,6 +60,7 @@ typedef enum {
ProcessorPartNumType04,
ProcessorSerialNumType04,
ProcessorVersionType04,
ProcessorSocketTypeType04,
SmbiosHiiStringFieldMax
} OEM_MISC_SMBIOS_HII_STRING_FIELD;

View file

@ -0,0 +1,110 @@
/** @file
Arm SMCCC SoC ID library.
Copyright (c) 2021, NUVIA Inc. All rights reserved.<BR>
Copyright (c) 2021 - 2022, Ampere Computing LLC. All rights reserved.<BR>
Copyright (c) 2026, Arm Limited. All rights reserved.<BR>
SPDX-License-Identifier: BSD-2-Clause-Patent
**/
#include <Uefi.h>
#include <IndustryStandard/ArmStdSmc.h>
#include <Library/ArmSmcLib.h>
#include <Library/ArmSmcccSocIdLib.h>
/**
Check whether the SMCCC Architecture SoC ID interface is supported.
@retval TRUE The SMCCC Architecture SoC ID interface is supported.
@retval FALSE The SMCCC Architecture SoC ID interface is not supported.
**/
BOOLEAN
ArmSmcccSocIdIsSupported (
VOID
)
{
INT32 SmcCallStatus;
UINTN SmcParameter;
SmcCallStatus = ArmCallSmc0 (SMCCC_VERSION, NULL, NULL, NULL);
if ((SmcCallStatus >= 0) && ((SmcCallStatus >> 16) < 1)) {
return FALSE;
}
SmcParameter = SMCCC_ARCH_SOC_ID;
SmcCallStatus = ArmCallSmc1 (
SMCCC_ARCH_FEATURES,
&SmcParameter,
NULL,
NULL
);
return (SmcCallStatus >= 0);
}
/**
Get the JEP106 identification code and SoC revision using the SMCCC
Architecture SoC ID interface.
@param[out] Jep106Code Pointer to the JEP106 identification code.
@param[out] SocRevision Pointer to the SoC revision.
@retval EFI_SUCCESS The SoC identification information was
returned successfully.
@retval EFI_INVALID_PARAMETER A required output parameter is NULL.
@retval EFI_UNSUPPORTED The SMCCC Architecture SoC ID interface is
unsupported or an SoC ID call failed.
**/
EFI_STATUS
ArmSmcccGetSocId (
OUT UINT32 *Jep106Code,
OUT UINT32 *SocRevision
)
{
INT32 SmcCallStatus;
UINTN SmcParameter;
UINT32 LocalJep106Code;
UINT32 LocalSocRevision;
if ((Jep106Code == NULL) || (SocRevision == NULL)) {
return EFI_INVALID_PARAMETER;
}
if (!ArmSmcccSocIdIsSupported ()) {
return EFI_UNSUPPORTED;
}
SmcParameter = 0;
SmcCallStatus = ArmCallSmc1 (
SMCCC_ARCH_SOC_ID,
&SmcParameter,
NULL,
NULL
);
if (SmcCallStatus < 0) {
return EFI_UNSUPPORTED;
}
LocalJep106Code = (UINT32)SmcCallStatus;
SmcParameter = 1;
SmcCallStatus = ArmCallSmc1 (
SMCCC_ARCH_SOC_ID,
&SmcParameter,
NULL,
NULL
);
if (SmcCallStatus < 0) {
return EFI_UNSUPPORTED;
}
LocalSocRevision = (UINT32)SmcCallStatus;
*Jep106Code = LocalJep106Code;
*SocRevision = LocalSocRevision;
return EFI_SUCCESS;
}

View file

@ -0,0 +1,25 @@
## @file
# Arm SMCCC SoC ID library.
#
# Copyright (c) 2026, Arm Limited. All rights reserved.<BR>
#
# SPDX-License-Identifier: BSD-2-Clause-Patent
##
[Defines]
INF_VERSION = 1.30
BASE_NAME = ArmSmcccSocIdLib
FILE_GUID = 06525cc6-5a4d-4465-be65-186e2e587b1d
MODULE_TYPE = BASE
VERSION_STRING = 1.0
LIBRARY_CLASS = ArmSmcccSocIdLib
[Sources]
ArmSmcccSocIdLib.c
[Packages]
ArmPkg/ArmPkg.dec
MdePkg/MdePkg.dec
[LibraryClasses]
ArmSmcLib

View file

@ -780,20 +780,20 @@ SetEventCompleteSvcArgs (
EventCompleteSvcArgs->Arg0 = ARM_FID_FFA_MSG_SEND_DIRECT_RESP2;
if (FfaMsgInfo->ServiceType == ServiceTypeMisc) {
EventCompleteSvcArgs->Arg4 = mMiscMmCommunicateBuffer->DirectMsgArgs.Arg0;
EventCompleteSvcArgs->Arg5 = mMiscMmCommunicateBuffer->DirectMsgArgs.Arg1;
EventCompleteSvcArgs->Arg6 = mMiscMmCommunicateBuffer->DirectMsgArgs.Arg2;
EventCompleteSvcArgs->Arg7 = mMiscMmCommunicateBuffer->DirectMsgArgs.Arg3;
EventCompleteSvcArgs->Arg8 = mMiscMmCommunicateBuffer->DirectMsgArgs.Arg4;
EventCompleteSvcArgs->Arg9 = mMiscMmCommunicateBuffer->DirectMsgArgs.Arg5;
EventCompleteSvcArgs->Arg10 = mMiscMmCommunicateBuffer->DirectMsgArgs.Arg6;
EventCompleteSvcArgs->Arg11 = mMiscMmCommunicateBuffer->DirectMsgArgs.Arg7;
EventCompleteSvcArgs->Arg12 = mMiscMmCommunicateBuffer->DirectMsgArgs.Arg8;
EventCompleteSvcArgs->Arg13 = mMiscMmCommunicateBuffer->DirectMsgArgs.Arg9;
EventCompleteSvcArgs->Arg14 = mMiscMmCommunicateBuffer->DirectMsgArgs.Arg10;
EventCompleteSvcArgs->Arg15 = mMiscMmCommunicateBuffer->DirectMsgArgs.Arg11;
EventCompleteSvcArgs->Arg16 = mMiscMmCommunicateBuffer->DirectMsgArgs.Arg12;
EventCompleteSvcArgs->Arg17 = mMiscMmCommunicateBuffer->DirectMsgArgs.Arg13;
EventCompleteSvcArgs->Arg4 = mMiscMmCommunicateBuffer->FfaArgs.Arg4;
EventCompleteSvcArgs->Arg5 = mMiscMmCommunicateBuffer->FfaArgs.Arg5;
EventCompleteSvcArgs->Arg6 = mMiscMmCommunicateBuffer->FfaArgs.Arg6;
EventCompleteSvcArgs->Arg7 = mMiscMmCommunicateBuffer->FfaArgs.Arg7;
EventCompleteSvcArgs->Arg8 = mMiscMmCommunicateBuffer->FfaArgs.Arg8;
EventCompleteSvcArgs->Arg9 = mMiscMmCommunicateBuffer->FfaArgs.Arg9;
EventCompleteSvcArgs->Arg10 = mMiscMmCommunicateBuffer->FfaArgs.Arg10;
EventCompleteSvcArgs->Arg11 = mMiscMmCommunicateBuffer->FfaArgs.Arg11;
EventCompleteSvcArgs->Arg12 = mMiscMmCommunicateBuffer->FfaArgs.Arg12;
EventCompleteSvcArgs->Arg13 = mMiscMmCommunicateBuffer->FfaArgs.Arg13;
EventCompleteSvcArgs->Arg14 = mMiscMmCommunicateBuffer->FfaArgs.Arg14;
EventCompleteSvcArgs->Arg15 = mMiscMmCommunicateBuffer->FfaArgs.Arg15;
EventCompleteSvcArgs->Arg16 = mMiscMmCommunicateBuffer->FfaArgs.Arg16;
EventCompleteSvcArgs->Arg17 = mMiscMmCommunicateBuffer->FfaArgs.Arg17;
}
}
@ -831,21 +831,9 @@ InitializeMiscMmCommunicateBuffer (
{
ZeroMem (Buffer, sizeof (MISC_MM_COMMUNICATE_BUFFER));
Buffer->MessageLength = sizeof (DIRECT_MSG_ARGS);
Buffer->DirectMsgArgs.Arg0 = EventSvcArgs->Arg4;
Buffer->DirectMsgArgs.Arg1 = EventSvcArgs->Arg5;
Buffer->DirectMsgArgs.Arg2 = EventSvcArgs->Arg6;
Buffer->DirectMsgArgs.Arg3 = EventSvcArgs->Arg7;
Buffer->DirectMsgArgs.Arg4 = EventSvcArgs->Arg8;
Buffer->DirectMsgArgs.Arg5 = EventSvcArgs->Arg9;
Buffer->DirectMsgArgs.Arg6 = EventSvcArgs->Arg10;
Buffer->DirectMsgArgs.Arg7 = EventSvcArgs->Arg11;
Buffer->DirectMsgArgs.Arg8 = EventSvcArgs->Arg12;
Buffer->DirectMsgArgs.Arg9 = EventSvcArgs->Arg13;
Buffer->DirectMsgArgs.Arg10 = EventSvcArgs->Arg14;
Buffer->DirectMsgArgs.Arg11 = EventSvcArgs->Arg15;
Buffer->DirectMsgArgs.Arg12 = EventSvcArgs->Arg16;
Buffer->DirectMsgArgs.Arg13 = EventSvcArgs->Arg17;
Buffer->MessageLength = sizeof (DIRECT_MSG_ARGS);
CopyMem (&Buffer->FfaArgs, EventSvcArgs, sizeof (ARM_FFA_ARGS));
CopyGuid (&Buffer->HeaderGuid, ServiceGuid);
}

View file

@ -12,10 +12,8 @@
#include <Uefi.h>
#include <Protocol/Smbios.h>
#include <IndustryStandard/ArmCache.h>
#include <IndustryStandard/ArmStdSmc.h>
#include <IndustryStandard/SmBios.h>
#include <Library/ArmLib.h>
#include <Library/ArmSmcLib.h>
#include <Library/BaseLib.h>
#include <Library/BaseMemoryLib.h>
#include <Library/DebugLib.h>
@ -104,7 +102,9 @@ SMBIOS_TABLE_TYPE4 mSmbiosProcessorTableTemplate = {
ProcessorFamilyARM, // ProcessorFamily2
0, // CoreCount2
0, // EnabledCoreCount2
0 // ThreadCount2
0, // ThreadCount2
0, // ThreadEnabled
7 // SocketType
};
/** Sets the HII variable `StringId` is `Pcd` isn't empty.
@ -495,12 +495,14 @@ AllocateType4AndSetProcessorInformationStrings (
EFI_STRING_ID SerialNumber;
EFI_STRING_ID AssetTag;
EFI_STRING_ID PartNumber;
EFI_STRING_ID SocketType;
EFI_STRING ProcessorStr;
EFI_STRING ProcessorManuStr;
EFI_STRING ProcessorVersionStr;
EFI_STRING SerialNumberStr;
EFI_STRING AssetTagStr;
EFI_STRING PartNumberStr;
EFI_STRING SocketTypeStr;
CHAR8 *OptionalStrStart;
CHAR8 *StrStart;
UINTN ProcessorStrLen;
@ -509,6 +511,7 @@ AllocateType4AndSetProcessorInformationStrings (
UINTN SerialNumberStrLen;
UINTN AssetTagStrLen;
UINTN PartNumberStrLen;
UINTN SocketTypeStrLen;
UINTN TotalSize;
UINTN StringBufferSize;
@ -519,12 +522,14 @@ AllocateType4AndSetProcessorInformationStrings (
SerialNumberStr = NULL;
AssetTagStr = NULL;
PartNumberStr = NULL;
SocketTypeStr = NULL;
ProcessorManu = STRING_TOKEN (STR_PROCESSOR_MANUFACTURE);
ProcessorVersion = STRING_TOKEN (STR_PROCESSOR_VERSION);
SerialNumber = STRING_TOKEN (STR_PROCESSOR_SERIAL_NUMBER);
AssetTag = STRING_TOKEN (STR_PROCESSOR_ASSET_TAG);
PartNumber = STRING_TOKEN (STR_PROCESSOR_PART_NUMBER);
SocketType = STRING_TOKEN (STR_PROCESSOR_SOCKET_TYPE);
SET_HII_STRING_IF_PCD_NOT_EMPTY (PcdProcessorManufacturer, ProcessorManu);
SET_HII_STRING_IF_PCD_NOT_EMPTY (PcdProcessorAssetTag, AssetTag);
@ -547,6 +552,12 @@ AllocateType4AndSetProcessorInformationStrings (
OemUpdateSmbiosInfo (mHiiHandle, ProcessorVersion, ProcessorVersionType04);
}
if (StrLen ((CHAR16 *)FixedPcdGetPtr (PcdProcessorSocketType)) > 0) {
HiiSetString (mHiiHandle, SocketType, (CHAR16 *)FixedPcdGetPtr (PcdProcessorSocketType), NULL);
} else {
OemUpdateSmbiosInfo (mHiiHandle, SocketType, ProcessorSocketTypeType04);
}
// Processor Designation
StringBufferSize = sizeof (CHAR16) * SMBIOS_STRING_MAX_LENGTH;
ProcessorStr = AllocateZeroPool (StringBufferSize);
@ -581,13 +592,17 @@ AllocateType4AndSetProcessorInformationStrings (
PartNumberStr = HiiGetPackageString (&gEfiCallerIdGuid, PartNumber, NULL);
PartNumberStrLen = StrLen (PartNumberStr);
SocketTypeStr = HiiGetPackageString (&gEfiCallerIdGuid, SocketType, NULL);
SocketTypeStrLen = StrLen (SocketTypeStr);
TotalSize = sizeof (SMBIOS_TABLE_TYPE4) +
ProcessorStrLen + 1 +
ProcessorManuStrLen + 1 +
ProcessorVersionStrLen + 1 +
SerialNumberStrLen + 1 +
AssetTagStrLen + 1 +
PartNumberStrLen + 1 + 1;
PartNumberStrLen + 1 +
SocketTypeStrLen + 1 + 1;
*Type4Record = AllocateZeroPool (TotalSize);
if (*Type4Record == NULL) {
@ -639,6 +654,13 @@ AllocateType4AndSetProcessorInformationStrings (
PartNumberStrLen + 1
);
StrStart += PartNumberStrLen + 1;
UnicodeStrToAsciiStrS (
SocketTypeStr,
StrStart,
SocketTypeStrLen + 1
);
Exit:
FreePool (ProcessorStr);
FreePool (ProcessorManuStr);
@ -646,6 +668,7 @@ Exit:
FreePool (SerialNumberStr);
FreePool (AssetTagStr);
FreePool (PartNumberStr);
FreePool (SocketTypeStr);
return Status;
}

View file

@ -4,6 +4,7 @@
# Copyright (c) 2021, NUVIA Inc. All rights reserved.
# Copyright (c) 2015, Hisilicon Limited. All rights reserved.
# Copyright (c) 2015, Linaro Limited. All rights reserved.
# Copyright (c) 2026, Arm Limited. All rights reserved.<BR>
#
# SPDX-License-Identifier: BSD-2-Clause-Patent
#
@ -34,7 +35,7 @@
[LibraryClasses]
ArmLib
ArmSmcLib
ArmSmcccSocIdLib
BaseLib
BaseMemoryLib
DebugLib
@ -55,6 +56,7 @@
gArmTokenSpaceGuid.PcdProcessorSerialNumber
gArmTokenSpaceGuid.PcdProcessorAssetTag
gArmTokenSpaceGuid.PcdProcessorPartNumber
gArmTokenSpaceGuid.PcdProcessorSocketType
[Guids]

View file

@ -21,4 +21,5 @@
#string STR_PROCESSOR_SERIAL_NUMBER #language en-US "Not Specified"
#string STR_PROCESSOR_ASSET_TAG #language en-US "Not Specified"
#string STR_PROCESSOR_PART_NUMBER #language en-US "Not Specified"
#string STR_PROCESSOR_SOCKET_TYPE #language en-US "Not Specified"
#string STR_PROCESSOR_UNKNOWN #language en-US "Unknown"

View file

@ -3,6 +3,7 @@
Copyright (c) 2021, NUVIA Inc. All rights reserved.<BR>
Copyright (c) 2021 - 2022, Ampere Computing LLC. All rights reserved.<BR>
Copyright (c) 2026, Arm Limited. All rights reserved.<BR>
SPDX-License-Identifier: BSD-2-Clause-Patent
@ -10,10 +11,9 @@
#include <Uefi.h>
#include <IndustryStandard/ArmCache.h>
#include <IndustryStandard/ArmStdSmc.h>
#include <IndustryStandard/SmBios.h>
#include <Library/ArmLib.h>
#include <Library/ArmSmcLib.h>
#include <Library/ArmSmcccSocIdLib.h>
#include <Library/BaseMemoryLib.h>
#include "SmbiosProcessor.h"
@ -79,75 +79,6 @@ SmbiosProcessorHasSeparateCaches (
return SeparateCaches;
}
/** Checks if ther ARM64 SoC ID SMC call is supported
@return Whether the ARM64 SoC ID call is supported.
**/
BOOLEAN
HasSmcArm64SocId (
VOID
)
{
INT32 SmcCallStatus;
BOOLEAN Arm64SocIdSupported;
UINTN SmcParam;
Arm64SocIdSupported = FALSE;
SmcCallStatus = ArmCallSmc0 (SMCCC_VERSION, NULL, NULL, NULL);
if ((SmcCallStatus < 0) || ((SmcCallStatus >> 16) >= 1)) {
SmcParam = SMCCC_ARCH_SOC_ID;
SmcCallStatus = ArmCallSmc1 (SMCCC_ARCH_FEATURES, &SmcParam, NULL, NULL);
if (SmcCallStatus >= 0) {
Arm64SocIdSupported = TRUE;
}
}
return Arm64SocIdSupported;
}
/** Fetches the JEP106 code and SoC Revision.
@param Jep106Code JEP 106 code.
@param SocRevision SoC revision.
@retval EFI_SUCCESS Succeeded.
@retval EFI_UNSUPPORTED Failed.
**/
EFI_STATUS
SmbiosGetSmcArm64SocId (
OUT INT32 *Jep106Code,
OUT INT32 *SocRevision
)
{
INT32 SmcCallStatus;
EFI_STATUS Status;
UINTN SmcParam;
Status = EFI_SUCCESS;
SmcParam = 0;
SmcCallStatus = ArmCallSmc1 (SMCCC_ARCH_SOC_ID, &SmcParam, NULL, NULL);
if (SmcCallStatus >= 0) {
*Jep106Code = SmcCallStatus;
} else {
Status = EFI_UNSUPPORTED;
}
SmcParam = 1;
SmcCallStatus = ArmCallSmc1 (SMCCC_ARCH_SOC_ID, &SmcParam, NULL, NULL);
if (SmcCallStatus >= 0) {
*SocRevision = SmcCallStatus;
} else {
Status = EFI_UNSUPPORTED;
}
return Status;
}
/** Returns a value for the Processor ID field that conforms to SMBIOS
requirements.
@ -158,12 +89,13 @@ SmbiosGetProcessorId (
VOID
)
{
INT32 Jep106Code;
INT32 SocRevision;
UINT64 ProcessorId;
EFI_STATUS Status;
UINT32 Jep106Code;
UINT32 SocRevision;
UINT64 ProcessorId;
if (HasSmcArm64SocId ()) {
SmbiosGetSmcArm64SocId (&Jep106Code, &SocRevision);
Status = ArmSmcccGetSocId (&Jep106Code, &SocRevision);
if (!EFI_ERROR (Status)) {
ProcessorId = ((UINT64)SocRevision << 32) | Jep106Code;
} else {
ProcessorId = ArmReadMidr ();
@ -236,7 +168,8 @@ SmbiosGetProcessorCharacteristics (
ZeroMem (&Characteristics, sizeof (Characteristics));
Characteristics.ProcessorArm64SocId = HasSmcArm64SocId ();
Characteristics.ProcessorArm64SocId =
ArmSmcccSocIdIsSupported ();
return Characteristics;
}

View file

@ -135,5 +135,11 @@
],
"AdditionalIncludePaths": [] # Additional paths to spell check
# (wildcards supported)
},
## options defined .pytool/Plugin/MarkdownLintCheck
"MarkdownLintCheck": {
"AuditOnly": True, # If True, log all errors and then mark as skipped
"IgnoreFiles": [] # package root relative file, folder, or glob pattern to ignore
}
}

View file

@ -88,6 +88,7 @@
MemoryAllocationLib|EmbeddedPkg/Library/PrePiMemoryAllocationLib/PrePiMemoryAllocationLib.inf
PrePiHobListPointerLib|ArmPlatformPkg/Library/PrePiHobListPointerLib/PrePiHobListPointerLib.inf
Tpm2CommandLib|SecurityPkg/Library/Tpm2CommandLib/Tpm2CommandLib.inf
Tpm2HelpLib|SecurityPkg/Library/Tpm2HelpLib/Tpm2HelpLib.inf
Tpm2DeviceLib|SecurityPkg/Library/Tpm2DeviceLibFfa/Tpm2DeviceSecLibFfa.inf
HashLib|SecurityPkg/Library/HashLibTpm2/HashLibTpm2PeilessSecLib.inf
PeilessSecMeasureLib|SecurityPkg/Library/PeilessSecMeasureLib/PeilessSecMeasureLib.inf

View file

@ -51,6 +51,7 @@ DEFINE FD_SIZE_IN_MB = 3
CLANGPDB:*_*_*_DLINK_FLAGS = /ALIGN:0x10000
[LibraryClasses.common]
GptLib|MdeModulePkg/Library/GptLib/GptLib.inf
!if $(TARGET) == RELEASE
DebugLib|MdePkg/Library/BaseDebugLibNull/BaseDebugLibNull.inf
!else
@ -120,6 +121,8 @@ DEFINE FD_SIZE_IN_MB = 3
# Virtio Support
VirtioLib|OvmfPkg/Library/VirtioLib/VirtioLib.inf
VirtioMmioDeviceLib|OvmfPkg/Library/VirtioMmioDeviceLib/VirtioMmioDeviceLib.inf
QemuFwCfgLib|OvmfPkg/Library/QemuFwCfgLib/QemuFwCfgLibNull.inf
QemuFwCfgSimpleParserLib|OvmfPkg/Library/QemuFwCfgSimpleParserLib/QemuFwCfgSimpleParserLib.inf
#
# Misc
@ -279,6 +282,7 @@ DEFINE FD_SIZE_IN_MB = 3
SecurityManagementLib|MdeModulePkg/Library/DxeSecurityManagementLib/DxeSecurityManagementLib.inf
PerformanceLib|MdeModulePkg/Library/DxePerformanceLib/DxePerformanceLib.inf
MemoryAllocationLib|MdePkg/Library/UefiMemoryAllocationLib/UefiMemoryAllocationLib.inf
MapMmioLib|OvmfPkg/Library/MapMmioLib/MapMmioLib.inf
[LibraryClasses.common.UEFI_APPLICATION]
PerformanceLib|MdeModulePkg/Library/DxePerformanceLib/DxePerformanceLib.inf
@ -286,6 +290,7 @@ DEFINE FD_SIZE_IN_MB = 3
[LibraryClasses.common.DXE_RUNTIME_DRIVER]
MemoryAllocationLib|MdePkg/Library/UefiMemoryAllocationLib/UefiMemoryAllocationLib.inf
MapMmioLib|OvmfPkg/Library/MapMmioLib/MapMmioLib.inf
!if $(TARGET) != RELEASE
DebugLib|ArmVirtPkg/Library/DebugLibFdtPL011Uart/DxeRuntimeDebugLibFdtPL011Uart.inf
!endif
@ -378,8 +383,8 @@ DEFINE FD_SIZE_IN_MB = 3
# (the memory used, and the free memory that was prereserved
# but not used).
#
gEmbeddedTokenSpaceGuid.PcdMemoryTypeEfiACPIReclaimMemory|0
gEmbeddedTokenSpaceGuid.PcdMemoryTypeEfiACPIMemoryNVS|0
gEmbeddedTokenSpaceGuid.PcdMemoryTypeEfiACPIReclaimMemory|4
gEmbeddedTokenSpaceGuid.PcdMemoryTypeEfiACPIMemoryNVS|0x3C
gEmbeddedTokenSpaceGuid.PcdMemoryTypeEfiReservedMemoryType|0
!if $(SECURE_BOOT_ENABLE) == TRUE
gEmbeddedTokenSpaceGuid.PcdMemoryTypeEfiRuntimeServicesData|600
@ -387,7 +392,7 @@ DEFINE FD_SIZE_IN_MB = 3
gEmbeddedTokenSpaceGuid.PcdMemoryTypeEfiBootServicesCode|1500
!else
gEmbeddedTokenSpaceGuid.PcdMemoryTypeEfiRuntimeServicesData|300
gEmbeddedTokenSpaceGuid.PcdMemoryTypeEfiRuntimeServicesCode|150
gEmbeddedTokenSpaceGuid.PcdMemoryTypeEfiRuntimeServicesCode|0x424
gEmbeddedTokenSpaceGuid.PcdMemoryTypeEfiBootServicesCode|1000
!endif
gEmbeddedTokenSpaceGuid.PcdMemoryTypeEfiBootServicesData|12000
@ -480,7 +485,11 @@ DEFINE FD_SIZE_IN_MB = 3
#
EmbeddedPkg/Drivers/FdtClientDxe/FdtClientDxe.inf
!if $(ENABLE_VIRTIO)
OvmfPkg/Fdt/VirtioFdtDxe/VirtioFdtDxe.inf
OvmfPkg/Fdt/VirtioFdtDxe/VirtioFdtDxe.inf {
<LibraryClasses>
NULL|OvmfPkg/Library/VirtioMmioProbeLib/VirtioMmioProbeLib.inf
}
OvmfPkg/Fdt/HighMemDxe/HighMemDxe.inf
OvmfPkg/VirtioBlkDxe/VirtioBlk.inf
OvmfPkg/VirtioScsiDxe/VirtioScsi.inf

View file

@ -68,6 +68,10 @@
DynamicPlatRepoLib|DynamicTablesPkg/Library/Common/DynamicPlatRepoLib/DynamicPlatRepoLib.inf
ArmMonitorLib|ArmVirtPkg/Library/ArmVirtMonitorLib/ArmVirtMonitorLib.inf
# OpensslLibFull/FullAccel is required for ECDH, see CryptoPkg/Readme.md
OpensslLib|CryptoPkg/Library/OpensslLib/OpensslLibFullAccel.inf
ArmCcaBootSyncCryptoLib|ArmVirtPkg/Library/ArmCcaBootSyncCryptoLib/ArmCcaBootSyncCryptoLib.inf
[LibraryClasses.common.SEC, LibraryClasses.common.PEI_CORE, LibraryClasses.common.PEIM]
PciExpressLib|MdePkg/Library/BasePciExpressLib/BasePciExpressLib.inf
@ -223,6 +227,7 @@
HobLib|EmbeddedPkg/Library/PrePiHobLib/PrePiHobLib.inf
PrePiHobListPointerLib|ArmPlatformPkg/Library/PrePiHobListPointerLib/PrePiHobListPointerLib.inf
MemoryAllocationLib|EmbeddedPkg/Library/PrePiMemoryAllocationLib/PrePiMemoryAllocationLib.inf
NULL|ArmVirtPkg/Library/Fdt16550SerialPortHookLib/EarlyFdt16550SerialPortProbeLib.inf
}
#

View file

@ -56,7 +56,8 @@
"PcAtChipsetPkg/PcAtChipsetPkg.dec",
"SecurityPkg/SecurityPkg.dec",
"UefiCpuPkg/UefiCpuPkg.dec",
"ShellPkg/ShellPkg.dec" #Is this ok?
"ShellPkg/ShellPkg.dec", #Is this ok?
"CryptoPkg/CryptoPkg.dec"
],
# For host based unit tests
"AcceptableDependencies-HOST_APPLICATION":[
@ -133,5 +134,11 @@
# Reason: Expansion of macro that contains a print specifier.
"FMT_CM_OBJECT_ID": "0x%lx"
}
},
## options defined .pytool/Plugin/MarkdownLintCheck
"MarkdownLintCheck": {
"AuditOnly": True, # If True, log all errors and then mark as skipped
"IgnoreFiles": [] # package root relative file, folder, or glob pattern to ignore
}
}

View file

@ -26,6 +26,7 @@
Include # Root include for the package
[LibraryClasses]
ArmCcaBootSyncCryptoLib|Include/Library/ArmCcaBootSyncCryptoLib.h
ArmCcaInitPeiLib|Include/Library/ArmCcaInitPeiLib.h
ArmCcaLib|Include/Library/ArmCcaLib.h
ArmCcaRsiLib|Include/Library/ArmCcaRsiLib.h
@ -51,3 +52,8 @@
# Cloud Hypervisor has no other way to pass Rsdp address to the guest except use a PCD.
#
gArmVirtTokenSpaceGuid.PcdCloudHvAcpiRsdpBaseAddress|0x0|UINT64|0x00000005
## Serial debug log level override. Accepts "silent", "verbose", or a
# hex bitmask (e.g. "0x80000040"). "verbose" falls back to the
# compiled-in PcdDebugPrintErrorLevel.
gArmVirtTokenSpaceGuid.PcdSerialDebugPrintErrorLevel|"verbose"|VOID*|0x00000006

View file

@ -78,6 +78,7 @@
!if $(TPM2_ENABLE) == TRUE
Tpm2CommandLib|SecurityPkg/Library/Tpm2CommandLib/Tpm2CommandLib.inf
Tpm2HelpLib|SecurityPkg/Library/Tpm2HelpLib/Tpm2HelpLib.inf
Tcg2PhysicalPresenceLib|OvmfPkg/Library/Tcg2PhysicalPresenceLibQemu/DxeTcg2PhysicalPresenceLib.inf
TpmMeasurementLib|SecurityPkg/Library/DxeTpmMeasurementLib/DxeTpmMeasurementLib.inf
TpmPlatformHierarchyLib|SecurityPkg/Library/PeiDxeTpmPlatformHierarchyLib/PeiDxeTpmPlatformHierarchyLib.inf
@ -146,6 +147,7 @@
gUefiOvmfPkgTokenSpaceGuid.PcdQemuVarsRequire|TRUE
gEfiMdeModulePkgTokenSpaceGuid.PcdEnableVariableRuntimeCache|FALSE
!endif
gEfiMdeModulePkgTokenSpaceGuid.PcdPeiMemoryBinsEnable|TRUE
[PcdsFixedAtBuild.common]
gUefiOvmfPkgTokenSpaceGuid.PcdOvmfFdBaseAddress|0x00000000
@ -436,7 +438,7 @@
<PcdsFixedAtBuild>
gEfiMdePkgTokenSpaceGuid.PcdDebugPrintErrorLevel|0
}
OvmfPkg/VirtioKeyboardDxe/VirtioKeyboard.inf
OvmfPkg/VirtioInputDxe/VirtioInput.inf
MdeModulePkg/Application/BootManagerMenuApp/BootManagerMenuApp.inf
OvmfPkg/QemuKernelLoaderFsDxe/QemuKernelLoaderFsDxe.inf {

View file

@ -75,6 +75,9 @@
ArmMonitorLib|ArmVirtPkg/Library/ArmVirtMonitorLib/ArmVirtMonitorLib.inf
[LibraryClasses.common.SEC]
QemuFwCfgLib|OvmfPkg/Library/QemuFwCfgLib/QemuFwCfgLibNull.inf
[LibraryClasses.common.DXE_DRIVER]
AcpiPlatformLib|OvmfPkg/Library/AcpiPlatformLib/DxeAcpiPlatformLib.inf
ReportStatusCodeLib|MdeModulePkg/Library/DxeReportStatusCodeLib/DxeReportStatusCodeLib.inf

View file

@ -21,9 +21,16 @@ typedef struct {
//
// for SerialPortLib and console IO
//
UINT64 ConsoleAddress;
UINT64 ConsoleAddress;
//
// for DebugLib; may equal ConsoleAddress if there's only one PL011 UART
//
UINT64 DebugAddress;
UINT64 DebugAddress;
//
// Serial debug log level override from fw_cfg "opt/org.tianocore/DebugLevel"
// or PcdSerialDebugPrintErrorLevel. DebugLevelSet is TRUE when an override
// is active; DebugLevel contains the parsed bitmask.
//
BOOLEAN DebugLevelSet;
UINT32 DebugLevel;
} EARLY_PL011_BASE_ADDRESS;

View file

@ -0,0 +1,239 @@
/** @file
Boot Sync Crypto Lib.
Copyright (c) 2024, Arm Limited. All rights reserved.<BR>
SPDX-License-Identifier: BSD-2-Clause-Patent
@par Glossary:
- BS - Boot Sync
@par Reference(s):
- Realm Host Interface (RHI) Specification, version 1.0-alp0
(https://developer.arm.com/documentation/den0148/)
**/
#pragma once
#include <Uefi/UefiBaseType.h>
/**
Generate an ECDH key using the ECC Curve-P384 and retrive the public key.
@param[out] Context Pointer to the key handle.
@retval EFI_INVALID_PARAMETER A parameter was invalid.
@retval EFI_OUT_OF_RESOURCES Failed to allocate memory.
@retval EFI_ABORTED An operation failed.
@retval EFI_SUCCESS Success.
**/
EFI_STATUS
EFIAPI
ArmCcaBootSyncCryptoGenerateKey (
OUT VOID **Context
);
/**
Delete the key and associated data.
@param[in] Context Pointer to the key handle.
@retval EFI_INVALID_PARAMETER A parameter was invalid.
@retval EFI_SUCCESS Success.
**/
EFI_STATUS
EFIAPI
ArmCcaBootSyncCryptoDeleteKey (
VOID *Context
);
/**
Get the public key in PEM format.
Note: The caller is responsible to free the PubKeyPem buffer
by calling FreePool().
@param[in] Context Pointer to the key handle.
@param[out] PubKeyPem Pointer to store the PEM data.
@param[out] PubKeyPemSize PEM data size.
@retval EFI_INVALID_PARAMETER A parameter was invalid.
@retval EFI_OUT_OF_RESOURCES Failed to allocate memory.
@retval EFI_ABORTED An operation failed.
@retval EFI_SUCCESS Success.
**/
EFI_STATUS
EFIAPI
ArmCcaBootSyncCryptoGetPublicKey (
IN VOID *Context,
OUT UINT8 **PubKeyPem,
OUT UINTN *PubKeyPemSize
);
/**
Get the peer key using the peer public PEM data.
Note: The caller is responsible for freeing the peer key by calling
ArmCcaBootSyncCryptoDeleteKey() for the PeerContext.
@param[out] Context Pointer to the peer key handle.
@param[in] PeerPubKeyPem Pointer to the peer PEM data.
@param[in] PeerPubKeyPemSize PEM data size.
@retval EFI_INVALID_PARAMETER A parameter was invalid.
@retval EFI_OUT_OF_RESOURCES Failed to allocate memory.
@retval EFI_ABORTED An operation failed.
@retval EFI_SUCCESS Success.
**/
EFI_STATUS
EFIAPI
ArmCcaBootSyncCryptoGeneratePeerKey (
OUT VOID **PeerContext,
IN UINT8 *PeerPubKeyPem,
IN UINTN PeerPubKeyPemSize
);
/**
Generate the common key.
Note: The common key is freed when the caller frees the Context
by calling ArmCcaBootSyncCryptoDeleteKey().
@param[in] Context Pointer to the key handle.
@param[in] PeerContext Pointer to the peer key handle.
@retval EFI_INVALID_PARAMETER A parameter was invalid.
@retval EFI_OUT_OF_RESOURCES Failed to allocate memory.
@retval EFI_ABORTED An operation failed.
@retval EFI_SUCCESS Success.
**/
EFI_STATUS
EFIAPI
ArmCcaBootSyncCryptoGenerateCommonKey (
IN VOID *Context,
IN VOID *PeerContext
);
/**
Derive keys using SHA512 HMAC-based Extract-and-Expand Key
Derivation Function (HKDF).
@param[in] Context Pointer to the key handle.
@param[in] Salt Pointer to the salt(non-secret) value.
@param[in] SaltSize Salt size in bytes.
@param[in] Info Pointer to the application specific info.
@param[in] InfoSize Info size in bytes.
@param[out] Out Pointer to buffer to receive hkdf value.
@param[in] OutSize Size of hkdf bytes to generate.
@retval TRUE Key derevation successful.
@retval FALSE Key derevation failed.
**/
BOOLEAN
EFIAPI
ArmCcaBootSyncCryptoDeriveKey (
IN VOID *Context,
IN CONST UINT8 *Salt,
IN UINTN SaltSize,
IN CONST UINT8 *Info,
IN UINTN InfoSize,
OUT UINT8 *Out,
IN UINTN OutSize
);
/**
Performs AEAD AES-GCM authenticated encryption on a data buffer and
additional authenticated data (AAD).
IvSize must be 12, otherwise FALSE is returned.
KeySize must be 16, 24 or 32, otherwise FALSE is returned.
TagSize must be 12, 13, 14, 15, 16, otherwise FALSE is returned.
@param[in] Key Pointer to the encryption key.
@param[in] KeySize Size of the encryption key in bytes.
@param[in] Iv Pointer to the IV value.
@param[in] IvSize Size of the IV value in bytes.
@param[in] AData Pointer to the additional authenticated data (AAD).
@param[in] ADataSize Size of the additional authenticated data (AAD) in bytes.
@param[in] DataIn Pointer to the input data buffer to be encrypted.
@param[in] DataInSize Size of the input data buffer in bytes.
@param[out] TagOut Pointer to a buffer that receives the authentication tag output.
@param[in] TagSize Size of the authentication tag in bytes.
@param[out] DataOut Pointer to a buffer that receives the encryption output.
@param[out] DataOutSize Size of the output data buffer in bytes.
@retval TRUE AEAD AES-GCM authenticated encryption succeeded.
@retval FALSE AEAD AES-GCM authenticated encryption failed.
**/
BOOLEAN
EFIAPI
ArmCcaBootSyncCryptoEncrypt (
IN CONST UINT8 *Key,
IN UINTN KeySize,
IN CONST UINT8 *Iv,
IN UINTN IvSize,
IN CONST UINT8 *AData,
IN UINTN ADataSize,
IN CONST UINT8 *DataIn,
IN UINTN DataInSize,
OUT UINT8 *TagOut,
IN UINTN TagSize,
OUT UINT8 *DataOut,
OUT UINTN *DataOutSize
);
/**
Performs AEAD AES-GCM authenticated decryption on a data buffer and
additional authenticated data (AAD).
IvSize must be 12, otherwise FALSE is returned.
KeySize must be 16, 24 or 32, otherwise FALSE is returned.
TagSize must be 12, 13, 14, 15, 16, otherwise FALSE is returned.
If additional authenticated data verification fails, FALSE is returned.
@param[in] Key Pointer to the encryption key.
@param[in] KeySize Size of the encryption key in bytes.
@param[in] Iv Pointer to the IV value.
@param[in] IvSize Size of the IV value in bytes.
@param[in] AData Pointer to the additional authenticated data (AAD).
@param[in] ADataSize Size of the additional authenticated data (AAD) in bytes.
@param[in] DataIn Pointer to the input data buffer to be decrypted.
@param[in] DataInSize Size of the input data buffer in bytes.
@param[in] Tag Pointer to a buffer that contains the authentication tag.
@param[in] TagSize Size of the authentication tag in bytes.
@param[out] DataOut Pointer to a buffer that receives the decryption output.
@param[out] DataOutSize Size of the output data buffer in bytes.
@retval TRUE AEAD AES-GCM authenticated decryption succeeded.
@retval FALSE AEAD AES-GCM authenticated decryption failed.
**/
BOOLEAN
EFIAPI
ArmCcaBootSyncCryptoDecrypt (
IN CONST UINT8 *Key,
IN UINTN KeySize,
IN CONST UINT8 *Iv,
IN UINTN IvSize,
IN CONST UINT8 *AData,
IN UINTN ADataSize,
IN CONST UINT8 *DataIn,
IN UINTN DataInSize,
IN CONST UINT8 *Tag,
IN UINTN TagSize,
OUT UINT8 *DataOut,
OUT UINTN *DataOutSize
);
/**
Perform initialisation required for cryptographic operations.
Note: This API must be called once before any other APIs in this library
are used.
@retval EFI_ABORTED Failed to generate seed.
@retval EFI_SUCCESS Success.
**/
EFI_STATUS
EFIAPI
ArmCcaBootSyncCryptoInit (
VOID
);

View file

@ -0,0 +1,37 @@
/** @file
Boot Sync Crypto definitions.
Copyright (c) 2024, Arm Limited. All rights reserved.<BR>
SPDX-License-Identifier: BSD-2-Clause-Patent
@par Glossary:
- BS - Boot Sync
@par Reference(s):
- Realm Host Interface (RHI) Specification, version 1.0-alp0
(https://developer.arm.com/documentation/den0148/)
**/
#pragma once
/**
A structure for storing the cryptographic key context and associated
parameters and data.
*/
typedef struct ArmCcaBootSyncKeyContext {
/// Pointer to the key context.
VOID *EcContext;
/// Cryptographic curve Nid.
UINTN EcCurveNid;
/// Pointer to the public key.
UINT8 *PublicKey;
/// Public key size
UINTN PublicKeySize;
/// Pointer to the Common key.
UINT8 *CommonKey;
/// Common key size.
UINTN CommonKeySize;
} ARM_CCA_BOOTSYNC_KEY_CONTEXT;
// For P-384, the PublicSize is 96. First 48-byte is X, Second 48-byte is Y.
#define ECC_CURVE_P384_PUB_KEY_SIZE 96

View file

@ -0,0 +1,614 @@
/** @file
Arm CCA Boot Sync Crypto library.
Copyright (c) 2024, Arm Limited. All rights reserved.<BR>
SPDX-License-Identifier: BSD-2-Clause-Patent
@par Glossary:
- BS - Boot Sync
@par Reference(s):
- Realm Host Interface (RHI) Specification, version 1.0-alp0
(https://developer.arm.com/documentation/den0148/)
**/
#include <Base.h>
#include <Library/BaseLib.h>
#include <Library/BaseCryptLib.h>
#include <Library/BaseMemoryLib.h>
#include <Library/DebugLib.h>
#include <Library/MemoryAllocationLib.h>
#include <Library/PrintLib.h>
#include <Library/RngLib.h>
#include "ArmCcaBootSyncCrypto.h"
/**
Generate a 256-bit random number as initial seed and
prime the pseudo-random number generator.
@retval EFI_ABORTED Failed to generate seed.
@retval EFI_SUCCESS Success.
**/
STATIC
EFI_STATUS
EFIAPI
ArmCcaInitRandomNumberSeed (
VOID
)
{
UINT64 RngSeed[4];
ZeroMem (RngSeed, sizeof (RngSeed));
// Generate a 256 bit random number as an inital seed.
if (!GetRandomNumber128 (RngSeed)) {
return EFI_ABORTED;
}
if (!GetRandomNumber128 (&RngSeed[2])) {
return EFI_ABORTED;
}
// Prime the pseudo-random number generator with the initial seed.
if (!RandomSeed ((UINT8 *)RngSeed, 32)) {
return EFI_ABORTED;
}
return EFI_SUCCESS;
}
/**
Generate an ECDH key using the ECC Curve-P384 and retrive the public key.
@param[out] Context Pointer to the key handle.
@retval EFI_INVALID_PARAMETER A parameter was invalid.
@retval EFI_OUT_OF_RESOURCES Failed to allocate memory.
@retval EFI_ABORTED An operation failed.
@retval EFI_SUCCESS Success.
**/
EFI_STATUS
EFIAPI
ArmCcaBootSyncCryptoGenerateKey (
OUT VOID **Context
)
{
BOOLEAN Result;
EFI_STATUS Status;
ARM_CCA_BOOTSYNC_KEY_CONTEXT *BsKey;
VOID *EcContext;
UINT8 *PublicKey;
UINTN PublicKeySize;
UINTN EcCurveNid;
if (Context == NULL) {
return EFI_INVALID_PARAMETER;
}
BsKey = (ARM_CCA_BOOTSYNC_KEY_CONTEXT *)AllocateZeroPool (
sizeof (ARM_CCA_BOOTSYNC_KEY_CONTEXT)
);
if (BsKey == NULL) {
return EFI_OUT_OF_RESOURCES;
}
// Arm CCA Security Model document section '12.3.1 Recommended parameter
// sizes' recommends using ECC Curve-P384
EcCurveNid = CRYPTO_NID_SECP384R1;
EcContext = EcNewByNid (EcCurveNid);
if (EcContext == NULL) {
Status = EFI_ABORTED;
goto exit_handler;
}
PublicKeySize = ECC_CURVE_P384_PUB_KEY_SIZE;
PublicKey = (UINT8 *)AllocateZeroPool (PublicKeySize);
if (PublicKey == NULL) {
Status = EFI_OUT_OF_RESOURCES;
goto exit_handler1;
}
Result = EcGenerateKey (
EcContext,
PublicKey,
&PublicKeySize
);
if (!Result) {
Status = EFI_ABORTED;
goto exit_handler2;
}
BsKey->EcContext = EcContext;
BsKey->PublicKey = PublicKey;
BsKey->PublicKeySize = PublicKeySize;
BsKey->EcCurveNid = EcCurveNid;
*Context = BsKey;
return EFI_SUCCESS;
exit_handler2:
FreePool (PublicKey);
exit_handler1:
EcFree (EcContext);
exit_handler:
FreePool (BsKey);
return Status;
}
/**
Delete the key and associated data.
@param[in] Context Pointer to the key handle.
@retval EFI_INVALID_PARAMETER A parameter was invalid.
@retval EFI_SUCCESS Success.
**/
EFI_STATUS
EFIAPI
ArmCcaBootSyncCryptoDeleteKey (
VOID *Context
)
{
ARM_CCA_BOOTSYNC_KEY_CONTEXT *BsKey;
if (Context == NULL) {
return EFI_INVALID_PARAMETER;
}
BsKey = (ARM_CCA_BOOTSYNC_KEY_CONTEXT *)Context;
if (BsKey->PublicKey != NULL) {
ZeroMem (BsKey->PublicKey, BsKey->PublicKeySize);
FreePool (BsKey->PublicKey);
}
if (BsKey->CommonKey != NULL) {
ZeroMem (BsKey->CommonKey, BsKey->CommonKeySize);
FreePool (BsKey->CommonKey);
}
if (BsKey->EcContext != NULL) {
EcFree (BsKey->EcContext);
}
FreePool (BsKey);
return EFI_SUCCESS;
}
/**
Get the public key in PEM format.
Note: The caller is responsible to free the PubKeyPem buffer
by calling FreePool().
@param[in] Context Pointer to the key handle.
@param[out] PubKeyPem Pointer to store the PEM data.
@param[out] PubKeyPemSize PEM data size.
@retval EFI_INVALID_PARAMETER A parameter was invalid.
@retval EFI_OUT_OF_RESOURCES Failed to allocate memory.
@retval EFI_ABORTED An operation failed.
@retval EFI_SUCCESS Success.
**/
EFI_STATUS
EFIAPI
ArmCcaBootSyncCryptoGetPublicKey (
IN VOID *Context,
OUT UINT8 **PubKeyPem,
OUT UINTN *PubKeyPemSize
)
{
BOOLEAN Result;
EFI_STATUS Status;
ARM_CCA_BOOTSYNC_KEY_CONTEXT *BsKey;
UINT8 *PemData;
UINTN PemSize;
if ((Context == NULL) || (PubKeyPem == NULL) || (PubKeyPemSize == NULL)) {
return EFI_INVALID_PARAMETER;
}
BsKey = (ARM_CCA_BOOTSYNC_KEY_CONTEXT *)Context;
// First get the PEM size.
PemData = NULL;
PemSize = 0;
Result = EcPublicKeyToPEM (
BsKey->EcContext,
PemData,
&PemSize
);
if ((!Result) && (PemSize == 0)) {
return EFI_ABORTED;
}
PemData = AllocateZeroPool (PemSize);
if (PemData == NULL) {
return EFI_OUT_OF_RESOURCES;
}
Result = EcPublicKeyToPEM (
BsKey->EcContext,
PemData,
&PemSize
);
if (!Result) {
Status = EFI_ABORTED;
goto exit_handler;
}
*PubKeyPem = PemData;
*PubKeyPemSize = PemSize;
return EFI_SUCCESS;
exit_handler:
FreePool (PemData);
return Status;
}
/**
Get the peer key using the peer public PEM data.
Note: The caller is responsible for freeing the peer key by calling
ArmCcaBootSyncCryptoDeleteKey() for the PeerContext.
@param[out] PeerContext Pointer to the peer key handle.
@param[in] PeerPubKeyPem Pointer to the peer PEM data.
@param[in] PeerPubKeyPemSize PEM data size.
@retval EFI_INVALID_PARAMETER A parameter was invalid.
@retval EFI_OUT_OF_RESOURCES Failed to allocate memory.
@retval EFI_ABORTED An operation failed.
@retval EFI_SUCCESS Success.
**/
EFI_STATUS
EFIAPI
ArmCcaBootSyncCryptoGeneratePeerKey (
OUT VOID **PeerContext,
IN UINT8 *PeerPubKeyPem,
IN UINTN PeerPubKeyPemSize
)
{
BOOLEAN Result;
EFI_STATUS Status;
ARM_CCA_BOOTSYNC_KEY_CONTEXT *BsKey;
VOID *EcContextRetrieved;
UINT8 *PublicKey;
UINTN PublicKeySize;
UINTN PeerKeyNid;
if ((PeerContext == NULL) ||
(PeerPubKeyPem == NULL) ||
(PeerPubKeyPemSize == 0))
{
return EFI_INVALID_PARAMETER;
}
BsKey = (ARM_CCA_BOOTSYNC_KEY_CONTEXT *)AllocateZeroPool (
sizeof (ARM_CCA_BOOTSYNC_KEY_CONTEXT)
);
if (BsKey == NULL) {
return EFI_OUT_OF_RESOURCES;
}
Result = EcGetPublicKeyFromPem (
PeerPubKeyPem,
PeerPubKeyPemSize,
NULL,
&EcContextRetrieved
);
if (!Result) {
Status = EFI_ABORTED;
goto exit_handler;
}
Result = EcGetCurveNid (EcContextRetrieved, &PeerKeyNid);
if ((!Result) || (PeerKeyNid != CRYPTO_NID_SECP384R1)) {
Status = EFI_INVALID_PARAMETER;
goto exit_handler1;
}
PublicKeySize = ECC_CURVE_P384_PUB_KEY_SIZE;
PublicKey = AllocateZeroPool (PublicKeySize);
if (PublicKey == NULL) {
Status = EFI_OUT_OF_RESOURCES;
goto exit_handler1;
}
Result = EcGetPubKey (
EcContextRetrieved,
PublicKey,
&PublicKeySize
);
if (!Result) {
Status = EFI_ABORTED;
goto exit_handler2;
}
BsKey->EcContext = EcContextRetrieved;
BsKey->PublicKey = PublicKey;
BsKey->PublicKeySize = PublicKeySize;
BsKey->EcCurveNid = CRYPTO_NID_SECP384R1;
*PeerContext = BsKey;
return EFI_SUCCESS;
exit_handler2:
FreePool (PublicKey);
exit_handler1:
EcFree (EcContextRetrieved);
exit_handler:
FreePool (BsKey);
return Status;
}
/**
Generate the common key.
Note: The common key is freed when the caller frees the Context
by calling ArmCcaBootSyncCryptoDeleteKey().
@param[in] Context Pointer to the key handle.
@param[in] PeerContext Pointer to the peer key handle.
@retval EFI_INVALID_PARAMETER A parameter was invalid.
@retval EFI_OUT_OF_RESOURCES Failed to allocate memory.
@retval EFI_ABORTED An operation failed.
@retval EFI_SUCCESS Success.
**/
EFI_STATUS
EFIAPI
ArmCcaBootSyncCryptoGenerateCommonKey (
IN VOID *Context,
IN VOID *PeerContext
)
{
BOOLEAN Result;
EFI_STATUS Status;
ARM_CCA_BOOTSYNC_KEY_CONTEXT *BsKey;
ARM_CCA_BOOTSYNC_KEY_CONTEXT *BsKeyPeer;
UINT8 *CommKey;
UINTN CommKeySize;
if ((Context == NULL) ||
(PeerContext == NULL))
{
ASSERT (0);
return EFI_INVALID_PARAMETER;
}
BsKey = (ARM_CCA_BOOTSYNC_KEY_CONTEXT *)Context;
BsKeyPeer = (ARM_CCA_BOOTSYNC_KEY_CONTEXT *)PeerContext;
if ((BsKey->CommonKey != NULL) ||
(BsKey->CommonKeySize != 0))
{
ASSERT (0);
return EFI_INVALID_PARAMETER;
}
CommKeySize = ECC_CURVE_P384_PUB_KEY_SIZE;
CommKey = (UINT8 *)AllocateZeroPool (CommKeySize);
if (CommKey == NULL) {
ASSERT (0);
return EFI_OUT_OF_RESOURCES;
}
Result = EcDhComputeKey (
BsKey->EcContext,
BsKeyPeer->PublicKey,
BsKeyPeer->PublicKeySize,
NULL,
CommKey,
&CommKeySize
);
if (!Result) {
Status = EFI_ABORTED;
ASSERT (0);
goto exit_handler;
}
BsKey->CommonKey = CommKey;
BsKey->CommonKeySize = CommKeySize;
return EFI_SUCCESS;
exit_handler:
FreePool (CommKey);
return Status;
}
/**
Derive keys using SHA512 HMAC-based Extract-and-Expand Key
Derivation Function (HKDF).
@param[in] Context Pointer to the key handle.
@param[in] Salt Pointer to the salt(non-secret) value.
@param[in] SaltSize Salt size in bytes.
@param[in] Info Pointer to the application specific info.
@param[in] InfoSize Info size in bytes.
@param[out] Out Pointer to buffer to receive hkdf value.
@param[in] OutSize Size of hkdf bytes to generate.
@retval TRUE Key derevation successful.
@retval FALSE Key derevation failed.
**/
BOOLEAN
EFIAPI
ArmCcaBootSyncCryptoDeriveKey (
IN VOID *Context,
IN CONST UINT8 *Salt,
IN UINTN SaltSize,
IN CONST UINT8 *Info,
IN UINTN InfoSize,
OUT UINT8 *Out,
IN UINTN OutSize
)
{
ARM_CCA_BOOTSYNC_KEY_CONTEXT *BsKey;
if ((Context == NULL) ||
(Salt == NULL) ||
(Info == NULL) ||
(Out == NULL))
{
return FALSE;
}
BsKey = (ARM_CCA_BOOTSYNC_KEY_CONTEXT *)Context;
if ((BsKey->CommonKey == NULL) ||
(BsKey->CommonKeySize == 0))
{
return FALSE;
}
// Derive SHA512 HMAC-based Extract-and-Expand Key Derivation Function (HKDF).
return HkdfSha512ExtractAndExpand (
BsKey->CommonKey,
BsKey->CommonKeySize,
Salt,
SaltSize,
Info,
InfoSize,
Out,
OutSize
);
}
/**
Performs AEAD AES-GCM authenticated encryption on a data buffer and
additional authenticated data (AAD).
IvSize must be 12, otherwise FALSE is returned.
KeySize must be 16, 24 or 32, otherwise FALSE is returned.
TagSize must be 12, 13, 14, 15, 16, otherwise FALSE is returned.
@param[in] Key Pointer to the encryption key.
@param[in] KeySize Size of the encryption key in bytes.
@param[in] Iv Pointer to the IV value.
@param[in] IvSize Size of the IV value in bytes.
@param[in] AData Pointer to the additional authenticated data (AAD).
@param[in] ADataSize Size of the additional authenticated data (AAD) in bytes.
@param[in] DataIn Pointer to the input data buffer to be encrypted.
@param[in] DataInSize Size of the input data buffer in bytes.
@param[out] TagOut Pointer to a buffer that receives the authentication tag output.
@param[in] TagSize Size of the authentication tag in bytes.
@param[out] DataOut Pointer to a buffer that receives the encryption output.
@param[out] DataOutSize Size of the output data buffer in bytes.
@retval TRUE AEAD AES-GCM authenticated encryption succeeded.
@retval FALSE AEAD AES-GCM authenticated encryption failed.
**/
BOOLEAN
EFIAPI
ArmCcaBootSyncCryptoEncrypt (
IN CONST UINT8 *Key,
IN UINTN KeySize,
IN CONST UINT8 *Iv,
IN UINTN IvSize,
IN CONST UINT8 *AData,
IN UINTN ADataSize,
IN CONST UINT8 *DataIn,
IN UINTN DataInSize,
OUT UINT8 *TagOut,
IN UINTN TagSize,
OUT UINT8 *DataOut,
OUT UINTN *DataOutSize
)
{
return AeadAesGcmEncrypt (
Key,
KeySize,
Iv,
IvSize,
AData,
ADataSize,
DataIn,
DataInSize,
TagOut,
TagSize,
DataOut,
DataOutSize
);
}
/**
Performs AEAD AES-GCM authenticated decryption on a data buffer and
additional authenticated data (AAD).
IvSize must be 12, otherwise FALSE is returned.
KeySize must be 16, 24 or 32, otherwise FALSE is returned.
TagSize must be 12, 13, 14, 15, 16, otherwise FALSE is returned.
If additional authenticated data verification fails, FALSE is returned.
@param[in] Key Pointer to the encryption key.
@param[in] KeySize Size of the encryption key in bytes.
@param[in] Iv Pointer to the IV value.
@param[in] IvSize Size of the IV value in bytes.
@param[in] AData Pointer to the additional authenticated data (AAD).
@param[in] ADataSize Size of the additional authenticated data (AAD) in bytes.
@param[in] DataIn Pointer to the input data buffer to be decrypted.
@param[in] DataInSize Size of the input data buffer in bytes.
@param[in] Tag Pointer to a buffer that contains the authentication tag.
@param[in] TagSize Size of the authentication tag in bytes.
@param[out] DataOut Pointer to a buffer that receives the decryption output.
@param[out] DataOutSize Size of the output data buffer in bytes.
@retval TRUE AEAD AES-GCM authenticated decryption succeeded.
@retval FALSE AEAD AES-GCM authenticated decryption failed.
**/
BOOLEAN
EFIAPI
ArmCcaBootSyncCryptoDecrypt (
IN CONST UINT8 *Key,
IN UINTN KeySize,
IN CONST UINT8 *Iv,
IN UINTN IvSize,
IN CONST UINT8 *AData,
IN UINTN ADataSize,
IN CONST UINT8 *DataIn,
IN UINTN DataInSize,
IN CONST UINT8 *Tag,
IN UINTN TagSize,
OUT UINT8 *DataOut,
OUT UINTN *DataOutSize
)
{
return AeadAesGcmDecrypt (
Key,
KeySize,
Iv,
IvSize,
AData,
ADataSize,
DataIn,
DataInSize,
Tag,
TagSize,
DataOut,
DataOutSize
);
}
/**
Perform initialisation required for cryptographic operations.
Note: This API must be called once before any other APIs in this library
are used.
@retval EFI_ABORTED Failed to generate seed.
@retval EFI_SUCCESS Success.
**/
EFI_STATUS
EFIAPI
ArmCcaBootSyncCryptoInit (
VOID
)
{
return ArmCcaInitRandomNumberSeed ();
}

View file

@ -0,0 +1,33 @@
## @file
# Library that implements the Boot Sync Crypto interfaces.
#
# Copyright (c) 2024, Arm Limited. All rights reserved.<BR>
#
# SPDX-License-Identifier: BSD-2-Clause-Patent
#
##
[Defines]
INF_VERSION = 0x0001001B
BASE_NAME = ArmCcaBootSyncCryptoLib
FILE_GUID = 234394BC-1D5D-4F6D-A890-259B166BCF0A
MODULE_TYPE = BASE
VERSION_STRING = 1.0
LIBRARY_CLASS = ArmCcaBootSyncCryptoLib
[Sources]
ArmCcaBootSyncCrypto.h
ArmCcaBootSyncCryptoLib.c
[Packages]
ArmVirtPkg/ArmVirtPkg.dec
CryptoPkg/CryptoPkg.dec
MdePkg/MdePkg.dec
[LibraryClasses]
BaseCryptLib
BaseLib
BaseMemoryLib
DebugLib
RngLib
MemoryAllocationLib

View file

@ -2,6 +2,7 @@
NULL library class implementation to discover the GIC for DT based virt platforms
Copyright (c) 2015 - 2016, Linaro Ltd. All rights reserved.<BR>
Copyright (c) 2026, Arm Ltd. All rights reserved.<BR>
SPDX-License-Identifier: BSD-2-Clause-Patent
@ -13,6 +14,7 @@
#include <Library/ArmGicLib.h>
#include <Library/BaseLib.h>
#include <Library/DebugLib.h>
#include <Library/MapMmioLib.h>
#include <Library/PcdLib.h>
#include <Library/UefiBootServicesTableLib.h>
@ -31,6 +33,7 @@ ArmVirtGicArchLibConstructor (
UINTN GicRevision;
EFI_STATUS Status;
UINT64 DistBase, CpuBase, RedistBase;
UINT64 DistSize, CpuSize, RedistSize;
RETURN_STATUS PcdStatus;
Status = gBS->LocateProtocol (
@ -84,10 +87,14 @@ ArmVirtGicArchLibConstructor (
// RegProp[0..1] == { GICD base, GICD size }
DistBase = SwapBytes64 (Reg[0]);
ASSERT (DistBase < MAX_UINTN);
DistSize = SwapBytes64 (Reg[1]);
ASSERT (DistSize < MAX_UINTN);
// RegProp[2..3] == { GICR base, GICR size }
RedistBase = SwapBytes64 (Reg[2]);
ASSERT (RedistBase < MAX_UINTN);
RedistSize = SwapBytes64 (Reg[3]);
ASSERT (RedistSize < MAX_UINTN);
PcdStatus = PcdSet64S (PcdGicDistributorBase, DistBase);
ASSERT_RETURN_ERROR (PcdStatus);
@ -96,11 +103,38 @@ ArmVirtGicArchLibConstructor (
DEBUG ((
DEBUG_INFO,
"Found GIC v3 (re)distributor @ 0x%Lx (0x%Lx)\n",
"Found GIC v3 Distributor @ 0x%Lx, Len 0x%Lx\n",
DistBase,
RedistBase
DistSize
));
DEBUG ((
DEBUG_INFO,
"Found GIC v3 Redistributor @ 0x%Lx, Len 0x%Lx\n",
RedistBase,
RedistSize
));
Status = MapMmioMemory (
DistBase,
DistSize,
(EFI_MEMORY_UC | EFI_MEMORY_XP)
);
if (EFI_ERROR (Status)) {
ASSERT_EFI_ERROR (Status);
return (RETURN_STATUS)Status;
}
Status = MapMmioMemory (
RedistBase,
RedistSize,
(EFI_MEMORY_UC | EFI_MEMORY_XP)
);
if (EFI_ERROR (Status)) {
ASSERT_EFI_ERROR (Status);
return (RETURN_STATUS)Status;
}
break;
case 2:
@ -112,9 +146,13 @@ ArmVirtGicArchLibConstructor (
ASSERT ((RegSize == 32) || (RegSize == 64));
DistBase = SwapBytes64 (Reg[0]);
DistSize = SwapBytes64 (Reg[1]);
CpuBase = SwapBytes64 (Reg[2]);
CpuSize = SwapBytes64 (Reg[3]);
ASSERT (DistBase < MAX_UINTN);
ASSERT (CpuBase < MAX_UINTN);
ASSERT (DistSize < MAX_UINTN);
ASSERT (CpuSize < MAX_UINTN);
PcdStatus = PcdSet64S (PcdGicDistributorBase, DistBase);
ASSERT_RETURN_ERROR (PcdStatus);
@ -123,6 +161,26 @@ ArmVirtGicArchLibConstructor (
DEBUG ((DEBUG_INFO, "Found GIC @ 0x%Lx/0x%Lx\n", DistBase, CpuBase));
Status = MapMmioMemory (
DistBase,
DistSize,
(EFI_MEMORY_UC | EFI_MEMORY_XP)
);
if (EFI_ERROR (Status)) {
ASSERT_EFI_ERROR (Status);
return (RETURN_STATUS)Status;
}
Status = MapMmioMemory (
CpuBase,
CpuSize,
(EFI_MEMORY_UC | EFI_MEMORY_XP)
);
if (EFI_ERROR (Status)) {
ASSERT_EFI_ERROR (Status);
return (RETURN_STATUS)Status;
}
break;
default:

View file

@ -3,6 +3,7 @@
# Component description file for ArmVirtGicArchLib module
#
# Copyright (c) 2015, Linaro Ltd. All rights reserved.<BR>
# Copyright (c) 2026, Arm Ltd. All rights reserved.<BR>
#
# SPDX-License-Identifier: BSD-2-Clause-Patent
#
@ -24,6 +25,7 @@
BaseLib
DebugLib
PcdLib
MapMmioLib
UefiBootServicesTableLib
[Packages]
@ -31,6 +33,7 @@
ArmVirtPkg/ArmVirtPkg.dec
EmbeddedPkg/EmbeddedPkg.dec
MdePkg/MdePkg.dec
OvmfPkg/OvmfPkg.dec
[Protocols]
gFdtClientProtocolGuid ## CONSUMES

View file

@ -94,17 +94,28 @@ DebugPrintMarker (
IN BASE_LIST BaseListMarker
)
{
CHAR8 Buffer[MAX_DEBUG_MESSAGE_LENGTH];
CHAR8 Buffer[MAX_DEBUG_MESSAGE_LENGTH];
UINT32 SerialDebugLevel;
UINT32 DebugLevel;
EFI_STATUS Status;
//
// If Format is NULL, then ASSERT().
//
ASSERT (Format != NULL);
DebugLevel = GetDebugPrintErrorLevel ();
Status = GetSerialDebugPrintErrorLevel (&SerialDebugLevel);
if (EFI_ERROR (Status)) {
SerialDebugLevel = DebugLevel;
}
//
// Check driver debug mask value and global mask
// SerialDebugLevel can be more verbose than DebugLevel.
// Check if we have something to print
//
if ((ErrorLevel & GetDebugPrintErrorLevel ()) == 0) {
if (((ErrorLevel & DebugLevel) == 0) && ((ErrorLevel & SerialDebugLevel) == 0)) {
return;
}
@ -118,12 +129,19 @@ DebugPrintMarker (
}
//
// Send string to Memory Debug Log if enabled
// Send string to Memory Debug Log if enabled and error level matches
//
if (MemDebugLogEnabled ()) {
if (((ErrorLevel & DebugLevel) != 0) && MemDebugLogEnabled ()) {
MemDebugLogWrite ((CHAR8 *)Buffer, AsciiStrLen (Buffer));
}
//
// Check runtime debug mask value and global mask
//
if ((ErrorLevel & SerialDebugLevel) == 0) {
return;
}
//
// Send the print string to a Serial Port
//

View file

@ -50,6 +50,7 @@
[FixedPcd]
gArmPlatformTokenSpaceGuid.PL011UartClkInHz
gArmVirtTokenSpaceGuid.PcdSerialDebugPrintErrorLevel
gEfiMdePkgTokenSpaceGuid.PcdUartDefaultBaudRate
gEfiMdePkgTokenSpaceGuid.PcdUartDefaultDataBits
gEfiMdePkgTokenSpaceGuid.PcdUartDefaultParity

View file

@ -6,12 +6,64 @@
SPDX-License-Identifier: BSD-2-Clause-Patent
**/
#include <Library/BaseLib.h>
#include <Library/DebugLib.h>
#include <Library/FdtSerialPortAddressLib.h>
#include <Library/PL011UartLib.h>
#include <Library/PcdLib.h>
#include "Write.h"
//
// Duplicated in ArmVirtPkg/Library/PlatformPeiLib/PlatformPeiLib.c —
// keep both copies in sync.
//
/**
Parse a serial debug level string.
Accepted values are "silent" (DEBUG_ERROR only), "verbose" (no
override), or a hex bitmask (e.g. "0x80000040").
@param[in] String NUL-terminated ASCII string to parse.
@param[out] DebugLevel On success, the parsed debug level bitmask.
@retval TRUE String was recognised; *DebugLevel is valid.
@retval FALSE String is NULL, "verbose", or unrecognised; no override.
**/
STATIC
BOOLEAN
ParseSerialDebugLevel (
IN CONST CHAR8 *String,
OUT UINT32 *DebugLevel
)
{
UINT64 Value;
CHAR8 *End;
if ((String == NULL) || (DebugLevel == NULL)) {
return FALSE;
}
if (AsciiStrCmp (String, "silent") == 0) {
*DebugLevel = DEBUG_ERROR;
return TRUE;
}
if (AsciiStrCmp (String, "verbose") == 0) {
return FALSE;
}
if (!EFI_ERROR (AsciiStrHexToUint64S (String, &End, &Value)) &&
(*End == '\0'))
{
*DebugLevel = (UINT32)Value;
return TRUE;
}
return FALSE;
}
/**
(Copied from SerialPortWrite() in "MdePkg/Include/Library/SerialPortLib.h" at
commit c4547aefb3d0, with the Buffer non-nullity assertion removed:)
@ -105,3 +157,35 @@ DebugLibFdtPL011UartWrite (
return PL011UartWrite ((UINTN)DebugAddress, Buffer, NumberOfBytes);
}
/**
Retrieve the serial debug print error level override.
The flash variant parses the compile-time PCD only. The fw_cfg
override is not available in SEC/PEI_CORE phases.
@param[out] Value On success, the debug log level bitmask.
@retval EFI_SUCCESS The debug level was retrieved successfully.
@retval EFI_INVALID_PARAMETER Value is NULL.
@retval EFI_NOT_FOUND No override is configured (e.g. "verbose").
**/
EFI_STATUS
GetSerialDebugPrintErrorLevel (
OUT UINT32 *Value
)
{
CONST CHAR8 *String;
if (Value == NULL) {
return EFI_INVALID_PARAMETER;
}
String = (CONST CHAR8 *)PcdGetPtr (PcdSerialDebugPrintErrorLevel);
if (ParseSerialDebugLevel (String, Value)) {
return EFI_SUCCESS;
}
return EFI_NOT_FOUND;
}

View file

@ -20,6 +20,8 @@
UINTN mDebugLibFdtPL011UartAddress;
RETURN_STATUS mDebugLibFdtPL011UartPermanentStatus = RETURN_SUCCESS;
BOOLEAN mSerialDebugLevelSet;
UINT32 mSerialDebugLevel;
/**
Statefully initialize both the library instance and the debug PL011 UART.
@ -62,6 +64,11 @@ Initialize (
goto Failed;
}
if (UartBase->DebugLevelSet) {
mSerialDebugLevelSet = TRUE;
mSerialDebugLevel = UartBase->DebugLevel;
}
BaudRate = (UINTN)PcdGet64 (PcdUartDefaultBaudRate);
ReceiveFifoDepth = 0; // Use the default value for Fifo depth
Parity = (EFI_PARITY_TYPE)PcdGet8 (PcdUartDefaultParity);
@ -122,3 +129,36 @@ DebugLibFdtPL011UartWrite (
return PL011UartWrite (mDebugLibFdtPL011UartAddress, Buffer, NumberOfBytes);
}
/**
Retrieve the serial debug print error level override.
@param[out] Value On success, the debug log level bitmask.
@retval EFI_SUCCESS The debug level was retrieved successfully.
@retval EFI_INVALID_PARAMETER Value is NULL.
@retval EFI_NOT_FOUND The debug level is not available.
**/
EFI_STATUS
GetSerialDebugPrintErrorLevel (
OUT UINT32 *Value
)
{
RETURN_STATUS Status;
if (Value == NULL) {
return EFI_INVALID_PARAMETER;
}
Status = Initialize ();
if (RETURN_ERROR (Status)) {
return EFI_NOT_FOUND;
}
if (mSerialDebugLevelSet) {
*Value = mSerialDebugLevel;
return EFI_SUCCESS;
}
return EFI_NOT_FOUND;
}

View file

@ -34,3 +34,17 @@ DebugLibFdtPL011UartWrite (
IN UINT8 *Buffer,
IN UINTN NumberOfBytes
);
/**
Retrieve the serial debug print error level override.
@param[out] Value On success, the debug log level bitmask.
@retval EFI_SUCCESS The debug level was retrieved successfully.
@retval EFI_INVALID_PARAMETER Value is NULL.
@retval EFI_NOT_FOUND The debug level is not available.
**/
EFI_STATUS
GetSerialDebugPrintErrorLevel (
OUT UINT32 *Value
);

View file

@ -0,0 +1,31 @@
/** @file
Early FDT 16550 serial port probe constructor.
Copyright (c) 2026, ARM Ltd. All rights reserved.<BR>
SPDX-License-Identifier: BSD-2-Clause-Patent
**/
#include <Base.h>
#include <Library/PlatformHookLib.h>
/**
Early constructor to probe the FDT for the 16550 UART base address.
This constructor invokes the platform serial hook so early boot code can
populate PcdSerialRegisterBase before it is used.
@retval RETURN_SUCCESS The serial port base address was already
configured or was found and stored.
@retval RETURN_INVALID_PARAMETER A parameter was invalid.
@retval RETURN_NOT_FOUND Serial port information was not found.
@retval RETURN_PROTOCOL_ERROR Invalid serial port information was found
in the device tree.
**/
RETURN_STATUS
EFIAPI
EarlyFdt16550SerialPortProbeLibConstructor (
VOID
)
{
return PlatformHookSerialPortInitialize ();
}

View file

@ -0,0 +1,29 @@
## @file
# Early Platform Probe Library instance for 16550 Uart.
#
# Copyright (c) 2026, ARM Ltd. All rights reserved.<BR>
#
# SPDX-License-Identifier: BSD-2-Clause-Patent
#
##
[Defines]
INF_VERSION = 0x0001001B
BASE_NAME = EarlyFdt16550SerialPortProbeLib
MODULE_UNI_FILE = Fdt16550SerialPortHookLib.uni
FILE_GUID = 07a000d5-7de7-485f-ab59-a2ce4da5e488
MODULE_TYPE = BASE
VERSION_STRING = 1.0
LIBRARY_CLASS = NULL|SEC PEI_CORE PEIM
CONSTRUCTOR = EarlyFdt16550SerialPortProbeLibConstructor
[Sources]
EarlyFdt16550SerialPortProbeLib.c
[LibraryClasses]
PlatformHookLib
[Packages]
ArmVirtPkg/ArmVirtPkg.dec
MdeModulePkg/MdeModulePkg.dec
MdePkg/MdePkg.dec

View file

@ -1,7 +1,7 @@
/** @file
FDT client library for motorola,mc146818 RTC driver
Copyright (c) 2020, ARM Limited. All rights reserved.<BR>
Copyright (c) 2020 - 2026, ARM Limited. All rights reserved.<BR>
SPDX-License-Identifier: BSD-2-Clause-Patent
@ -10,6 +10,7 @@
#include <Library/BaseLib.h>
#include <Library/DebugLib.h>
#include <Library/DxeServicesTableLib.h>
#include <Library/MapMmioLib.h>
#include <Library/PcdLib.h>
#include <Library/UefiBootServicesTableLib.h>
#include <Protocol/FdtClient.h>
@ -29,7 +30,8 @@
@retval EFI_SUCCESS Success.
@retval EFI_INVALID_PARAMETER A parameter is invalid.
@retval EFI_NOT_FOUND Flash device not found.
@retval EFI_NOT_FOUND The requested GCD memory space could
not be found.
**/
STATIC
EFI_STATUS
@ -40,16 +42,15 @@ KvmtoolRtcMapMemory (
{
EFI_STATUS Status;
Status = gDS->AddMemorySpace (
EfiGcdMemoryTypeMemoryMappedIo,
RtcPageBase,
EFI_PAGE_SIZE,
EFI_MEMORY_UC | EFI_MEMORY_RUNTIME | EFI_MEMORY_XP
);
Status = MapMmioMemory (
RtcPageBase,
EFI_PAGE_SIZE,
EFI_MEMORY_UC | EFI_MEMORY_RUNTIME | EFI_MEMORY_XP
);
if (EFI_ERROR (Status)) {
DEBUG ((
DEBUG_ERROR,
"Failed to add memory space. Status = %r\n",
"Failed to map memory. Status = %r\n",
Status
));
return Status;
@ -70,32 +71,6 @@ KvmtoolRtcMapMemory (
"Failed to allocate memory space. Status = %r\n",
Status
));
gDS->RemoveMemorySpace (
RtcPageBase,
EFI_PAGE_SIZE
);
return Status;
}
Status = gDS->SetMemorySpaceAttributes (
RtcPageBase,
EFI_PAGE_SIZE,
EFI_MEMORY_UC | EFI_MEMORY_RUNTIME | EFI_MEMORY_XP
);
if (EFI_ERROR (Status)) {
DEBUG ((
DEBUG_ERROR,
"Failed to set memory attributes. Status = %r\n",
Status
));
gDS->FreeMemorySpace (
RtcPageBase,
EFI_PAGE_SIZE
);
gDS->RemoveMemorySpace (
RtcPageBase,
EFI_PAGE_SIZE
);
}
return Status;
@ -113,7 +88,8 @@ KvmtoolRtcMapMemory (
@retval EFI_SUCCESS Success.
@retval EFI_INVALID_PARAMETER A parameter is invalid.
@retval EFI_NOT_FOUND Flash device not found.
@retval EFI_NOT_FOUND The requested GCD memory space could
not be found.
**/
EFI_STATUS
EFIAPI

View file

@ -1,7 +1,7 @@
## @file
# FDT client library for motorola,mc146818 RTC driver
#
# Copyright (c) 2020 - 2023, ARM Limited. All rights reserved.<BR>
# Copyright (c) 2020 - 2026, ARM Limited. All rights reserved.<BR>
#
# SPDX-License-Identifier: BSD-2-Clause-Patent
#
@ -23,11 +23,13 @@
ArmVirtPkg/ArmVirtPkg.dec
EmbeddedPkg/EmbeddedPkg.dec
MdePkg/MdePkg.dec
OvmfPkg/OvmfPkg.dec
PcAtChipsetPkg/PcAtChipsetPkg.dec
[LibraryClasses]
BaseLib
DebugLib
MapMmioLib
PcdLib
UefiBootServicesTableLib
DxeServicesTableLib
@ -40,4 +42,4 @@
gPcAtChipsetPkgTokenSpaceGuid.PcdRtcTargetRegister64
[Depex]
gFdtClientProtocolGuid AND gEfiCpuArchProtocolGuid
gFdtClientProtocolGuid

View file

@ -1,7 +1,7 @@
/** @file
Kvmtool virtual memory map library.
Copyright (c) 2018 - 2020, ARM Limited. All rights reserved.
Copyright (c) 2018 - 2026, ARM Limited. All rights reserved.
SPDX-License-Identifier: BSD-2-Clause-Patent
@ -9,8 +9,6 @@
#include <Base.h>
#include <Library/ArmLib.h>
#include <Library/BaseLib.h>
#include <Library/BaseMemoryLib.h>
#include <Library/DebugLib.h>
#include <Library/MemoryAllocationLib.h>
@ -37,12 +35,9 @@ ArmVirtGetMemoryMap (
{
ARM_MEMORY_REGION_DESCRIPTOR *VirtualMemoryTable;
UINTN Idx;
EFI_PHYSICAL_ADDRESS TopOfAddressSpace;
ASSERT (VirtualMemoryMap != NULL);
TopOfAddressSpace = LShiftU64 (1ULL, ArmGetPhysicalAddressBits ());
VirtualMemoryTable = (ARM_MEMORY_REGION_DESCRIPTOR *)
AllocatePages (
EFI_SIZE_TO_PAGES (
@ -66,20 +61,13 @@ ArmVirtGetMemoryMap (
VirtualMemoryTable[Idx].Length = PcdGet64 (PcdSystemMemorySize);
VirtualMemoryTable[Idx].Attributes = ARM_MEMORY_REGION_ATTRIBUTE_WRITE_BACK;
// Peripheral space before DRAM
VirtualMemoryTable[++Idx].PhysicalBase = 0x0;
VirtualMemoryTable[Idx].VirtualBase = 0x0;
VirtualMemoryTable[Idx].Length = PcdGet64 (PcdSystemMemoryBase);
// Map the UART
ASSERT (IS_ALIGNED (PcdGet64 (PcdSerialRegisterBase), EFI_PAGE_SIZE));
VirtualMemoryTable[++Idx].PhysicalBase = PcdGet64 (PcdSerialRegisterBase);
VirtualMemoryTable[Idx].VirtualBase = PcdGet64 (PcdSerialRegisterBase);
VirtualMemoryTable[Idx].Length = EFI_PAGE_SIZE;
VirtualMemoryTable[Idx].Attributes = ARM_MEMORY_REGION_ATTRIBUTE_DEVICE;
// Peripheral space after DRAM
VirtualMemoryTable[++Idx].PhysicalBase = PcdGet64 (PcdSystemMemoryBase) +
PcdGet64 (PcdSystemMemorySize);
VirtualMemoryTable[Idx].VirtualBase = VirtualMemoryTable[Idx].PhysicalBase;
VirtualMemoryTable[Idx].Length = TopOfAddressSpace -
VirtualMemoryTable[Idx].PhysicalBase;
VirtualMemoryTable[Idx].Attributes = ARM_MEMORY_REGION_ATTRIBUTE_DEVICE;
// Map the FV region as normal executable memory
VirtualMemoryTable[++Idx].PhysicalBase = PcdGet64 (PcdFvBaseAddress);
VirtualMemoryTable[Idx].VirtualBase = VirtualMemoryTable[Idx].PhysicalBase;

View file

@ -27,8 +27,6 @@
[LibraryClasses]
ArmLib
BaseLib
BaseMemoryLib
DebugLib
MemoryAllocationLib
PcdLib
@ -37,6 +35,7 @@
gArmTokenSpaceGuid.PcdFvBaseAddress
gArmTokenSpaceGuid.PcdSystemMemoryBase
gArmTokenSpaceGuid.PcdSystemMemorySize
gEfiMdeModulePkgTokenSpaceGuid.PcdSerialRegisterBase
[FixedPcd]
gArmTokenSpaceGuid.PcdFvSize

View file

@ -9,6 +9,7 @@
#include <PiPei.h>
#include <Library/BaseLib.h>
#include <Library/BaseMemoryLib.h>
#include <Library/MemoryAllocationLib.h>
#include <Library/DebugLib.h>
@ -17,10 +18,61 @@
#include <Library/PcdLib.h>
#include <Library/PeiServicesLib.h>
#include <Library/FdtSerialPortAddressLib.h>
#include <Library/QemuFwCfgSimpleParserLib.h>
#include <Guid/EarlyPL011BaseAddress.h>
#include <Guid/FdtHob.h>
//
// Duplicated in ArmVirtPkg/Library/DebugLibFdtPL011Uart/Flash.c —
// keep both copies in sync.
//
/**
Parse a serial debug level string.
Accepted values are "silent" (DEBUG_ERROR only), "verbose" (no
override), or a hex bitmask (e.g. "0x80000040").
@param[in] String NUL-terminated ASCII string to parse.
@param[out] DebugLevel On success, the parsed debug level bitmask.
@retval TRUE String was recognised; *DebugLevel is valid.
@retval FALSE String is NULL, "verbose", or unrecognised; no override.
**/
STATIC
BOOLEAN
ParseSerialDebugLevel (
IN CONST CHAR8 *String,
OUT UINT32 *DebugLevel
)
{
UINT64 Value;
CHAR8 *End;
if ((String == NULL) || (DebugLevel == NULL)) {
return FALSE;
}
if (AsciiStrCmp (String, "silent") == 0) {
*DebugLevel = DEBUG_ERROR;
return TRUE;
}
if (AsciiStrCmp (String, "verbose") == 0) {
return FALSE;
}
if (!EFI_ERROR (AsciiStrHexToUint64S (String, &End, &Value)) &&
(*End == '\0'))
{
*DebugLevel = (UINT32)Value;
return TRUE;
}
return FALSE;
}
STATIC CONST EFI_PEI_PPI_DESCRIPTOR mTpm2DiscoveredPpi = {
EFI_PEI_PPI_DESCRIPTOR_PPI | EFI_PEI_PPI_DESCRIPTOR_TERMINATE_LIST,
&gOvmfTpmDiscoveredPpiGuid,
@ -56,6 +108,9 @@ PlatformPeim (
CONST UINT32 *RangesProp;
UINT64 TpmBase;
EFI_STATUS Status;
CHAR8 DebugLevelBuf[32];
UINTN DebugLevelBufSize;
CONST CHAR8 *DebugLevelStr;
Base = (VOID *)(UINTN)PcdGet64 (PcdDeviceTreeInitialBaseAddress);
ASSERT (Base != NULL);
@ -124,6 +179,23 @@ PlatformPeim (
));
}
DebugLevelBufSize = sizeof (DebugLevelBuf);
Status = QemuFwCfgGetAsString (
"opt/org.tianocore/DebugLevel",
&DebugLevelBufSize,
DebugLevelBuf
);
if (!RETURN_ERROR (Status)) {
DebugLevelStr = DebugLevelBuf;
} else {
DebugLevelStr = (CONST CHAR8 *)PcdGetPtr (PcdSerialDebugPrintErrorLevel);
}
UartHobData->DebugLevelSet = ParseSerialDebugLevel (
DebugLevelStr,
&UartHobData->DebugLevel
);
TpmBase = 0;
//

View file

@ -30,6 +30,7 @@
gArmVirtTokenSpaceGuid.PcdTpm2SupportEnabled
[LibraryClasses]
BaseLib
BaseMemoryLib
DebugLib
HobLib
@ -37,9 +38,11 @@
FdtSerialPortAddressLib
PcdLib
PeiServicesLib
QemuFwCfgSimpleParserLib
[FixedPcd]
gArmTokenSpaceGuid.PcdFvSize
gArmVirtTokenSpaceGuid.PcdSerialDebugPrintErrorLevel
gUefiOvmfPkgTokenSpaceGuid.PcdDeviceTreeAllocationPadding
[Pcd]

View file

@ -17,7 +17,7 @@ from edk2toolext.invocables.edk2_update import UpdateSettingsManager
from edk2toolext.invocables.edk2_pr_eval import PrEvalSettingsManager
from edk2toollib.utility_functions import RunCmd
from edk2toollib.utility_functions import GetHostInfo
from pathlib import Path
# ####################################################################################### #
# Configuration for Update & Setup #
@ -236,11 +236,33 @@ class PlatformBuilder(UefiBuilder, BuildSettingsManager):
# Common Args
args += CommonPlatform.FvQemuArg + Built_FV # path to fw
args += " -m 1024" # 1gb memory
# turn off network
args += " -net none"
# Serial messages out
args += " -serial stdio"
path_to_os = self.env.GetValue("PATH_TO_OS")
if path_to_os is not None:
args += f" -m 8192" # 8gb memory for OS
file_extension = Path(path_to_os).suffix.lower().replace('"', '')
storage_format = {
".vhd": "raw",
".qcow2": "qcow2",
".iso": "iso",
}.get(file_extension, None)
if storage_format is None:
raise Exception(f"Unknown OS storage type: {path_to_os}")
if storage_format == "iso":
args += f" -cdrom \"{path_to_os}\""
else:
args += f" -drive file=\"{path_to_os}\",format={storage_format},if=none,id=os_nvme"
args += " -device nvme,serial=nvme-1,drive=os_nvme,bootindex=0"
else:
args += " -m 1024" # 1gb memory
# Mount disk with startup.nsh
args += f" -drive file=fat:rw:{VirtualDrive},format=raw,media=disk"
# Provides Rng services to the Guest VM

View file

@ -1,5 +1,5 @@
//
// Copyright (c) 2011-2013, ARM Limited. All rights reserved.
// Copyright (c) 2011-2026, ARM Limited. All rights reserved.
// Copyright (c) 2015-2016, Linaro Limited. All rights reserved.
//
// SPDX-License-Identifier: BSD-2-Clause-Patent
@ -20,6 +20,12 @@ ASM_FUNC(_ModuleEntryPoint)
0:mov x28, x0 // preserve DTB pointer
mov x27, x1 // preserve base of image pointer
// The TPIDR_EL0 register is used to store the HobList pointer.
// The register value is unknown at reset, so clear the register
// to prevent early callers of GetHobList(), i.e. before the HOB list
// has been setup in PrePiMain() from getting an invalid value.
msr tpidr_el0, xzr
// Enable Floating Point. This needs to be done before entering C code, which
// may use FP/SIMD registers.
bl ArmEnableVFP

362
BREAKING-CHANGES.md Normal file
View file

@ -0,0 +1,362 @@
# EDK II Breaking Changes
This file is the in-tree record of breaking changes in EDK II. Each breaking change has a single entry that is added
in the pull request that introduces the change and updated in any later pull request that changes its state. The file
is organized by stable tag milestone with most recent first.
Within a given section, each breaking change is added after existing entries so they are in chronological merge order
within the section.
For the full process, including the breaking change taxonomy, deprecation timeline, required entry content, and GitHub
issue requirements, see the [Breaking Change and Release Process for EDK II](https://raw.githubusercontent.com/tianocore/tianocore-wiki.github.io/refs/heads/main/rfc/text/0003-edk2-breaking-change-and-release-process.md)
RFC.
## edk2-stable202702
- Milestone: [edk2-stable202702](https://github.com/tianocore/edk2/milestone/7)
### edk2-stable202702: Source-Level Breaking Changes
#### edk2-stable202702: Changes with Removal
None
#### edk2-stable202702: Changes without Removal
None
### edk2-stable202702: Behavioral Breaking Changes
None
### edk2-stable202702: Build-System Breaking Changes
None
---
## edk2-stable202611
- Milestone: [edk2-stable202611](https://github.com/tianocore/edk2/milestone/6)
### edk2-stable202611: Source-Level Breaking Changes
#### edk2-stable202611: Changes with Removal
None
#### edk2-stable202611: Changes without Removal
None
### edk2-stable202611: Behavioral Breaking Changes
None
### edk2-stable202611: Build-System Breaking Changes
None
---
## edk2-stable202608
- Milestone: [edk2-stable202608](https://github.com/tianocore/edk2/milestone/5)
> Note: The entries below with "N/A" issues were merged during the edk2-stable202608 development period
> (after the `edk2-stable202605 tag`) and before the breaking change process took effect. They therefore have no
> associated GitHub Tracking, Deprecation, or Removal issues. Each entry links to the pull request that introduced
> the change in place of those issues. This is expected to be a one-time occurrence during the transition to the new
> breaking changes process during the `edk2-stable202608` development period.
### edk2-stable202608: Source-Level Breaking Changes
#### edk2-stable202608: Changes with Removal
##### Breaking Change: AArch64 exception handling relocated from ArmPkg to UefiCpuPkg
- **Status**: Removed
- **Tracking Issue**: N/A (merged before the breaking change process took effect)
- **Deprecation Issue**: N/A
- **Removal Issue**: N/A
- **Pull Request**: [tianocore/edk2#12340](https://github.com/tianocore/edk2/pull/12340)
- **Type**: Source-Level (Removal) - Library class restructure, API removal, and header file removal
**What changed**: AArch64 exception handling was moved from `ArmPkg` to `UefiCpuPkg`. `ArmExceptionLib` and
`DefaultExceptionHandlerLib` were merged into `CpuExceptionHandlerLib`, the `DefaultExceptionHandler()` API was renamed
to `DumpCpuContext()`, and the `ArmPkg/Include/Library/DefaultExceptionHandlerLib.h` public header was removed.
**What is removed**: The `ArmPkg` `ArmExceptionLib` and `DefaultExceptionHandlerLib` library instances, the
`DefaultExceptionHandlerLib.h` public header, and the `DefaultExceptionHandler()` API.
**Why it changed**: To provide consistent exception handling across all CPU architectures (IA32, X64, LoongArch64,
RISCV64, AARCH64) by unifying on the `UefiCpuPkg` `CpuExceptionHandlerLib`.
**What replaces it**: The `UefiCpuPkg` `CpuExceptionHandlerLib` (for example, `DxeCpuExceptionHandlerLib.inf`) and the
`DumpCpuContext()` API declared in the `UefiCpuPkg` `CpuExceptionLib.h` interface.
**How to migrate**: For out-of-tree modules that used `DefaultExceptionHandlerLib`, add `UefiCpuPkg.dec` as a package
dependency and update the platform DSC to map the exception handling library class to `CpuExceptionHandlerLib`. Replace
all `DefaultExceptionHandler()` calls with `DumpCpuContext()`. Remove all references of `ArmExceptionLib` from the DSC
file.
**Breaking conditions**: Affects AArch64 (ARM) platforms and out-of-tree modules that consumed `ArmExceptionLib`,
`DefaultExceptionHandlerLib`, or the `DefaultExceptionHandler()` API.
**Earliest removal**: Already removed in this change. The old code was removed in the same PR with no compatibility window.
##### Breaking Change: PrePiLib FfsFindSectionDataWithHook and FfsProcessFvFile gain new parameters
- **Status**: Removed
- **Tracking Issue**: N/A (merged before the breaking change process took effect)
- **Deprecation Issue**: N/A
- **Removal Issue**: N/A
- **Pull Request**: [tianocore/edk2#12672](https://github.com/tianocore/edk2/pull/12672)
- **Type**: Source-Level (Removal) - API signature change
**What changed**: `EmbeddedPkg` `PrePiLib` API signatures changed to improve FV2/FV3 HOB handling.
`FfsFindSectionDataWithHook()` gained an `AuthenticationStatus` output parameter and `FfsProcessFvFile()` gained a
`ParentVolumeHandle` parameter. In addition, `PrePi.h` dropped duplicate HOB definitions in favor of `HobLib.h`.
**What is removed**: The previous `FfsFindSectionDataWithHook()` and `FfsProcessFvFile()` function signatures.
**Why it changed**: To correctly produce FV3 HOBs (which supersede FV2 HOBs) for extracted FVs and to set the FV2 HOB
`FvName` to the parent FV name so DXE does not re-extract already-extracted FVs (a performance hit of approximately one
second on some platforms). Producing the FV3 HOB requires the authentication status from the GUIDed extraction, and
correct FV2 HOB production requires the parent FV handle.
**What replaces it**: The same functions with the new signatures.
**How to migrate**: Update callers of `FfsFindSectionDataWithHook()` to pass the new `AuthenticationStatus` argument
(pass `NULL` to retain existing behavior, or a `UINT32 *` to receive the status). Update callers of
`FfsProcessFvFile()` to pass the `ParentVolumeHandle`.
**Breaking conditions**: Affects modules that call `PrePiLib`'s `FfsFindSectionDataWithHook()` or `FfsProcessFvFile()`
(for example, `EmbeddedPkg` and `OvmfPkg` peiless startup consumers).
**Earliest removal**: Already removed in this change. The old signatures were replaced in the same PR with no
compatibility window.
##### Breaking Change: BaseRiscV64CpuTimerLib renamed and split into SEC and DXE TimerLib instances
- **Status**: Removed
- **Tracking Issue**: N/A (merged before the breaking change process took effect)
- **Deprecation Issue**: N/A
- **Removal Issue**: N/A
- **Pull Request**: [tianocore/edk2#12210](https://github.com/tianocore/edk2/pull/12210)
- **Type**: Source-Level (Removal) - Library class restructure
**What changed**: The `UefiCpuPkg` `BaseRiscV64CpuTimerLib` was renamed to `RiscV64CpuTimerLib` and split into two
instances: `RiscV64CpuTimerSecLib.inf` (`MODULE_TYPE` `SEC`, for SEC and PEI, no constructor) and
`RiscV64CpuTimerDxeLib.inf` (for `DXE_CORE`, `DXE_DRIVER`, and other DXE-phase modules, which retains the constructor).
The old `UefiCpuPkg/Library/BaseRiscV64CpuTimerLib/BaseRiscV64CpuTimerLib.inf` path was removed.
**What is removed**: The `BaseRiscV64CpuTimerLib` library instance and its INF path.
**Why it changed**: The library constructor calls `GetPerformanceCounterProperties()`, which requires the HOB list. In
the SEC and PEI phases the HOB list may not yet be available, causing a crash. Splitting the instances runs the
constructor only in the DXE instance.
**What replaces it**: The phase-specific instances `RiscV64CpuTimerSecLib.inf` (SEC and PEI) and
`RiscV64CpuTimerDxeLib.inf` (DXE).
**How to migrate**: Update platform DSC `TimerLib` mappings that referenced
`UefiCpuPkg/Library/BaseRiscV64CpuTimerLib/BaseRiscV64CpuTimerLib.inf`. Map `TimerLib` to `RiscV64CpuTimerSecLib.inf`
for SEC and PEI modules and to `RiscV64CpuTimerDxeLib.inf` for DXE modules.
**Breaking conditions**: Affects RISC-V (RISCV64) platforms that consume the RISC-V CPU timer library.
**Earliest removal**: Already removed in this change. The old INF path was removed in the same PR with no compatibility
window.
##### Breaking Change: TPM2 helper functions moved to new Tpm2HelpLib library class
- **Status**: Deprecation Active
- **Tracking Issue**: [tianocore/edk2#12797](https://github.com/tianocore/edk2/issues/12797)
- **Deprecation Issue**: [tianocore/edk2#12799](https://github.com/tianocore/edk2/issues/12799)
- **Pull Request**: [tianocore/edk2#11634](https://github.com/tianocore/edk2/pull/11634)
- **Type**: Source-Level (Non-removal) - Library class dependency addition (single expected instance)
**What changed**: The TPM2 helper functions in `Tpm2Help.c` were decoupled from `Tpm2CommandLib` into a new standalone
`SecurityPkg` library class, `Tpm2HelpLib`. This allows using the helpers without pulling in `Tpm2CommandLib` and
`Tpm2DeviceLib`, which are tied to TPM communication. In-tree modules (for example, `HashLibBaseCryptoRouter`,
`PeilessSecMeasureLib`, and `TdTcg2Dxe`) were updated to consume `Tpm2HelpLib`.
**Library class dependency case**: Single expected instance. `SecurityPkg` provides the single recommended instance at
`SecurityPkg/Library/Tpm2HelpLib/Tpm2HelpLib.inf`, so migration is a DSC library class mapping.
**Why it changed**: Some callers need the helper functions without TPM communication dependencies. Examples include
generating a HOB for pre-DXE measurements and the SEC phase, where there is no `Tpm2DeviceLib`.
**What replaces it**: The `Tpm2HelpLib` library class. The helper functions remaining in `Tpm2CommandLib`'s
`Tpm2Help.c` are now deprecated wrappers that delegate to `Tpm2HelpLib`.
**How to migrate**: Platforms building modules that now depend on `Tpm2HelpLib` must add a mapping in their DSC
(`Tpm2HelpLib|SecurityPkg/Library/Tpm2HelpLib/Tpm2HelpLib.inf`) or the build fails with an unresolved library class. For
code, add `Tpm2HelpLib` to the module INF and include the header, then update calls to the deprecated `Tpm2Help.c`
wrappers in `Tpm2CommandLib` to use the `Tpm2HelpLib` versions.
**Earliest removal**: The deprecated `Tpm2CommandLib` `Tpm2Help.c` wrappers may be removed in a future stable tag. A
removal stable tag has not been scheduled at this time.
> Note: GitHub issues were created to track edk2-platforms following migration instructions.
>
> - [Platform/ARM: Switch to Tpm2HelpLib](https://github.com/tianocore/edk2-platforms/issues/994)
> - [Platform/MinPlatformPkg: Switch to Tpm2HelpLib](https://github.com/tianocore/edk2-platforms/issues/995)
> - [Silicon/Ampere/AmpereAltraPkg: Switch to Tpm2HelpLib](https://github.com/tianocore/edk2-platforms/issues/996)
#### edk2-stable202608: Changes without Removal
##### Breaking Change: New GptLib library class dependency
- **Status**: Announced
- **Tracking Issue**: [tianocore/edk2#12808](https://github.com/tianocore/edk2/issues/12808)
- **Pull Request**: [tianocore/edk2#12745](https://github.com/tianocore/edk2/pull/12745)
**Type**: Source-Level (Non-removal) - Library class dependency addition
(single expected instance)
**What changed**: PartitionDxe, DxeTpm2MeasureBootLib and
DxeTpmMeasureBootLib gained a required dependency on the new GptLib library
class declared in MdeModulePkg. Platforms that build any of these modules
must resolve GptLib in their DSC or the build fails with an unresolved
library class.
**Why it changed**: As reported in CVE-2024-13745, DxeTpm2MeasureBootLib
could measure a GPT partition table that differs from the one parsed and
used by PartitionDxe, because the two components carried independent GPT
parsing logic. GptLib consolidates GPT parsing and validation so the
partition table measured into PCR[5] is validated by the same logic the
firmware uses.
**What replaces it**: Nothing is removed. A single canonical GptLib
instance is provided in-tree (MdeModulePkg/Library/GptLib/GptLib.inf).
**How to migrate**: Add the following mapping to the platform DSC
[LibraryClasses] section:
GptLib|MdeModulePkg/Library/GptLib/GptLib.inf
### edk2-stable202608: Behavioral Breaking Changes
None
### edk2-stable202608: Build-System Breaking Changes
#### Breaking Change: GenFv ForceRebase now honors a per-module Xip flag
- **Status**: Removed
- **Tracking Issue**: N/A (merged before the breaking change process took effect)
- **Deprecation Issue**: N/A
- **Removal Issue**: N/A
- **Pull Request**: [tianocore/edk2#12551](https://github.com/tianocore/edk2/pull/12551)
- **Type**: Build-System - DSC/INF/DEC syntax change and BaseTools change
**What changed**: Previously the `GenFv` rebase feature (`ForceRebase=1`, that is `FvForceRebase=TRUE`) was
all-or-nothing: it rebased every eligible FFS file in the firmware volume to the FV base address, with no way to
selectively rebase only XIP modules. A new `Xip=TRUE/FALSE` keyword was added to the FDF `[Rule]` section PE32/TE
section syntax so specific module types can be tagged for XIP rebase.
```text
[Rule.Common.PEI_CORE]
FILE PEI_CORE = $(NAMED_GUID) {
PE32 PE32 Align=Auto Xip=TRUE $(INF_OUTPUT)/$(MODULE_NAME).efi
}
```
When `ForceRebase=1`, `GenFv` now rebases only modules whose type is tagged `Xip=TRUE`; a module type with no `Xip`
keyword defaults to not being rebased. The eligible file types considered for rebase are `SECURITY_CORE`, `PEI_CORE`,
`PEIM`, `COMBINED_PEIM_DRIVER`, `DRIVER`, and `DXE_CORE`. Per-module (rather than per-type) control is available by
defining named `XIP`/`NOXIP` rules and selecting them with `RuleOverride` in the `[FV]` section:
```text
[Rule.Common.PEIM.XIP]
FILE PEIM = $(NAMED_GUID) {
PE32 PE32 Align=Auto Xip=TRUE $(INF_OUTPUT)/$(MODULE_NAME).efi
}
[Rule.Common.PEIM.NOXIP]
FILE PEIM = $(NAMED_GUID) {
PE32 PE32 Align=Auto $(INF_OUTPUT)/$(MODULE_NAME).efi
}
[FV.PEIFV]
INF RuleOverride=XIP MdeModulePkg/Core/Pei/PeiMain.inf
INF RuleOverride=NOXIP SomePkg/SomePeim/SomePeim.inf
```
**`FvForceRebase` rebase decision table**
| FvForceRebase | FvBaseAddress | Xip in any Rule | Result |
| :---: | :---: | :---: | :--- |
| `TRUE` | any | No files have `Xip=TRUE` | Rebase ALL eligible files (legacy) |
| `TRUE` | any | At least one file has `Xip=TRUE` | Rebase ONLY files with `Xip=TRUE` |
| `FALSE` | any | any | No rebase |
| not specified | != 0 | any | Rebase ALL eligible files (legacy) |
| not specified | == 0 or not specified | any | No rebase |
**Detailed changes**: The pull request description has a detailed explanation of the change and its motivation that
readers may find useful: [tianocore/edk2#12551](https://github.com/tianocore/edk2/pull/12551).
**Why it changed**: Only XIP (execute-in-place) modules (for example, `PEI_CORE` and `PEIM`) need PE32 address fixups to
their flash location. Rebasing non-XIP modules (for example, `DXE_CORE` and `DRIVER`) is unnecessary and can cause
issues. This provides finer-grained control than the all-or-nothing `ForceRebase`.
**What replaces it**: The `Xip` keyword in FDF `[Rule]` sections used together with `ForceRebase`.
**How to migrate**: The selective rebase only activates for an FV once at least one of its `[Rule]` sections uses
`Xip=TRUE`. Platforms that relied on `ForceRebase=1` rebasing all eligible modules and do not use `Xip=TRUE` anywhere
in the FV are unaffected. Platforms adopting selective rebase must add `Xip=TRUE` to the relevant `[Rule]` sections
(for example, the `PEI_CORE` and `PEIM` rules) so those modules continue to be rebased. Module types without
`Xip=TRUE` will not be rebased once any rule in the FV uses `Xip=TRUE`. For per-module rather than per-type control,
define named `XIP`/`NOXIP` rules and select them with `RuleOverride`.
**Breaking conditions**: The new `Xip` filter only applies when `ForceRebase=1` (`FvForceRebase=TRUE`) **and** at
least one FFS file in the FV is produced by a `[Rule]` section with `Xip=TRUE`. If no rule in the FV uses
`Xip=TRUE`, `ForceRebase=1` continues to rebase all eligible files, matching pre-#12551 behavior. The default
behavior is unchanged: when `ForceRebase` is unspecified with a non-zero FV base address, all eligible files are still
rebased unconditionally and the `Xip` keyword is not consulted. When `ForceRebase=0`, nothing is rebased regardless of
`Xip`.
**Earliest removal**: Already in effect in this change. The previous "rebase all" behavior was replaced in the same PR
with no compatibility window.
> Note: [tianocore/edk2#12807](https://github.com/tianocore/edk2/pull/12807) fixed a backward-compatibility
> regression introduced by this change, in which `FvForceRebase=TRUE` stopped rebasing any files in an FV when no
> `[Rule]` section in that FV specified `Xip=TRUE`. The fix tracks the count of `Xip=TRUE` files per FV and only
> enables the selective rebase logic when that count is greater than zero. Otherwise the legacy "rebase all" behavior
> is preserved. The **Breaking conditions** and **How to migrate** guidance above reflect the behavior after this
> fix.
#### Breaking Change: Visual Studio 2015 and 2017 toolchain support removed
- **Status**: Removed
- **Tracking Issue**: N/A (merged before the breaking change process took effect)
- **Deprecation Issue**: N/A
- **Removal Issue**: N/A
- **Pull Request**: [tianocore/edk2#12683](https://github.com/tianocore/edk2/pull/12683)
- **Type**: Build-System - Tool version requirement
**What changed**: Support for the `VS2015` and `VS2017` toolchains was removed from the repository. This removed the
`VS2015` and `VS2017` toolchain definitions from `BaseTools/Conf/tools_def.template`, the associated environment setup
logic in `toolsetup.bat`, `set_vsprefix_envs.bat`, `get_vsvars.bat`, and `edksetup.bat`, the `VS2017` configuration in
the `WindowsVsToolChain` build plugin, the `VS2015`-specific `CryptoPkg` compiler flags, the `EmulatorPkg` `VS2017`
Visual Studio solution, and the unused `ShowEnvironment.bat` and `SetVisualStudio.bat` helper scripts. The oldest
supported Visual Studio toolchain is now `VS2019`.
**What is removed**: The `VS2015` and `VS2017` toolchain definitions and their supporting scripts and build options.
**Why it changed**: To reduce maintenance burden and align on newer, supported toolchains. Visual Studio 2015
mainstream support ended on October 13, 2020 and extended support ended on October 14, 2025. Visual Studio 2017 is past
its mainstream support end date.
**What replaces it**: The `VS2019`, `VS2022`, and `VS2026` toolchains.
**How to migrate**: Developers building locally with the `VS2015` or `VS2017` toolchain must move to a newer Visual
Studio version (`VS2019` is the next supported version).
**Breaking conditions**: Only affects Windows developers and CI environments that build with the `VS2015` or `VS2017`
toolchain.
**Earliest removal**: Already removed in this change. The toolchains were removed in the same PR with no compatibility
window.

View file

@ -16,6 +16,6 @@
"type": "nuget",
"name": "edk2-acpica-iasl",
"source": "https://pkgs.dev.azure.com/projectmu/acpica/_packaging/mu_iasl/nuget/v3/index.json",
"version": "20200717.0.0",
"version": "20230628.0.1",
"flags": ["set_path", "host_specific"]
}

View file

@ -290,7 +290,7 @@
<Command.GCC>
$(RM) ${dst}
"$(SLINK)" cr ${dst} $(SLINK_FLAGS) @$(OBJECT_FILES_LIST)
<Command.XCODE>
"$(SLINK)" $(SLINK_FLAGS) ${dst} -filelist $(OBJECT_FILES_LIST)
@ -321,8 +321,8 @@
<Command.XCODE>
"$(DLINK)" $(DLINK_FLAGS) -o ${dst} $(DLINK_SPATH) -filelist $(STATIC_LIBRARY_FILES_LIST) $(DLINK2_FLAGS)
[Static-Library-File.SEC, Static-Library-File.PEI_CORE, Static-Library-File.PEIM]
<InputFile>
*.lib
@ -387,8 +387,8 @@
<Command.XCODE>
"$(DLINK)" -o ${dst} $(DLINK_FLAGS) $(DLINK_SPATH) -filelist $(STATIC_LIBRARY_FILES_LIST) $(DLINK2_FLAGS)
[Dynamic-Library-File]
<InputFile>
?.dll
@ -403,7 +403,7 @@
$(CP) ${dst} $(DEBUG_DIR)
$(CP) ${dst} $(BIN_DIR)(+)$(MODULE_NAME_GUID).efi
-$(CP) $(DEBUG_DIR)(+)*.map $(OUTPUT_DIR)
-$(CP) $(DEBUG_DIR)(+)*.pdb $(OUTPUT_DIR)
-$(CP) $(DEBUG_DIR)(+)*.pdb $(OUTPUT_DIR)
<Command.GCC, Command.CLANGDWARF>
$(CP) ${src} $(DEBUG_DIR)(+)$(MODULE_NAME).debug
@ -420,7 +420,7 @@
$(CP) ${dst} $(BIN_DIR)(+)$(MODULE_NAME_GUID).efi
-$(CP) $(DEBUG_DIR)(+)*.map $(OUTPUT_DIR)
-$(CP) $(DEBUG_DIR)(+)*.pdb $(OUTPUT_DIR)
<Command.XCODE>
# tool to convert Mach-O to PE/COFF
"$(MTOC)" -subsystem $(MODULE_TYPE) $(MTOC_FLAGS) ${src} $(DEBUG_DIR)(+)$(MODULE_NAME).pecoff
@ -460,14 +460,14 @@
<Command.MSFT, Command.INTEL>
Trim --asl-file --asl-deps -o $(OUTPUT_DIR)(+)${s_dir}(+)${s_base}.i -i $(INC_LIST) ${src}
"$(ASLPP)" $(DEPS_FLAGS) $(ASLPP_FLAGS) $(INC) /I${s_path} $(OUTPUT_DIR)(+)${s_dir}(+)${s_base}.i > $(OUTPUT_DIR)(+)${s_dir}(+)${s_base}.iii
Trim --source-code -l -o $(OUTPUT_DIR)(+)${s_dir}(+)${s_base}.iiii $(OUTPUT_DIR)(+)${s_dir}(+)${s_base}.iii
Trim --source-code -l -o $(OUTPUT_DIR)(+)${s_dir}(+)${s_base}.iiii $(OUTPUT_DIR)(+)${s_dir}(+)${s_base}.iii
"$(ASL)" $(ASL_FLAGS) $(ASL_OUTFLAGS)${dst} $(OUTPUT_DIR)(+)${s_dir}(+)${s_base}.iiii
$(CP) $(OUTPUT_DIR)(+)${s_dir}(+)${s_base}.aml $(OUTPUT_DIR)(+)${s_dir}(+)${s_base}.amli
<Command.GCC>
Trim --asl-file --asl-deps -o $(OUTPUT_DIR)(+)${s_dir}(+)${s_base}.i -i $(INC_LIST) ${src}
"$(ASLPP)" $(DEPS_FLAGS) $(ASLPP_FLAGS) $(INC) -I${s_path} $(OUTPUT_DIR)(+)${s_dir}(+)${s_base}.i > $(OUTPUT_DIR)(+)${s_dir}(+)${s_base}.iii
Trim --source-code -l -o $(OUTPUT_DIR)(+)${s_dir}(+)${s_base}.iiii $(OUTPUT_DIR)(+)${s_dir}(+)${s_base}.iii
Trim --source-code -l -o $(OUTPUT_DIR)(+)${s_dir}(+)${s_base}.iiii $(OUTPUT_DIR)(+)${s_dir}(+)${s_base}.iii
"$(ASL)" $(ASL_FLAGS) $(ASL_OUTFLAGS)${dst} $(OUTPUT_DIR)(+)${s_dir}(+)${s_base}.iiii
$(CP) $(OUTPUT_DIR)(+)${s_dir}(+)${s_base}.aml $(OUTPUT_DIR)(+)${s_dir}(+)${s_base}.amli
@ -531,13 +531,13 @@
"$(ASLDLINK)" /OUT:$(OUTPUT_DIR)(+)${s_dir}(+)${s_base}.dll $(ASLDLINK_FLAGS) $(OUTPUT_DIR)(+)${s_dir}(+)${s_base}.obj
"$(GENFW)" -o ${dst} -c $(OUTPUT_DIR)(+)${s_dir}(+)${s_base}.dll $(GENFW_FLAGS)
<Command.XCODE>
<Command.XCODE>
"$(ASLCC)" $(DEPS_FLAGS) -o $(OUTPUT_DIR)(+)${s_dir}(+)${s_base}.obj $(ASLCC_FLAGS) $(DEPS_FLAGS) $(INC) ${src}
"$(ASLDLINK)" -o $(OUTPUT_DIR)(+)${s_dir}(+)${s_base}.dll $(ASLDLINK_FLAGS) $(OUTPUT_DIR)(+)${s_dir}(+)${s_base}.obj
"$(MTOC)" -subsystem $(MODULE_TYPE) $(MTOC_FLAGS) $(OUTPUT_DIR)(+)${s_dir}(+)${s_base}.dll $(OUTPUT_DIR)(+)${s_dir}(+)${s_base}.pecoff
"$(GENFW)" -o ${dst} -c $(OUTPUT_DIR)(+)${s_dir}(+)${s_base}.pecoff $(GENFW_FLAGS)
[Masm16-Code-File]
<InputFile>
?.asm16, ?.Asm16, ?.ASM16, ?.s16, ?.S16
@ -562,7 +562,7 @@
Trim --source-code -o ${d_path}(+)${s_base}.iii ${d_path}(+)${s_base}.ii
"$(ASM)" -o $(OUTPUT_DIR)(+)${s_dir}(+)${s_base}.obj $(ASM_FLAGS) $(INC) ${d_path}(+)${s_base}.iii
"$(DLINK)" -o ${dst} $(DLINK_FLAGS) --start-group $(DLINK_SPATH) $(LIBS) $(OUTPUT_DIR)(+)${s_dir}(+)${s_base}.obj --end-group
<Command.XCODE>
Trim --asm-file -o ${d_path}(+)${s_base}.i -i $(INC_LIST) ${src}
"$(PP)" $(DEPS_FLAGS) $(PP_FLAGS) $(INC) ${src} > ${d_path}(+)${s_base}.ii
@ -570,7 +570,7 @@
"$(ASM)" -o $(OUTPUT_DIR)(+)${s_dir}(+)${s_base}.obj $(ASM_FLAGS) $(INC) ${d_path}(+)${s_base}.iii
"$(SLINK)" $(SLINK_FLAGS) $(OUTPUT_DIR)(+)${s_dir}(+)${s_base}.slib $(OUTPUT_DIR)(+)${s_dir}(+)${s_base}.obj
otool -t $(OUTPUT_DIR)(+)${s_dir}(+)${s_base}.slib | hex2bin.py ${dst}
[Nasm-to-Binary-Code-File]
<InputFile>

View file

@ -27,28 +27,22 @@
# 3.05 - Add CLANGPDB AARCH64 Support
# 3.06 - Remove GCC48, GCC49 and GCC5
# 3.07 - Switch alignemnt to 4k for X64 builds add XIP_FLAGS.
# - Add --apply-dynamic-relocs option for AARCH64 CLANGDWARF builds
# - Add missing CLANGDWARF OBJCOPY_FLAGS
# - Canonicalize CLANGDWARF definitions
# - Align X64 CLANGDWARF and CLANGPDB definitions
# - Add GENFWHII_FLAGS to fix VS2026 GenFw build issue
# - Add -malign-double to IA32 ASLCC_FLAGS
# - Add CLANGDWARF support for LoongArch64
#4.00 - Remove VS2015 support
#4.01 - Remove VS2017 support
#
#!VERSION=3.06
#!VERSION=4.01
IDENTIFIER = Default TOOL_CHAIN_CONF
# common path macros
DEFINE VS2015_BIN = ENV(VS2015_PREFIX)Vc\bin
DEFINE VS2015_DLL = ENV(VS2015_PREFIX)Common7\IDE;DEF(VS2015_BIN)
DEFINE VS2015_BINX64 = DEF(VS2015_BIN)\x86_amd64
DEFINE VS2015x86_BIN = ENV(VS2015_PREFIX)Vc\bin
DEFINE VS2015x86_DLL = ENV(VS2015_PREFIX)Common7\IDE;DEF(VS2015x86_BIN)
DEFINE VS2015x86_BINX64 = DEF(VS2015x86_BIN)\x86_amd64
DEFINE VS_HOST = x86
DEFINE VS2017_BIN = ENV(VS2017_PREFIX)bin
DEFINE VS2017_BIN_HOST = DEF(VS2017_BIN)\HostDEF(VS_HOST)\DEF(VS_HOST)
DEFINE VS2017_BIN_IA32 = DEF(VS2017_BIN)\HostDEF(VS_HOST)\x86
DEFINE VS2017_BIN_X64 = DEF(VS2017_BIN)\HostDEF(VS_HOST)\x64
DEFINE VS2017_BIN_AARCH64 = DEF(VS2017_BIN)\HostDEF(VS_HOST)\arm64
DEFINE VS2019_BIN = ENV(VS2019_PREFIX)bin
DEFINE VS2019_BIN_HOST = DEF(VS2019_BIN)\HostDEF(VS_HOST)\DEF(VS_HOST)
DEFINE VS2019_BIN_IA32 = DEF(VS2019_BIN)\HostDEF(VS_HOST)\x86
@ -75,10 +69,6 @@ DEFINE RC_PATH = ENV(WINSDK_PATH_FOR_RC_EXE)\rc.exe
DEFINE WINSDK_BIN = ENV(WINSDK_PREFIX)
DEFINE WINSDKx86_BIN = ENV(WINSDKx86_PREFIX)
# Microsoft Visual Studio 2015 Professional Edition
DEFINE WINSDK81_BIN = ENV(WINSDK81_PREFIX)x64
DEFINE WINSDK81x86_BIN = ENV(WINSDK81x86_PREFIX)x86
# Microsoft Visual Studio 2017/2019/2022/2026 Professional Edition
DEFINE WINSDK10_BIN = ENV(WINSDK10_PREFIX)DEF(VS_HOST)
@ -146,21 +136,6 @@ DEFINE DTC_BIN = ENV(DTC_PREFIX)dtc
#
# Supported Tool Chains
# =====================
# VS2015 -win32- Requires:
# Microsoft Visual Studio 2015 Professional Edition, Update 3
# Optional:
# Required to build platforms or ACPI tables:
# Intel(r) ACPI Compiler (iasl.exe) from
# https://acpica.org/downloads
# VS2017 -win32- Requires:
# Microsoft Visual Studio 2017 version 15.2 (15.4 for ARM64) or later
# Optional:
# Required to build platforms or ACPI tables:
# Intel(r) ACPI Compiler (iasl.exe) from
# https://acpica.org/downloads
# Note:
# Building of XIP firmware images for ARM64 is not currently supported (only applications).
# /FILEALIGN:4096 and other changes are needed for ARM64 firmware builds.
# VS2019 -win32- Requires:
# Microsoft Visual Studio 2019 version 16.2 or later
# Optional:
@ -199,12 +174,6 @@ DEFINE DTC_BIN = ENV(DTC_PREFIX)dtc
# Required to compile nasm source:
# nasm compiler from
# NASM -- http://www.nasm.us/
# VS2015x86 -win64- Requires:
# Microsoft Visual Studio 2015 (x86) Update 3 or above
# Optional:
# Required to build platforms or ACPI tables:
# Intel(r) ACPI Compiler (iasl.exe) from
# https://acpica.org/downloads
#
####################################################################################
####################################################################################
@ -244,313 +213,6 @@ DEFINE DTC_BIN = ENV(DTC_PREFIX)dtc
#
####################################################################################
####################################################################################
#
# Microsoft Visual Studio 2015
#
# VS2015 - Microsoft Visual Studio 2015 Professional Edition with Intel ASL
# ASL - Intel ACPI Source Language Compiler
####################################################################################
# VS2015 - Microsoft Visual Studio 2015 Professional Edition
*_VS2015_*_*_FAMILY = MSFT
*_VS2015_*_MAKE_PATH = DEF(VS2015_BIN)\nmake.exe
*_VS2015_*_MAKE_FLAGS = /nologo
*_VS2015_*_RC_PATH = DEF(WINSDK81_BIN)\rc.exe
*_VS2015_*_SLINK_FLAGS = /NOLOGO /LTCG
*_VS2015_*_APP_FLAGS = /nologo /E /TC
*_VS2015_*_PP_FLAGS = /nologo /E /TC /FIAutoGen.h
*_VS2015_*_VFRPP_FLAGS = /nologo /E /TC /DVFRCOMPILE /FI$(MODULE_NAME)StrDefs.h
*_VS2015_*_DLINK2_FLAGS =
*_VS2015_*_DEPS_FLAGS = DEF(MSFT_DEPS_FLAGS)
*_VS2015_*_GENFWHII_FLAGS = --hiipackage
*_VS2015_*_ASM16_PATH = DEF(VS2015_BIN)\ml.exe
##################
# ASL definitions
##################
*_VS2015_*_ASL_PATH = DEF(DEFAULT_WIN_ASL_BIN)
*_VS2015_*_ASL_FLAGS = DEF(DEFAULT_WIN_ASL_FLAGS)
*_VS2015_*_ASL_OUTFLAGS = DEF(DEFAULT_WIN_ASL_OUTFLAGS)
*_VS2015_*_ASLCC_FLAGS = DEF(MSFT_ASLCC_FLAGS)
*_VS2015_*_ASLPP_FLAGS = DEF(MSFT_ASLPP_FLAGS)
*_VS2015_*_ASLDLINK_FLAGS = DEF(MSFT_ASLDLINK_FLAGS)
##################
# IA32 definitions
##################
*_VS2015_IA32_*_DLL = DEF(VS2015_DLL)
*_VS2015_IA32_CC_PATH = DEF(VS2015_BIN)\cl.exe
*_VS2015_IA32_VFRPP_PATH = DEF(VS2015_BIN)\cl.exe
*_VS2015_IA32_SLINK_PATH = DEF(VS2015_BIN)\lib.exe
*_VS2015_IA32_DLINK_PATH = DEF(VS2015_BIN)\link.exe
*_VS2015_IA32_APP_PATH = DEF(VS2015_BIN)\cl.exe
*_VS2015_IA32_PP_PATH = DEF(VS2015_BIN)\cl.exe
*_VS2015_IA32_ASM_PATH = DEF(VS2015_BIN)\ml.exe
*_VS2015_IA32_ASLCC_PATH = DEF(VS2015_BIN)\cl.exe
*_VS2015_IA32_ASLPP_PATH = DEF(VS2015_BIN)\cl.exe
*_VS2015_IA32_ASLDLINK_PATH = DEF(VS2015_BIN)\link.exe
DEBUG_VS2015_IA32_CC_FLAGS = /nologo /arch:IA32 /c /WX /GS- /W4 /Gs32768 /D UNICODE /O1b2 /GL /FIAutoGen.h /EHs-c- /GR- /GF /Gy /Z7 /Gw
RELEASE_VS2015_IA32_CC_FLAGS = /nologo /arch:IA32 /c /WX /GS- /W4 /Gs32768 /D UNICODE /O1b2 /GL /FIAutoGen.h /EHs-c- /GR- /GF /Gw
NOOPT_VS2015_IA32_CC_FLAGS = /nologo /arch:IA32 /c /WX /GS- /W4 /Gs32768 /D UNICODE /FIAutoGen.h /EHs-c- /GR- /GF /Gy /Z7 /Od
DEBUG_VS2015_IA32_ASM_FLAGS = /nologo /c /WX /W3 /Cx /coff /Zd /Zi
RELEASE_VS2015_IA32_ASM_FLAGS = /nologo /c /WX /W3 /Cx /coff /Zd
NOOPT_VS2015_IA32_ASM_FLAGS = /nologo /c /WX /W3 /Cx /coff /Zd /Zi
DEBUG_VS2015_IA32_NASM_FLAGS = -Ox -f win32 -g
RELEASE_VS2015_IA32_NASM_FLAGS = -Ox -f win32
NOOPT_VS2015_IA32_NASM_FLAGS = -O0 -f win32 -g
DEBUG_VS2015_IA32_DLINK_FLAGS = /NOLOGO /NODEFAULTLIB /IGNORE:4001 /OPT:REF /OPT:ICF=10 /MAP /ALIGN:32 /SECTION:.xdata,D /SECTION:.pdata,D /MACHINE:X86 /LTCG /DLL /ENTRY:$(IMAGE_ENTRY_POINT) /SUBSYSTEM:EFI_BOOT_SERVICE_DRIVER /SAFESEH:NO /BASE:0 /DRIVER /DEBUG
RELEASE_VS2015_IA32_DLINK_FLAGS = /NOLOGO /NODEFAULTLIB /IGNORE:4001 /IGNORE:4254 /OPT:REF /OPT:ICF=10 /MAP /ALIGN:32 /SECTION:.xdata,D /SECTION:.pdata,D /MACHINE:X86 /LTCG /DLL /ENTRY:$(IMAGE_ENTRY_POINT) /SUBSYSTEM:EFI_BOOT_SERVICE_DRIVER /SAFESEH:NO /BASE:0 /DRIVER /MERGE:.rdata=.data
NOOPT_VS2015_IA32_DLINK_FLAGS = /NOLOGO /NODEFAULTLIB /IGNORE:4001 /OPT:REF /OPT:ICF=10 /MAP /ALIGN:32 /SECTION:.xdata,D /SECTION:.pdata,D /MACHINE:X86 /LTCG /DLL /ENTRY:$(IMAGE_ENTRY_POINT) /SUBSYSTEM:EFI_BOOT_SERVICE_DRIVER /SAFESEH:NO /BASE:0 /DRIVER /DEBUG
##################
# X64 definitions
##################
*_VS2015_X64_*_DLL = DEF(VS2015_DLL)
*_VS2015_X64_CC_PATH = DEF(VS2015_BINX64)\cl.exe
*_VS2015_X64_PP_PATH = DEF(VS2015_BINX64)\cl.exe
*_VS2015_X64_APP_PATH = DEF(VS2015_BINX64)\cl.exe
*_VS2015_X64_VFRPP_PATH = DEF(VS2015_BINX64)\cl.exe
*_VS2015_X64_ASM_PATH = DEF(VS2015_BINX64)\ml64.exe
*_VS2015_X64_SLINK_PATH = DEF(VS2015_BINX64)\lib.exe
*_VS2015_X64_DLINK_PATH = DEF(VS2015_BINX64)\link.exe
*_VS2015_X64_ASLCC_PATH = DEF(VS2015_BINX64)\cl.exe
*_VS2015_X64_ASLPP_PATH = DEF(VS2015_BINX64)\cl.exe
*_VS2015_X64_ASLDLINK_PATH = DEF(VS2015_BINX64)\link.exe
DEBUG_VS2015_X64_CC_FLAGS = /nologo /c /WX /GS- /W4 /Gs32768 /D UNICODE /O1b2s /GL /Gy /FIAutoGen.h /EHs-c- /GR- /GF /Z7 /Gw
RELEASE_VS2015_X64_CC_FLAGS = /nologo /c /WX /GS- /W4 /Gs32768 /D UNICODE /O1b2s /GL /Gy /FIAutoGen.h /EHs-c- /GR- /GF /Gw
NOOPT_VS2015_X64_CC_FLAGS = /nologo /c /WX /GS- /W4 /Gs32768 /D UNICODE /Gy /FIAutoGen.h /EHs-c- /GR- /GF /Z7 /Od
DEBUG_VS2015_X64_ASM_FLAGS = /nologo /c /WX /W3 /Cx /Zd /Zi
RELEASE_VS2015_X64_ASM_FLAGS = /nologo /c /WX /W3 /Cx /Zd
NOOPT_VS2015_X64_ASM_FLAGS = /nologo /c /WX /W3 /Cx /Zd /Zi
DEBUG_VS2015_X64_NASM_FLAGS = -Ox -f win64 -g
RELEASE_VS2015_X64_NASM_FLAGS = -Ox -f win64
NOOPT_VS2015_X64_NASM_FLAGS = -O0 -f win64 -g
DEBUG_VS2015_X64_DLINK_FLAGS = /NOLOGO /NODEFAULTLIB /IGNORE:4001 /OPT:REF /OPT:ICF=10 /MAP /ALIGN:32 /SECTION:.xdata,D /SECTION:.pdata,D /Machine:X64 /LTCG /DLL /ENTRY:$(IMAGE_ENTRY_POINT) /SUBSYSTEM:EFI_BOOT_SERVICE_DRIVER /SAFESEH:NO /BASE:0 /DRIVER /DEBUG
RELEASE_VS2015_X64_DLINK_FLAGS = /NOLOGO /NODEFAULTLIB /IGNORE:4001 /IGNORE:4254 /OPT:REF /OPT:ICF=10 /MAP /ALIGN:32 /SECTION:.xdata,D /SECTION:.pdata,D /Machine:X64 /LTCG /DLL /ENTRY:$(IMAGE_ENTRY_POINT) /SUBSYSTEM:EFI_BOOT_SERVICE_DRIVER /SAFESEH:NO /BASE:0 /DRIVER /MERGE:.rdata=.data
NOOPT_VS2015_X64_DLINK_FLAGS = /NOLOGO /NODEFAULTLIB /IGNORE:4001 /OPT:REF /OPT:ICF=10 /MAP /ALIGN:32 /SECTION:.xdata,D /SECTION:.pdata,D /Machine:X64 /LTCG /DLL /ENTRY:$(IMAGE_ENTRY_POINT) /SUBSYSTEM:EFI_BOOT_SERVICE_DRIVER /SAFESEH:NO /BASE:0 /DRIVER /DEBUG
####################################################################################
# VS2015x86 - Microsoft Visual Studio 2015 (x86) professional with Intel ASL
# ASL - Intel ACPI Source Language Compiler (iasl.exe)
####################################################################################
# VS2015x86 - Microsoft Visual Studio 2015 (x86) professional Edition with Intel ASL
*_VS2015x86_*_*_FAMILY = MSFT
*_VS2015x86_*_MAKE_PATH = DEF(VS2015x86_BIN)\nmake.exe
*_VS2015x86_*_MAKE_FLAGS = /nologo
*_VS2015x86_*_RC_PATH = DEF(WINSDK81x86_BIN)\rc.exe
*_VS2015x86_*_SLINK_FLAGS = /NOLOGO /LTCG
*_VS2015x86_*_APP_FLAGS = /nologo /E /TC
*_VS2015x86_*_PP_FLAGS = /nologo /E /TC /FIAutoGen.h
*_VS2015x86_*_VFRPP_FLAGS = /nologo /E /TC /DVFRCOMPILE /FI$(MODULE_NAME)StrDefs.h
*_VS2015x86_*_DLINK2_FLAGS =
*_VS2015x86_*_DEPS_FLAGS = DEF(MSFT_DEPS_FLAGS)
*_VS2015x86_*_GENFWHII_FLAGS = --hiipackage
*_VS2015x86_*_ASM16_PATH = DEF(VS2015x86_BIN)\ml.exe
##################
# ASL definitions
##################
*_VS2015x86_*_ASL_PATH = DEF(WIN_IASL_BIN)
*_VS2015x86_*_ASL_FLAGS = DEF(DEFAULT_WIN_ASL_FLAGS)
*_VS2015x86_*_ASL_OUTFLAGS = DEF(DEFAULT_WIN_ASL_OUTFLAGS)
*_VS2015x86_*_ASLCC_FLAGS = DEF(MSFT_ASLCC_FLAGS)
*_VS2015x86_*_ASLPP_FLAGS = DEF(MSFT_ASLPP_FLAGS)
*_VS2015x86_*_ASLDLINK_FLAGS = DEF(MSFT_ASLDLINK_FLAGS)
##################
# IA32 definitions
##################
*_VS2015x86_IA32_*_DLL = DEF(VS2015x86_DLL)
*_VS2015x86_IA32_CC_PATH = DEF(VS2015x86_BIN)\cl.exe
*_VS2015x86_IA32_VFRPP_PATH = DEF(VS2015x86_BIN)\cl.exe
*_VS2015x86_IA32_ASLCC_PATH = DEF(VS2015x86_BIN)\cl.exe
*_VS2015x86_IA32_ASLPP_PATH = DEF(VS2015x86_BIN)\cl.exe
*_VS2015x86_IA32_SLINK_PATH = DEF(VS2015x86_BIN)\lib.exe
*_VS2015x86_IA32_DLINK_PATH = DEF(VS2015x86_BIN)\link.exe
*_VS2015x86_IA32_ASLDLINK_PATH= DEF(VS2015x86_BIN)\link.exe
*_VS2015x86_IA32_APP_PATH = DEF(VS2015x86_BIN)\cl.exe
*_VS2015x86_IA32_PP_PATH = DEF(VS2015x86_BIN)\cl.exe
*_VS2015x86_IA32_ASM_PATH = DEF(VS2015x86_BIN)\ml.exe
DEBUG_VS2015x86_IA32_CC_FLAGS = /nologo /arch:IA32 /c /WX /GS- /W4 /Gs32768 /D UNICODE /O1b2 /GL /FIAutoGen.h /EHs-c- /GR- /GF /Gy /Z7 /Gw
RELEASE_VS2015x86_IA32_CC_FLAGS = /nologo /arch:IA32 /c /WX /GS- /W4 /Gs32768 /D UNICODE /O1b2 /GL /FIAutoGen.h /EHs-c- /GR- /GF /Gw
NOOPT_VS2015x86_IA32_CC_FLAGS = /nologo /arch:IA32 /c /WX /GS- /W4 /Gs32768 /D UNICODE /FIAutoGen.h /EHs-c- /GR- /GF /Gy /Z7 /Od
DEBUG_VS2015x86_IA32_ASM_FLAGS = /nologo /c /WX /W3 /Cx /coff /Zd /Zi
RELEASE_VS2015x86_IA32_ASM_FLAGS = /nologo /c /WX /W3 /Cx /coff /Zd
NOOPT_VS2015x86_IA32_ASM_FLAGS = /nologo /c /WX /W3 /Cx /coff /Zd /Zi
DEBUG_VS2015x86_IA32_NASM_FLAGS = -Ox -f win32 -g
RELEASE_VS2015x86_IA32_NASM_FLAGS = -Ox -f win32
NOOPT_VS2015x86_IA32_NASM_FLAGS = -O0 -f win32 -g
DEBUG_VS2015x86_IA32_DLINK_FLAGS = /NOLOGO /NODEFAULTLIB /IGNORE:4001 /OPT:REF /OPT:ICF=10 /MAP /ALIGN:32 /SECTION:.xdata,D /SECTION:.pdata,D /MACHINE:X86 /LTCG /DLL /ENTRY:$(IMAGE_ENTRY_POINT) /SUBSYSTEM:EFI_BOOT_SERVICE_DRIVER /SAFESEH:NO /BASE:0 /DRIVER /DEBUG
RELEASE_VS2015x86_IA32_DLINK_FLAGS = /NOLOGO /NODEFAULTLIB /IGNORE:4001 /IGNORE:4254 /OPT:REF /OPT:ICF=10 /MAP /ALIGN:32 /SECTION:.xdata,D /SECTION:.pdata,D /MACHINE:X86 /LTCG /DLL /ENTRY:$(IMAGE_ENTRY_POINT) /SUBSYSTEM:EFI_BOOT_SERVICE_DRIVER /SAFESEH:NO /BASE:0 /DRIVER /MERGE:.rdata=.data
NOOPT_VS2015x86_IA32_DLINK_FLAGS = /NOLOGO /NODEFAULTLIB /IGNORE:4001 /OPT:REF /OPT:ICF=10 /MAP /ALIGN:32 /SECTION:.xdata,D /SECTION:.pdata,D /MACHINE:X86 /LTCG /DLL /ENTRY:$(IMAGE_ENTRY_POINT) /SUBSYSTEM:EFI_BOOT_SERVICE_DRIVER /SAFESEH:NO /BASE:0 /DRIVER /DEBUG
##################
# X64 definitions
##################
*_VS2015x86_X64_*_DLL = DEF(VS2015x86_DLL)
*_VS2015x86_X64_CC_PATH = DEF(VS2015x86_BINX64)\cl.exe
*_VS2015x86_X64_PP_PATH = DEF(VS2015x86_BINX64)\cl.exe
*_VS2015x86_X64_APP_PATH = DEF(VS2015x86_BINX64)\cl.exe
*_VS2015x86_X64_VFRPP_PATH = DEF(VS2015x86_BINX64)\cl.exe
*_VS2015x86_X64_ASLCC_PATH = DEF(VS2015x86_BINX64)\cl.exe
*_VS2015x86_X64_ASLPP_PATH = DEF(VS2015x86_BINX64)\cl.exe
*_VS2015x86_X64_ASM_PATH = DEF(VS2015x86_BINX64)\ml64.exe
*_VS2015x86_X64_SLINK_PATH = DEF(VS2015x86_BINX64)\lib.exe
*_VS2015x86_X64_DLINK_PATH = DEF(VS2015x86_BINX64)\link.exe
*_VS2015x86_X64_ASLDLINK_PATH = DEF(VS2015x86_BINX64)\link.exe
DEBUG_VS2015x86_X64_CC_FLAGS = /nologo /c /WX /GS- /W4 /Gs32768 /D UNICODE /O1b2s /GL /Gy /FIAutoGen.h /EHs-c- /GR- /GF /Z7 /Gw
RELEASE_VS2015x86_X64_CC_FLAGS = /nologo /c /WX /GS- /W4 /Gs32768 /D UNICODE /O1b2s /GL /Gy /FIAutoGen.h /EHs-c- /GR- /GF /Gw
NOOPT_VS2015x86_X64_CC_FLAGS = /nologo /c /WX /GS- /W4 /Gs32768 /D UNICODE /Gy /FIAutoGen.h /EHs-c- /GR- /GF /Z7 /Od
DEBUG_VS2015x86_X64_ASM_FLAGS = /nologo /c /WX /W3 /Cx /Zd /Zi
RELEASE_VS2015x86_X64_ASM_FLAGS = /nologo /c /WX /W3 /Cx /Zd
NOOPT_VS2015x86_X64_ASM_FLAGS = /nologo /c /WX /W3 /Cx /Zd /Zi
DEBUG_VS2015x86_X64_NASM_FLAGS = -Ox -f win64 -g
RELEASE_VS2015x86_X64_NASM_FLAGS = -Ox -f win64
NOOPT_VS2015x86_X64_NASM_FLAGS = -O0 -f win64 -g
DEBUG_VS2015x86_X64_DLINK_FLAGS = /NOLOGO /NODEFAULTLIB /IGNORE:4001 /OPT:REF /OPT:ICF=10 /MAP /ALIGN:32 /SECTION:.xdata,D /SECTION:.pdata,D /Machine:X64 /LTCG /DLL /ENTRY:$(IMAGE_ENTRY_POINT) /SUBSYSTEM:EFI_BOOT_SERVICE_DRIVER /SAFESEH:NO /BASE:0 /DRIVER /DEBUG
RELEASE_VS2015x86_X64_DLINK_FLAGS = /NOLOGO /NODEFAULTLIB /IGNORE:4001 /IGNORE:4254 /OPT:REF /OPT:ICF=10 /MAP /ALIGN:32 /SECTION:.xdata,D /SECTION:.pdata,D /Machine:X64 /LTCG /DLL /ENTRY:$(IMAGE_ENTRY_POINT) /SUBSYSTEM:EFI_BOOT_SERVICE_DRIVER /SAFESEH:NO /BASE:0 /DRIVER /MERGE:.rdata=.data
NOOPT_VS2015x86_X64_DLINK_FLAGS = /NOLOGO /NODEFAULTLIB /IGNORE:4001 /OPT:REF /OPT:ICF=10 /MAP /ALIGN:32 /SECTION:.xdata,D /SECTION:.pdata,D /Machine:X64 /LTCG /DLL /ENTRY:$(IMAGE_ENTRY_POINT) /SUBSYSTEM:EFI_BOOT_SERVICE_DRIVER /SAFESEH:NO /BASE:0 /DRIVER /DEBUG
####################################################################################
# VS2017 - Microsoft Visual Studio 2017 with Intel ASL
# ASL - Intel ACPI Source Language Compiler (iasl.exe)
####################################################################################
# VS2017 - Microsoft Visual Studio 2017 professional Edition with Intel ASL
*_VS2017_*_*_FAMILY = MSFT
*_VS2017_*_*_DLL = DEF(VS2017_BIN_HOST)
*_VS2017_*_MAKE_PATH = DEF(VS2017_BIN_HOST)\nmake.exe
*_VS2017_*_MAKE_FLAGS = /nologo
*_VS2017_*_RC_PATH = DEF(RC_PATH)
*_VS2017_*_SLINK_FLAGS = /NOLOGO /LTCG
*_VS2017_*_APP_FLAGS = /nologo /E /TC
*_VS2017_*_PP_FLAGS = /nologo /E /TC /FIAutoGen.h
*_VS2017_*_VFRPP_FLAGS = /nologo /E /TC /DVFRCOMPILE /FI$(MODULE_NAME)StrDefs.h
*_VS2017_*_DLINK2_FLAGS = /WHOLEARCHIVE
*_VS2017_*_ASM16_PATH = DEF(VS2017_BIN_IA32)\ml.exe
*_VS2017_*_GENFWHII_FLAGS = --hiipackage
*_VS2017_*_DEPS_FLAGS = DEF(MSFT_DEPS_FLAGS)
##################
# ASL definitions
##################
*_VS2017_*_ASL_PATH = DEF(WIN_IASL_BIN)
*_VS2017_*_ASL_FLAGS = DEF(DEFAULT_WIN_ASL_FLAGS)
*_VS2017_*_ASL_OUTFLAGS = DEF(DEFAULT_WIN_ASL_OUTFLAGS)
*_VS2017_*_ASLCC_FLAGS = DEF(MSFT_ASLCC_FLAGS)
*_VS2017_*_ASLPP_FLAGS = DEF(MSFT_ASLPP_FLAGS)
*_VS2017_*_ASLDLINK_FLAGS = DEF(MSFT_ASLDLINK_FLAGS)
##################
# IA32 definitions
##################
*_VS2017_IA32_CC_PATH = DEF(VS2017_BIN_IA32)\cl.exe
*_VS2017_IA32_VFRPP_PATH = DEF(VS2017_BIN_IA32)\cl.exe
*_VS2017_IA32_ASLCC_PATH = DEF(VS2017_BIN_IA32)\cl.exe
*_VS2017_IA32_ASLPP_PATH = DEF(VS2017_BIN_IA32)\cl.exe
*_VS2017_IA32_SLINK_PATH = DEF(VS2017_BIN_IA32)\lib.exe
*_VS2017_IA32_DLINK_PATH = DEF(VS2017_BIN_IA32)\link.exe
*_VS2017_IA32_ASLDLINK_PATH= DEF(VS2017_BIN_IA32)\link.exe
*_VS2017_IA32_APP_PATH = DEF(VS2017_BIN_IA32)\cl.exe
*_VS2017_IA32_PP_PATH = DEF(VS2017_BIN_IA32)\cl.exe
*_VS2017_IA32_ASM_PATH = DEF(VS2017_BIN_IA32)\ml.exe
DEBUG_VS2017_IA32_CC_FLAGS = /nologo /arch:IA32 /c /WX /GS- /W4 /Gs32768 /D UNICODE /O1b2 /GL /FIAutoGen.h /EHs-c- /GR- /GF /Gy /Z7 /Gw
RELEASE_VS2017_IA32_CC_FLAGS = /nologo /arch:IA32 /c /WX /GS- /W4 /Gs32768 /D UNICODE /O1b2 /GL /FIAutoGen.h /EHs-c- /GR- /GF /Gw
NOOPT_VS2017_IA32_CC_FLAGS = /nologo /arch:IA32 /c /WX /GS- /W4 /Gs32768 /D UNICODE /FIAutoGen.h /EHs-c- /GR- /GF /Gy /Z7 /Od
DEBUG_VS2017_IA32_ASM_FLAGS = /nologo /c /WX /W3 /Cx /coff /Zd /Zi
RELEASE_VS2017_IA32_ASM_FLAGS = /nologo /c /WX /W3 /Cx /coff /Zd
NOOPT_VS2017_IA32_ASM_FLAGS = /nologo /c /WX /W3 /Cx /coff /Zd /Zi
DEBUG_VS2017_IA32_NASM_FLAGS = -Ox -f win32 -g
RELEASE_VS2017_IA32_NASM_FLAGS = -Ox -f win32
NOOPT_VS2017_IA32_NASM_FLAGS = -O0 -f win32 -g
DEBUG_VS2017_IA32_DLINK_FLAGS = /NOLOGO /NODEFAULTLIB /IGNORE:4001 /OPT:REF /OPT:ICF=10 /MAP /ALIGN:32 /SECTION:.xdata,D /SECTION:.pdata,D /MACHINE:X86 /LTCG /DLL /ENTRY:$(IMAGE_ENTRY_POINT) /SUBSYSTEM:EFI_BOOT_SERVICE_DRIVER /SAFESEH:NO /BASE:0 /DRIVER /DEBUG
RELEASE_VS2017_IA32_DLINK_FLAGS = /NOLOGO /NODEFAULTLIB /IGNORE:4001 /IGNORE:4254 /OPT:REF /OPT:ICF=10 /MAP /ALIGN:32 /SECTION:.xdata,D /SECTION:.pdata,D /MACHINE:X86 /LTCG /DLL /ENTRY:$(IMAGE_ENTRY_POINT) /SUBSYSTEM:EFI_BOOT_SERVICE_DRIVER /SAFESEH:NO /BASE:0 /DRIVER /MERGE:.rdata=.data
NOOPT_VS2017_IA32_DLINK_FLAGS = /NOLOGO /NODEFAULTLIB /IGNORE:4001 /OPT:REF /OPT:ICF=10 /MAP /ALIGN:32 /SECTION:.xdata,D /SECTION:.pdata,D /MACHINE:X86 /LTCG /DLL /ENTRY:$(IMAGE_ENTRY_POINT) /SUBSYSTEM:EFI_BOOT_SERVICE_DRIVER /SAFESEH:NO /BASE:0 /DRIVER /DEBUG
##################
# X64 definitions
##################
*_VS2017_X64_CC_PATH = DEF(VS2017_BIN_X64)\cl.exe
*_VS2017_X64_PP_PATH = DEF(VS2017_BIN_X64)\cl.exe
*_VS2017_X64_APP_PATH = DEF(VS2017_BIN_X64)\cl.exe
*_VS2017_X64_VFRPP_PATH = DEF(VS2017_BIN_X64)\cl.exe
*_VS2017_X64_ASLCC_PATH = DEF(VS2017_BIN_X64)\cl.exe
*_VS2017_X64_ASLPP_PATH = DEF(VS2017_BIN_X64)\cl.exe
*_VS2017_X64_ASM_PATH = DEF(VS2017_BIN_X64)\ml64.exe
*_VS2017_X64_SLINK_PATH = DEF(VS2017_BIN_X64)\lib.exe
*_VS2017_X64_DLINK_PATH = DEF(VS2017_BIN_X64)\link.exe
*_VS2017_X64_ASLDLINK_PATH = DEF(VS2017_BIN_X64)\link.exe
DEBUG_VS2017_X64_CC_FLAGS = /nologo /c /WX /GS- /W4 /Gs32768 /D UNICODE /O1b2s /GL /Gy /FIAutoGen.h /EHs-c- /GR- /GF /Z7 /Gw
RELEASE_VS2017_X64_CC_FLAGS = /nologo /c /WX /GS- /W4 /Gs32768 /D UNICODE /O1b2s /GL /Gy /FIAutoGen.h /EHs-c- /GR- /GF /Gw
NOOPT_VS2017_X64_CC_FLAGS = /nologo /c /WX /GS- /W4 /Gs32768 /D UNICODE /Gy /FIAutoGen.h /EHs-c- /GR- /GF /Z7 /Od
DEBUG_VS2017_X64_ASM_FLAGS = /nologo /c /WX /W3 /Cx /Zd /Zi
RELEASE_VS2017_X64_ASM_FLAGS = /nologo /c /WX /W3 /Cx /Zd
NOOPT_VS2017_X64_ASM_FLAGS = /nologo /c /WX /W3 /Cx /Zd /Zi
DEBUG_VS2017_X64_NASM_FLAGS = -Ox -f win64 -g
RELEASE_VS2017_X64_NASM_FLAGS = -Ox -f win64
NOOPT_VS2017_X64_NASM_FLAGS = -O0 -f win64 -g
DEBUG_VS2017_X64_DLINK_FLAGS = /NOLOGO /NODEFAULTLIB /IGNORE:4001 /IGNORE:4281 /OPT:REF /OPT:ICF=10 /MAP /ALIGN:32 /SECTION:.xdata,D /SECTION:.pdata,D /Machine:X64 /LTCG /DLL /ENTRY:$(IMAGE_ENTRY_POINT) /SUBSYSTEM:EFI_BOOT_SERVICE_DRIVER /SAFESEH:NO /BASE:0 /DRIVER /DEBUG
RELEASE_VS2017_X64_DLINK_FLAGS = /NOLOGO /NODEFAULTLIB /IGNORE:4001 /IGNORE:4281 /IGNORE:4254 /OPT:REF /OPT:ICF=10 /MAP /ALIGN:32 /SECTION:.xdata,D /SECTION:.pdata,D /Machine:X64 /LTCG /DLL /ENTRY:$(IMAGE_ENTRY_POINT) /SUBSYSTEM:EFI_BOOT_SERVICE_DRIVER /SAFESEH:NO /BASE:0 /DRIVER /MERGE:.rdata=.data
NOOPT_VS2017_X64_DLINK_FLAGS = /NOLOGO /NODEFAULTLIB /IGNORE:4001 /IGNORE:4281 /OPT:REF /OPT:ICF=10 /MAP /ALIGN:32 /SECTION:.xdata,D /SECTION:.pdata,D /Machine:X64 /LTCG /DLL /ENTRY:$(IMAGE_ENTRY_POINT) /SUBSYSTEM:EFI_BOOT_SERVICE_DRIVER /SAFESEH:NO /BASE:0 /DRIVER /DEBUG
#####################
# AARCH64 definitions
#####################
*_VS2017_AARCH64_CC_PATH = DEF(VS2017_BIN_AARCH64)\cl.exe
*_VS2017_AARCH64_VFRPP_PATH = DEF(VS2017_BIN_AARCH64)\cl.exe
*_VS2017_AARCH64_SLINK_PATH = DEF(VS2017_BIN_AARCH64)\lib.exe
*_VS2017_AARCH64_DLINK_PATH = DEF(VS2017_BIN_AARCH64)\link.exe
*_VS2017_AARCH64_APP_PATH = DEF(VS2017_BIN_AARCH64)\cl.exe
*_VS2017_AARCH64_PP_PATH = DEF(VS2017_BIN_AARCH64)\cl.exe
*_VS2017_AARCH64_ASM_PATH = DEF(VS2017_BIN_AARCH64)\armasm64.exe
*_VS2017_AARCH64_ASLCC_PATH = DEF(VS2017_BIN_AARCH64)\cl.exe
*_VS2017_AARCH64_ASLPP_PATH = DEF(VS2017_BIN_AARCH64)\cl.exe
*_VS2017_AARCH64_ASLDLINK_PATH = DEF(VS2017_BIN_AARCH64)\link.exe
DEBUG_VS2017_AARCH64_CC_FLAGS = /nologo /c /WX /GS- /W4 /Gs32768 /D UNICODE /O1b2 /GL /FIAutoGen.h /EHs-c- /GR- /GF /Gy /Zi /Gw /Oi-
RELEASE_VS2017_AARCH64_CC_FLAGS = /nologo /c /WX /GS- /W4 /Gs32768 /D UNICODE /O1b2 /GL /FIAutoGen.h /EHs-c- /GR- /GF /Gw /Oi-
NOOPT_VS2017_AARCH64_CC_FLAGS = /nologo /c /WX /GS- /W4 /Gs32768 /D UNICODE /FIAutoGen.h /EHs-c- /GR- /GF /Gy /Zi /Od /Oi-
DEBUG_VS2017_AARCH64_ASM_FLAGS = /nologo /g
RELEASE_VS2017_AARCH64_ASM_FLAGS = /nologo
NOOPT_VS2017_AARCH64_ASM_FLAGS = /nologo
DEBUG_VS2017_AARCH64_DLINK_FLAGS = /NOLOGO /NODEFAULTLIB /IGNORE:4001 /OPT:REF /OPT:ICF=10 /MAP /SECTION:.xdata,D /SECTION:.pdata,D /MACHINE:ARM64 /LTCG /DLL /ENTRY:$(IMAGE_ENTRY_POINT) /SUBSYSTEM:EFI_BOOT_SERVICE_DRIVER /SAFESEH:NO /DRIVER /DEBUG
RELEASE_VS2017_AARCH64_DLINK_FLAGS = /NOLOGO /NODEFAULTLIB /IGNORE:4001 /IGNORE:4254 /OPT:REF /OPT:ICF=10 /MAP /SECTION:.xdata,D /SECTION:.pdata,D /MACHINE:ARM64 /LTCG /DLL /ENTRY:$(IMAGE_ENTRY_POINT) /SUBSYSTEM:EFI_BOOT_SERVICE_DRIVER /SAFESEH:NO /DRIVER /MERGE:.rdata=.data
NOOPT_VS2017_AARCH64_DLINK_FLAGS = /NOLOGO /NODEFAULTLIB /IGNORE:4001 /OPT:REF /OPT:ICF=10 /MAP /SECTION:.xdata,D /SECTION:.pdata,D /MACHINE:ARM64 /LTCG /DLL /ENTRY:$(IMAGE_ENTRY_POINT) /SUBSYSTEM:EFI_BOOT_SERVICE_DRIVER /SAFESEH:NO /DRIVER /DEBUG
####################################################################################
# VS2019 - Microsoft Visual Studio 2019 with Intel ASL
# ASL - Intel ACPI Source Language Compiler (iasl.exe)
@ -924,10 +586,10 @@ NOOPT_*_*_OBJCOPY_ADDDEBUGFLAG = --add-gnu-debuglink="$(DEBUG_DIR)/$(MODULE_
*_*_*_DTCPP_PATH = DEF(DTCPP_BIN)
*_*_*_DTC_PATH = DEF(DTC_BIN)
# All supported GCC archs except LOONGARCH64 support -mstack-protector-guard=global, so set that on everything except LOONGARCH64
# Because LOONGARCH64 supports global stack protector guard by default, it does not support the parameter -mstack-protector-guard=global, and this parameter will be supported in GCC17. So set that on every thing except LOONGARCH64.
DEFINE GCC_ALL_CC_COMMON = -g -Os -fshort-wchar -fno-builtin -fno-strict-aliasing -Wall -Werror -Wno-array-bounds -include AutoGen.h -fno-common -fstack-protector
DEFINE GCC_IA32_X64_CC_FLAGS = -mstack-protector-guard=global
DEFINE GCC_LOONGARCH64_CC_FLAGS = DEF(GCC_ALL_CC_COMMON) -mabi=lp64d -fno-asynchronous-unwind-tables -Wno-address -fno-short-enums -fsigned-char -ffunction-sections -fdata-sections -march=loongarch64 -mno-memcpy -Werror -Wno-maybe-uninitialized -Wno-stringop-overflow -Wno-pointer-to-int-cast -no-pie -fno-stack-protector -mno-explicit-relocs -mno-relax
DEFINE GCC_LOONGARCH64_CC_FLAGS = DEF(GCC_ALL_CC_COMMON) -mabi=lp64d -fno-asynchronous-unwind-tables -Wno-address -fno-short-enums -fsigned-char -ffunction-sections -fdata-sections -march=loongarch64 -mno-memcpy -Werror -Wno-maybe-uninitialized -Wno-stringop-overflow -Wno-pointer-to-int-cast -no-pie -mno-explicit-relocs -mno-relax
DEFINE GCC_AARCH64_CC_COMMON = DEF(GCC_ALL_CC_COMMON) -mlittle-endian -fno-short-enums -fverbose-asm -funsigned-char -ffunction-sections -fdata-sections -Wno-address -fno-asynchronous-unwind-tables -fno-unwind-tables -fno-pic -fno-pie -ffixed-x18 -mstack-protector-guard=global
DEFINE GCC_AARCH64_CC_XIPCOMMON = -mstrict-align -mgeneral-regs-only
DEFINE GCC_RISCV64_CC_XIPFLAGS = -mstrict-align -mgeneral-regs-only
@ -989,7 +651,7 @@ DEFINE GCC_AARCH64_DLINK2_FLAGS = DEF(GCCNOLTO_AARCH64_DLINK2_FLAGS) -Wno-e
DEFINE GCC_AARCH64_ASLDLINK_FLAGS = DEF(GCCNOLTO_AARCH64_ASLDLINK_FLAGS) DEF(GCC_DLINK_WARNING_FLAGS)
DEFINE GCC_ASLCC_FLAGS = DEF(GCCNOLTO_ASLCC_FLAGS) -fno-lto
DEFINE GCC_RISCV_ALL_CC_FLAGS = -g -fshort-wchar -fno-omit-frame-pointer -fno-strict-aliasing -Wall -Werror -Wno-array-bounds -ffunction-sections -fdata-sections -include AutoGen.h -fno-common -DSTRING_ARRAY_NAME=$(BASE_NAME)Strings -msmall-data-limit=0
DEFINE GCC_RISCV_ALL_CC_FLAGS = DEF(GCC_ALL_CC_FLAGS) -fno-omit-frame-pointer -ffunction-sections -fdata-sections -DSTRING_ARRAY_NAME=$(BASE_NAME)Strings -msmall-data-limit=0
DEFINE GCC_RISCV_ALL_DLINK_COMMON = -nostdlib -Wl,-n,-q,--gc-sections -z common-page-size=0x40 DEF(GCC_DLINK_WARNING_FLAGS)
DEFINE GCC_RISCV_ALL_DLINK_FLAGS = DEF(GCC_RISCV_ALL_DLINK_COMMON) -Wl,--entry,$(IMAGE_ENTRY_POINT) -u $(IMAGE_ENTRY_POINT) -Wl,-Map,$(DEST_DIR_DEBUG)/$(BASE_NAME).map
DEFINE GCC_RISCV_ALL_DLINK2_FLAGS = -Wl,--defsym=PECOFF_HEADER_SIZE=0x220,--script=$(EDK_TOOLS_PATH)/Scripts/GccBase.lds

View file

@ -1,7 +1,7 @@
# @file Edk2ToolsBuild.py
# Invocable class that builds the basetool c files.
#
# Supports VS2019, VS2022, and GCC
# Supports VS2019, VS2022, VS2026, and GCC
##
# Copyright (c) Microsoft Corporation
#
@ -25,7 +25,7 @@ class Edk2ToolsBuild(BaseAbstractInvocable):
def ParseCommandLineOptions(self):
''' parse arguments '''
ParserObj = argparse.ArgumentParser()
ParserObj.add_argument("-t", "--tool_chain_tag", dest="tct", default="VS2022",
ParserObj.add_argument("-t", "--tool_chain_tag", dest="tct", default="VS2026",
help="Set the toolchain used to compile the build tools")
ParserObj.add_argument("-a", "--target_arch", dest="arch", default=None, choices=[None, 'IA32', 'X64', 'AARCH64'],
help="Specify the architecture of the built base tools. Not specifying this will fall back to the default "

View file

@ -2,7 +2,7 @@
- description: C++ queries
- queries: '.'
from: codeql/cpp-queries@1.1.0
from: codeql/cpp-queries@1.6.1
##########################################################################################
# Queries

View file

@ -0,0 +1,315 @@
#!/usr/bin/env python3
"""
@file CodeQlVersionUpdate.py
Update CodeQL CLI dependencies and the CodeQL query pack version.
This maintainer-only helper updates the pinned CodeQL CLI release and the
corresponding CodeQL C/C++ query pack version used by the EDK II BaseTools
CodeQL plugin. The CodeQL plugin does not invoke this script automatically.
Audience
--------
EDK II BaseTools CodeQL plugin maintainers. Developers who build with the
CodeQL plugin enabled, or who review CodeQL analysis results, do not need to
run this script.
Usage
-----
Run this script manually from a local checkout:
# Update to the latest published CodeQL CLI release.
python3 BaseTools/Plugin/CodeQL/CodeQlVersionUpdate.py
# Update to a specific CodeQL CLI version.
python3 BaseTools/Plugin/CodeQL/CodeQlVersionUpdate.py --codeql-version 2.25.3
Then review and commit the resulting file changes.
Updated files
-------------
- BaseTools/Plugin/CodeQL/codeqlcli_ext_dep.yaml
- BaseTools/Plugin/CodeQL/codeqlcli_linux_ext_dep.yaml
- BaseTools/Plugin/CodeQL/codeqlcli_windows_ext_dep.yaml
- BaseTools/Plugin/CodeQL/CodeQlQueries.qls
Data sources
------------
- SHA256 digests are read from GitHub release metadata.
- The codeql/cpp-queries version is read from qlpack.yml in the corresponding
CodeQL CLI branch.
Release metadata note
---------------------
This script depends on GitHub release-asset digests being present in the
release metadata. GitHub started exposing those digests on 2025-06-03:
https://github.blog/changelog/2025-06-03-releases-now-expose-digests-for-release-assets/
Releases published before that change may not have `digest` values in the API.
Copyright (c) 2026, Purdue University. All rights reserved.<BR>
SPDX-License-Identifier: BSD-2-Clause-Patent
"""
from __future__ import annotations
import argparse
import json
import re
import sys
import urllib.error
import urllib.request
from pathlib import Path
from typing import Dict
SCRIPT_DIR = Path(__file__).resolve().parent
EXT_DEP_FILES = {
"codeql.zip": SCRIPT_DIR / "codeqlcli_ext_dep.yaml",
"codeql-linux64.zip": SCRIPT_DIR / "codeqlcli_linux_ext_dep.yaml",
"codeql-win64.zip": SCRIPT_DIR / "codeqlcli_windows_ext_dep.yaml",
}
QUERY_FILE = SCRIPT_DIR / "CodeQlQueries.qls"
HTTP_TIMEOUT_SECONDS = 30
def _http_get(url: str) -> bytes:
req = urllib.request.Request(url, headers={"User-Agent": "edk2-codeql-updater"})
with urllib.request.urlopen(req, timeout=HTTP_TIMEOUT_SECONDS) as resp:
return resp.read()
def _http_get_json(url: str) -> dict:
return json.loads(_http_get(url).decode("utf-8"))
def _http_get_text(url: str) -> str:
return _http_get(url).decode("utf-8")
def _extract_sha256_from_text(text: str) -> str:
# Expected content is either "<sha256>" or "<sha256> <filename>".
token = text.strip().split()[0]
if not re.fullmatch(r"[0-9a-fA-F]{64}", token):
raise ValueError(f"Invalid sha256 text content: {text.strip()!r}")
return token.lower()
def fetch_latest_codeql_version() -> str:
latest_release_url = (
"https://api.github.com/repos/github/codeql-cli-binaries/releases/latest"
)
latest_release = _http_get_json(latest_release_url)
tag_name = latest_release.get("tag_name") or ""
if not isinstance(tag_name, str) or not tag_name:
raise ValueError("Unable to determine latest CodeQL version from GitHub")
return tag_name.lstrip("v")
def fetch_release_sha256_map(codeql_version: str) -> Dict[str, str]:
release_url = (
"https://api.github.com/repos/github/codeql-cli-binaries/releases/tags/"
f"v{codeql_version}"
)
release = _http_get_json(release_url)
assets = {asset["name"]: asset for asset in release.get("assets", [])}
sha_map: Dict[str, str] = {}
for asset_name in EXT_DEP_FILES:
asset = assets.get(asset_name)
if asset is None:
raise KeyError(
f"Release v{codeql_version} does not include required asset: {asset_name}"
)
digest = asset.get("digest") or ""
if digest.startswith("sha256:"):
sha_map[asset_name] = digest.split(":", 1)[1].lower()
continue
sha_asset = assets.get(f"{asset_name}.checksum.txt")
if sha_asset:
sha_text = _http_get_text(sha_asset["browser_download_url"])
sha_map[asset_name] = _extract_sha256_from_text(sha_text)
continue
raise KeyError(
f"Unable to find SHA256 for {asset_name} in release v{codeql_version}"
)
return sha_map
def fetch_cpp_queries_version(codeql_version: str) -> str:
qlpack_url = (
"https://raw.githubusercontent.com/github/codeql/"
f"codeql-cli/v{codeql_version}/cpp/ql/src/qlpack.yml"
)
qlpack_text = _http_get_text(qlpack_url)
# qlpack.yml for cpp queries uses:
# name: codeql/cpp-queries
# version: <pack version>
if "name: codeql/cpp-queries" not in qlpack_text:
raise ValueError(
f"Unable to validate cpp queries pack in qlpack.yml for v{codeql_version}"
)
match = re.search(r"(?m)^\s*version:\s*([0-9A-Za-z.\-_]+)\s*$", qlpack_text)
if not match:
raise ValueError(
f"Unable to parse codeql/cpp-queries version for v{codeql_version}"
)
return match.group(1)
def read_text(path: Path) -> str:
with path.open("r", encoding="utf-8", newline="") as f:
return f.read()
def detect_newline_style(text: str) -> str:
if "\r\n" in text:
return "\r\n"
return "\n"
def normalize_newlines(text: str, newline: str) -> str:
normalized = text.replace("\r\n", "\n")
if newline == "\r\n":
return normalized.replace("\n", "\r\n")
return normalized
def write_text(path: Path, text: str) -> None:
path.write_text(text, encoding="utf-8", newline="")
def replace_or_fail(pattern: str, replacement: str, text: str, path: Path) -> str:
new_text, count = re.subn(pattern, replacement, text, count=1, flags=re.MULTILINE)
if count != 1:
raise ValueError(f"Expected one match for pattern {pattern!r} in {path}")
return new_text
def update_ext_dep_file(path: Path, asset_name: str, codeql_version: str, sha256: str) -> bool:
original = read_text(path)
newline_style = detect_newline_style(original)
text = original
source_url = (
"https://github.com/github/codeql-cli-binaries/releases/download/"
f"v{codeql_version}/{asset_name}"
)
text = replace_or_fail(
r'("source"\s*:\s*")[^"]+(")',
rf'\g<1>{source_url}\g<2>',
text,
path,
)
text = replace_or_fail(
r'("version"\s*:\s*")[^"]+(")',
rf'\g<1>{codeql_version}\g<2>',
text,
path,
)
text = replace_or_fail(
r'("sha256"\s*:\s*")[0-9a-fA-F]{64}(")',
rf'\g<1>{sha256}\g<2>',
text,
path,
)
if text != original:
write_text(path, normalize_newlines(text, newline_style))
return True
return False
def update_queries_file(path: Path, cpp_queries_version: str) -> bool:
original = read_text(path)
newline_style = detect_newline_style(original)
text = replace_or_fail(
r"(from:\s*codeql/cpp-queries@)[0-9A-Za-z.\-_]+",
rf"\g<1>{cpp_queries_version}",
original,
path,
)
if text != original:
write_text(path, normalize_newlines(text, newline_style))
return True
return False
def parse_args() -> argparse.Namespace:
parser = argparse.ArgumentParser(
description="Update CodeQL CLI versions and cpp query pack version."
)
parser.add_argument(
"--codeql-version",
help=(
"CodeQL CLI version (for example: 2.24.1). If omitted, the latest "
"published release is used."
),
)
parser.add_argument(
"--dry-run",
action="store_true",
help="Calculate and print updates without writing files.",
)
return parser.parse_args()
def main() -> int:
args = parse_args()
try:
codeql_version = (
args.codeql_version.lstrip("v")
if args.codeql_version
else fetch_latest_codeql_version()
)
sha_map: Dict[str, str] = fetch_release_sha256_map(codeql_version)
for asset_name, sha in sha_map.items():
if not re.fullmatch(r"[0-9a-f]{64}", sha):
raise ValueError(f"Invalid SHA256 value for {asset_name}: {sha}")
cpp_queries_version = fetch_cpp_queries_version(codeql_version)
print(f"CodeQL version: v{codeql_version}")
print(f"codeql/cpp-queries version: {cpp_queries_version}")
for asset_name in sorted(sha_map):
print(f"{asset_name} sha256: {sha_map[asset_name]}")
if args.dry_run:
print("Dry run: no files were modified.")
return 0
changed_files = []
for asset_name, path in EXT_DEP_FILES.items():
if update_ext_dep_file(path, asset_name, codeql_version, sha_map[asset_name]):
changed_files.append(path)
if update_queries_file(QUERY_FILE, cpp_queries_version):
changed_files.append(QUERY_FILE)
if changed_files:
print("Updated files:")
for path in changed_files:
print(f" - {path}")
else:
print("No file changes were necessary.")
return 0
except urllib.error.HTTPError as err:
print(f"HTTP error while fetching release data: {err}", file=sys.stderr)
except (urllib.error.URLError, TimeoutError) as err:
print(f"Network error while fetching release data: {err}", file=sys.stderr)
except (KeyError, ValueError) as err:
print(f"Error: {err}", file=sys.stderr)
return 1
if __name__ == "__main__":
raise SystemExit(main())

View file

@ -10,6 +10,10 @@
#
# ****VERSION UPDATE INSTRUCTIONS****
#
# Use BaseTools/Plugin/CodeQL/CodeQlVersionUpdate.py to update this file,
# the platform-specific CodeQL CLI dependency files, and CodeQlQueries.qls together.
# The script refreshes the CLI version, release digests, and cpp query pack pin.
#
# When updating the CodeQL CLI used here, update the corresponding codeql/cpp-queries version in CodeQlQueries.qls.
# Visit the `qlpack.yml` in the release branch for the CodeQL CLI to get the version to use there. For example, the
# CodeQL CLI 2.18.1 file is https://github.com/github/codeql/blob/codeql-cli-2.18.1/cpp/ql/src/qlpack.yml and the
@ -23,9 +27,9 @@
"scope": "codeql-ext-dep",
"type": "web",
"name": "codeql_cli",
"source": "https://github.com/github/codeql-cli-binaries/releases/download/v2.18.1/codeql.zip",
"version": "2.18.1",
"sha256": "815f71c1a46e76f9dafdec26c2a4bab7ea4019a3773e91e39253e2d21cf792a2",
"source": "https://github.com/github/codeql-cli-binaries/releases/download/v2.25.3/codeql.zip",
"version": "2.25.3",
"sha256": "0982c5ba0a96deb69b7a14e68d21f3efb5dd89a820e092a4f2a8212f428095c5",
"compression_type": "zip",
"internal_path": "/codeql/",
"flags": ["set_shell_var", ],

View file

@ -8,6 +8,10 @@
#
# ****VERSION UPDATE INSTRUCTIONS****
#
# Use BaseTools/Plugin/CodeQL/CodeQlVersionUpdate.py to update this file,
# the platform-specific CodeQL CLI dependency files, and CodeQlQueries.qls together.
# The script refreshes the CLI version, release digests, and cpp query pack pin.
#
# When updating the CodeQL CLI used here, update the corresponding codeql/cpp-queries version in CodeQlQueries.qls.
# Visit the `qlpack.yml` in the release branch for the CodeQL CLI to get the version to use there. For example, the
# CodeQL CLI 2.18.1 file is https://github.com/github/codeql/blob/codeql-cli-2.18.1/cpp/ql/src/qlpack.yml and the
@ -21,9 +25,9 @@
"scope": "codeql-linux-ext-dep",
"type": "web",
"name": "codeql_linux_cli",
"source": "https://github.com/github/codeql-cli-binaries/releases/download/v2.18.1/codeql-linux64.zip",
"version": "2.18.1",
"sha256": "1547f4a3b509474404daf2e4b821f71cd93462ec45322d9124c2b04e3d52c771",
"source": "https://github.com/github/codeql-cli-binaries/releases/download/v2.25.3/codeql-linux64.zip",
"version": "2.25.3",
"sha256": "db69739e2a480128e1d96d96611129be12ad62a324529754ccdc529b850043a7",
"compression_type": "zip",
"internal_path": "/codeql/",
"flags": ["set_shell_var", ],

View file

@ -8,6 +8,10 @@
#
# ****VERSION UPDATE INSTRUCTIONS****
#
# Use BaseTools/Plugin/CodeQL/CodeQlVersionUpdate.py to update this file,
# the platform-specific CodeQL CLI dependency files, and CodeQlQueries.qls together.
# The script refreshes the CLI version, release digests, and cpp query pack pin.
#
# When updating the CodeQL CLI used here, update the corresponding codeql/cpp-queries version in CodeQlQueries.qls.
# Visit the `qlpack.yml` in the release branch for the CodeQL CLI to get the version to use there. For example, the
# CodeQL CLI 2.18.1 file is https://github.com/github/codeql/blob/codeql-cli-2.18.1/cpp/ql/src/qlpack.yml and the
@ -21,9 +25,9 @@
"scope": "codeql-windows-ext-dep",
"type": "web",
"name": "codeql_windows_cli",
"source": "https://github.com/github/codeql-cli-binaries/releases/download/v2.18.1/codeql-win64.zip",
"version": "2.18.1",
"sha256": "eb69c9ce40142904965ca3f2491c989f12747d74358385e2e94c427b4324201c",
"source": "https://github.com/github/codeql-cli-binaries/releases/download/v2.25.3/codeql-win64.zip",
"version": "2.25.3",
"sha256": "268950c5ca1444bb8439ecdb20e60be9080ba0d786c5a690871251a4b7677647",
"compression_type": "zip",
"internal_path": "/codeql/",
"flags": ["set_shell_var", ],

View file

@ -1,5 +1,5 @@
# @file WindowsVsToolChain.py
# Plugin to configure the environment for the VS2017, VS2019, VS2022, and VS2026 toolchains
# Plugin to configure the environment for the VS2019, VS2022, and VS2026 toolchains
#
# This plugin also runs for CLANGPDB toolchain on Windows as that toolchain
# leverages nmake from VS and needs to the SDK paths for unit tests
@ -30,86 +30,14 @@ class WindowsVsToolChain(IUefiBuildPlugin):
"UCRTVersion", "WindowsLibPath", "WindowsSdkBinPath", "WindowsSdkDir", "WindowsSdkVerBinPath",
"WindowsSDKVersion", "WindowsSDKLibVersion", "VCToolsInstallDir", "Path"]
#
# VS2017 - Follow VS2017 where there is potential for many versions of the tools.
# If a specific version is required then the user must set both env variables:
# VS150INSTALLPATH: base install path on system to VC install dir. Here you will find the VC folder, etc
# VS150TOOLVER: version number for the VC compiler tools
# VS2017_PREFIX: path to MSVC compiler folder with trailing slash (can be used instead of two vars above)
# VS2017_HOST: set the host architecture to use for host tools, and host libs, etc
if thebuilder.env.GetValue("TOOL_CHAIN_TAG") == "VS2017":
# check to see if host is configured
# HostType for VS2017 should be (defined in tools_def):
# x86 == 32bit Intel
# x64 == 64bit Intel
# arm64 == 64bit Arm
#
HostType = shell_environment.GetEnvironment().get_shell_var("VS2017_HOST")
if HostType is not None:
HostType = HostType.lower()
self.Logger.info(
f"HOST TYPE defined by environment. Host Type is {HostType}")
else:
HostInfo = GetHostInfo()
if HostInfo.arch == "x86":
if HostInfo.bit == "32":
HostType = "x86"
elif HostInfo.bit == "64":
HostType = "x64"
else:
raise NotImplementedError()
# VS2017_HOST options are not exactly the same as QueryVcVariables. This translates.
VC_HOST_ARCH_TRANSLATOR = {
"x86": "x86", "x64": "AMD64", "arm64": "not supported"}
# check to see if full path already configured
if shell_environment.GetEnvironment().get_shell_var("VS2017_PREFIX") != None:
self.Logger.info("VS2017_PREFIX is already set.")
else:
install_path = self._get_vs_install_path(
"VS2017".lower(), "VS150INSTALLPATH")
vc_ver = self._get_vc_version(install_path, "VS150TOOLVER")
if install_path is None or vc_ver is None:
self.Logger.error(
"Failed to configure environment for VS2017")
return -1
version_aggregator.GetVersionAggregator().ReportVersion(
"Visual Studio Install Path", install_path, version_aggregator.VersionTypes.INFO)
version_aggregator.GetVersionAggregator().ReportVersion(
"VC Version", vc_ver, version_aggregator.VersionTypes.TOOL)
# make VS2017_PREFIX to align with tools_def.txt
prefix = os.path.join(install_path, "VC",
"Tools", "MSVC", vc_ver)
prefix = prefix + os.path.sep
shell_environment.GetEnvironment().set_shell_var("VS2017_PREFIX", prefix)
shell_environment.GetEnvironment().set_shell_var("VS2017_HOST", HostType)
shell_env = shell_environment.GetEnvironment()
# Use the tools lib to determine the correct values for the vars that interest us.
vs_vars = locate_tools.QueryVcVariables(
interesting_keys, VC_HOST_ARCH_TRANSLATOR[HostType], vs_version="vs2017")
for (k, v) in vs_vars.items():
shell_env.set_shell_var(k, v)
# now confirm it exists
if not os.path.exists(shell_environment.GetEnvironment().get_shell_var("VS2017_PREFIX")):
self.Logger.error("Path for VS2017 toolchain is invalid")
return -2
#
# VS2019 - Follow VS2019 where there is potential for many versions of the tools.
# If a specific version is required then the user must set both env variables:
# VS160INSTALLPATH: base install path on system to VC install dir. Here you will find the VC folder, etc
# VS160TOOLVER: version number for the VC compiler tools
# VS2019_PREFIX: path to MSVC compiler folder with trailing slash (can be used instead of two vars above)
# VS2017_HOST: set the host architecture to use for host tools, and host libs, etc
elif thebuilder.env.GetValue("TOOL_CHAIN_TAG") == "VS2019":
# VS2019_HOST: set the host architecture to use for host tools, and host libs, etc
if thebuilder.env.GetValue("TOOL_CHAIN_TAG") == "VS2019":
# check to see if host is configured
# HostType for VS2019 should be (defined in tools_def):

View file

@ -1,82 +0,0 @@
@REM @file
@REM Windows batch file to set up the Microsoft Visual Studio environment
@REM
@REM This script is used to set up one of the Microsoft Visual Studio
@REM environments, VS2015 for
@REM building the Nt32Pkg/Nt32Pkg.dsc emulation environment to run on
@REM an X64 version of Windows.
@REM The system environment variables in this script are set by the
@rem Edk2Setup.bat script (that will be renamed to edksetup.bat).
@REM
@REM This script can also be used to build the Win32 binaries
@REM
@REM Copyright (c) 2014, Intel Corporation. All rights reserved.<BR>
@REM SPDX-License-Identifier: BSD-2-Clause-Patent
@REM
@echo off
@if defined NT32_X64 @goto CheckLatest
@if "%REBUILD_TOOLS%"=="TRUE" @goto RebuildTools
:CheckLatest
echo.
@if defined VS140COMNTOOLS (
@set "COMMONTOOLSx64=C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\bin\x86_amd64"
@goto SetVs
)
@echo.
@echo No version of Microsoft Visual Studio was found on this system
@echo.
@exit /B 1
@REM Set up the X64 environment for building Nt32Pkg/Nt32Pkg.dsc to run on an X64 platform
:SetVs
if exist "%COMMONTOOLSx64%\vcvarsx86_amd64.bat" (
@call "%COMMONTOOLSx64%\vcvarsx86_amd64.bat"
@if errorlevel 1 (
@echo. ERROR setting Microsoft Visual Studio %1
@set COMMONTOOLSx64=
@exit /B 1
)
)
if not exist "%COMMONTOOLSx64%\vcvarsx86_amd64.bat" (
@echo ERROR : This script does not exist: "%COMMONTOOLSx64%\vcvarsx86_amd64.bat"
@set COMMONTOOLSx64=
@exit /B 1
)
@set COMMONTOOLSx64=
@goto End
:RebuildTools
@call python "%BASE_TOOLS_PATH%\Scripts\UpdateBuildVersions.py"
@set "BIN_DIR=%EDK_TOOLS_PATH%\Bin\Win32"
if not exist "%BIN_DIR%" @mkdir "%BIN_DIR%"
@echo Removing temporary and binary files
@cd "%BASE_TOOLS_PATH%"
@call nmake cleanall
@echo Rebuilding the EDK II BaseTools
@cd "%BASE_TOOLS_PATH%\Source\C"
@call nmake -nologo -a -f Makefile
@if errorlevel 1 (
@echo Error building the C-based BaseTools
@cd "%WORKSPACE%"
@exit /B1
)
@cd %BASE_TOOLS_PATH%\Source\Python
@call nmake -nologo -a -f Makefile
@if errorlevel 1 (
@echo Error building the Python-based BaseTools
@cd %WORKSPACE%
@exit /B1
)
@cd %WORKSPACE%
@goto End
:VersionNotFound
@echo.
@echo This Microsoft Visual Studio version is in not installed on this system: %1
@echo.
@exit /B 1
:End
@exit /B 0

View file

@ -1,169 +0,0 @@
@REM @file
@REM Windows batch file to display the Windows environment
@REM
@REM This script will be used to show the current EDK II build environment.
@REM it may be called by the Edk2Setup.bat (that will be renamed to edksetup.bat) or
@REM run as stand-alone application.
@REM
@REM Copyright (c) 2014, Intel Corporation. All rights reserved.<BR>
@REM SPDX-License-Identifier: BSD-2-Clause-Patent
@REM
@echo off
@set SE_SVN_REVISION=$Revision: 8 $
@set SE_VERSION=0.7.0.
@if "%SCRIPT%"=="EDKSETUP_BAT" goto SkipCmdlineArgumentCheck
:parse_cmd_line
@if /I "%1"=="-h" @goto Usage
@if /I "%1"=="--help" @goto Usage
@if /I "%1"=="/?" @goto Usage
@if /I "%1"=="-v" @goto Version
@if /I "%1"=="--version" @goto Version
:Usage
@echo Usage: ShowEnvironment.bat [Options]
@echo Copyright(c) 2014, Intel Corporation. All rights reserved.
@echo.
@echo Options:
@echo --help, -h Print this help screen and exit
@echo --version, -v Print this tool's version and exit
@echo.
@goto End
:Version
@echo ShowEnvironment.bat Version: %SE_VERSION%%SE_SVN_REVISION:~11,-1%
@echo Copyright(c) 2014, Intel Corporation. All rights reserved.
:SkipCmdlineArgumentCheck
if defined SRC_CONF @goto SetEnv
@echo.
@echo #############################################################################
@if defined WORKSPACE @echo WORKSPACE = %WORKSPACE%
@if not defined WORKSPACE @echo WORKSPACE = Not Set
@if defined PACKAGES_PATH @echo PACKAGES_PATH = %PACKAGES_PATH%
@if defined EDK_TOOLS_PATH @echo EDK_TOOLS_PATH = %EDK_TOOLS_PATH%
@if not defined EDK_TOOLS_PATH @echo EDK_TOOLS_PATH = Not Set
@if defined BASE_TOOLS_PATH @echo BASE_TOOLS_PATH = %BASE_TOOLS_PATH%
@if defined EDK_TOOLS_BIN @echo EDK_TOOLS_BIN = %EDK_TOOLS_BIN%
@if "%NT32PKG%"=="TRUE" (
@echo.
@echo NOTE: Please configure your build to use the following TOOL_CHAIN_TAG
@echo when building NT32Pkg/Nt32Pkg.dsc
@if defined VCINSTALLDIR @call :CheckVsVer
@set TEST_VS=
)
@if defined HIDE_PATH goto End
@echo ############################## PATH #########################################
@setlocal DisableDelayedExpansion
@set "var=%PATH%"
@set "var=%var:"=""%"
@set "var=%var:^=^^%"
@set "var=%var:&=^&%"
@set "var=%var:|=^|%"
@set "var=%var:<=^<%"
@set "var=%var:>=^>%"
@set "var=%var:;=^;^;%"
@set var=%var:""="%
@set "var=%var:"=""Q%"
@set "var=%var:;;="S"S%"
@set "var=%var:^;^;=;%"
@set "var=%var:""="%"
@setlocal EnableDelayedExpansion
@set "var=!var:"Q=!"
@for %%a in ("!var:"S"S=";"!") do (
@if "!!"=="" endlocal
@if %%a neq "" echo %%~a
)
@goto End
:CheckVsVer
@set "TEST_VS=C:\Program Files (x86)\Microsoft Visual Studio 14.0\"
@if "%VSINSTALLDIR%"=="%TEST_VS%" (
@echo TOOL_CHAIN_TAG = VS2015x86
@goto :EOF
)
@set "TEST_VS=C:\Program Files\Microsoft Visual Studio 14.0\"
@if "%VSINSTALLDIR%"=="%TEST_VS%" (
@echo TOOL_CHAIN_TAG = VS2015
@goto :EOF
)
@goto :EOF
:SetEnv
@set FIRST_COPY=FALSE
@set MISSING_TARGET_TEMPLATE=FALSE
@set MISSING_TOOLS_DEF_TEMPLATE=FALSE
@set MISSING_BUILD_RULE_TEMPLATE=FALSE
@if not exist "%SRC_CONF%\target.template" @set MISSING_TARGET_TEMPLATE=TRUE
@if not exist "%SRC_CONF%\tools_def.template" @set MISSING_TOOLS_DEF_TEMPLATE=TRUE
@if not exist "%SRC_CONF%\build_rule.template" @set MISSING_BUILD_RULE_TEMPLATE=TRUE
@if not exist "%WORKSPACE%\Conf\target.txt" (
@if "%MISSING_TARGET_TEMPLATE%"=="TRUE" @goto MissingTemplates
@echo copying ... target.template to %WORKSPACE%\Conf\target.txt
@copy /Y "%SRC_CONF%\target.template" "%WORKSPACE%\Conf\target.txt" > nul
@set FIRST_COPY=TRUE
)
@if not exist "%WORKSPACE%\Conf\tools_def.txt" (
@if "%MISSING_TOOLS_DEF_TEMPLATE%"=="TRUE" @goto MissingTemplates
@echo copying ... tools_def.template to %WORKSPACE%\Conf\tools_def.txt
@copy /Y "%SRC_CONF%\tools_def.template" "%WORKSPACE%\Conf\tools_def.txt" > nul
@set FIRST_COPY=TRUE
)
@if not exist "%WORKSPACE%\Conf\build_rule.txt" (
@if "%MISSING_BUILD_RULE_TEMPLATE%"=="TRUE" @goto MissingTemplates
@echo copying ... build_rule.template to %WORKSPACE%\Conf\build_rule.txt
@copy /Y "%SRC_CONF%\build_rule.template" "%WORKSPACE%\Conf\build_rule.txt" > nul
@set FIRST_COPY=TRUE
)
@if "%FIRST_COPY%"=="TRUE" @goto End
@if not "%RECONFIG%"=="TRUE" @goto End
@if "%RECONFIG%"=="TRUE" (
@echo.
@echo Over-writing the files in the WORKSPACE\Conf directory
@echo using the default template files
@echo.
@if "%MISSING_TARGET_TEMPLATE%"=="TRUE" @goto MissingTemplates
@echo over-write ... target.template to %WORKSPACE%\Conf\target.txt
@copy /Y "%SRC_CONF%\target.template" "%WORKSPACE%\Conf\target.txt" > nul
@if "%MISSING_TOOLS_DEF_TEMPLATE%"=="TRUE" @goto MissingTemplates
@echo over-write ... tools_def.template to %WORKSPACE%\Conf\tools_def.txt
@copy /Y "%SRC_CONF%\tools_def.template" "%WORKSPACE%\Conf\tools_def.txt" > nul
@if "%MISSING_BUILD_RULE_TEMPLATE%"=="TRUE" @goto MissingTemplates
@echo over-write ... build_rule.template to %WORKSPACE%\Conf\build_rule.txt
@copy /Y "%SRC_CONF%\build_rule.template" "%WORKSPACE%\Conf\build_rule.txt" > nul
@goto End
)
:MissingTemplates
@echo.
@if "%RECONFIG%"=="TRUE" @echo ERROR : Reconfig failed
@if "%MISSING_TARGET_TEMPLATE%"=="TRUE" @echo ERROR : Unable to locate: "%SRC_CONF%\target.template"
@if "%MISSING_TOOLS_DEF_TEMPLATE%"=="TRUE" @echo ERROR : Unable to locate: "%SRC_CONF%\tools_def.template"
@if "%MISSING_BUILD_RULE_TEMPLATE%"=="TRUE" @echo ERROR : Unable to locate: "%SRC_CONF%\build_rule.template"
@echo.
@set MISSING_TARGET_TEMPLATE=
@set MISSING_TOOLS_DEF_TEMPLATE=
@set MISSING_BUILD_RULE_TEMPLATE=
@set FIRST_COPY=
@set SE_VERSION=
@set SE_SVN_REVISION=
@if not "%SCRIPT%"=="EDKSETUP_BAT" @echo on
exit /B 1
:End
@set MISSING_TARGET_TEMPLATE=
@set MISSING_TOOLS_DEF_TEMPLATE=
@set MISSING_BUILD_RULE_TEMPLATE=
@set FIRST_COPY=
@set SE_VERSION=
@set SE_SVN_REVISION=
@if not "%SCRIPT%"=="EDKSETUP_BAT" @echo on
exit /B 0

View file

@ -142,6 +142,7 @@ Returns:
UINTN Number;
EFI_STATUS Status;
EFI_GUID GuidValue;
CHAR8 *XipFlag;
//
// Read the FV base address
@ -325,6 +326,17 @@ Returns:
Status = FindToken (InfFile, FILES_SECTION_STRING, EFI_FILE_NAME_STRING, Index, Value);
if (Status == EFI_SUCCESS) {
//
// Check for ,XIP suffix indicating this file should be rebased
//
XipFlag = strrchr (Value, ',');
if (XipFlag != NULL && stricmp (XipFlag, ",XIP") == 0) {
*XipFlag = '\0';
FvInfo->XipFile[Number + Index] = TRUE;
FvInfo->XipFileCount++;
} else {
FvInfo->XipFile[Number + Index] = FALSE;
}
//
// Add the file
//
@ -1289,7 +1301,7 @@ Returns:
// Rebase the PE or TE image in FileBuffer of FFS file for XIP
// Rebase for the debug genfvmap tool
//
Status = FfsRebase (FvInfo, FvInfo->FvFiles[Index], (EFI_FFS_FILE_HEADER *) FileBuffer, (UINTN) *VtfFileImage - (UINTN) FvImage->FileImage, FvMapFile);
Status = FfsRebase (FvInfo, Index, FvInfo->FvFiles[Index], (EFI_FFS_FILE_HEADER *) FileBuffer, (UINTN) *VtfFileImage - (UINTN) FvImage->FileImage, FvMapFile);
if (EFI_ERROR (Status)) {
Error (NULL, 0, 3000, "Invalid", "Could not rebase %s.", FvInfo->FvFiles[Index]);
return Status;
@ -1335,7 +1347,7 @@ Returns:
// Rebase the PE or TE image in FileBuffer of FFS file for XIP.
// Rebase Bs and Rt drivers for the debug genfvmap tool.
//
Status = FfsRebase (FvInfo, FvInfo->FvFiles[Index], (EFI_FFS_FILE_HEADER *) FileBuffer, (UINTN) FvImage->CurrentFilePointer - (UINTN) FvImage->FileImage, FvMapFile);
Status = FfsRebase (FvInfo, Index, FvInfo->FvFiles[Index], (EFI_FFS_FILE_HEADER *) FileBuffer, (UINTN) FvImage->CurrentFilePointer - (UINTN) FvImage->FileImage, FvMapFile);
if (EFI_ERROR (Status)) {
Error (NULL, 0, 3000, "Invalid", "Could not rebase %s.", FvInfo->FvFiles[Index]);
return Status;
@ -3377,6 +3389,7 @@ Returns:
EFI_STATUS
FfsRebase (
IN OUT FV_INFO *FvInfo,
IN UINTN FileIndex,
IN CHAR8 *FileName,
IN OUT EFI_FFS_FILE_HEADER *FfsFile,
IN UINTN XipOffset,
@ -3451,6 +3464,16 @@ Returns:
return EFI_SUCCESS;
}
//
// If ForceRebase Flag specified to TRUE and at least one file has XIP flag,
// use selective rebase: only rebase files marked with XIP.
// If no files have XIP flag, preserve legacy behavior: rebase all files.
//
if (FvInfo->ForceRebase == 1) {
if (FvInfo->XipFileCount > 0 && !FvInfo->XipFile[FileIndex]) {
return EFI_SUCCESS;
}
}
XipBase = FvInfo->BaseAddress + XipOffset;

View file

@ -209,6 +209,8 @@ typedef struct {
CHAR8 FvName[MAX_LONG_FILE_PATH];
EFI_FV_BLOCK_MAP_ENTRY FvBlocks[MAX_NUMBER_OF_FV_BLOCKS];
CHAR8 FvFiles[MAX_NUMBER_OF_FILES_IN_FV][MAX_LONG_FILE_PATH];
BOOLEAN XipFile[MAX_NUMBER_OF_FILES_IN_FV];
UINT32 XipFileCount;
UINT32 SizeofFvFiles[MAX_NUMBER_OF_FILES_IN_FV];
BOOLEAN IsPiFvImage;
INT8 ForceRebase;
@ -329,6 +331,7 @@ CalculateFvSize (
EFI_STATUS
FfsRebase (
IN OUT FV_INFO *FvInfo,
IN UINTN FileIndex,
IN CHAR8 *FileName,
IN OUT EFI_FFS_FILE_HEADER *FfsFile,
IN UINTN XipOffset,

View file

@ -130,6 +130,8 @@ STATIC UINT32 mHiiRsrcOffset;
STATIC UINT32 mRelocOffset;
STATIC UINT32 mDebugOffset;
STATIC UINT32 mExportOffset;
STATIC UINT32 mBuildIdOffset;
STATIC BOOLEAN mBuildIdFound;
//
// Used for RISC-V relocations.
//
@ -227,6 +229,10 @@ InitializeElf64 (
ElfFunctions->WriteExport = WriteExport64;
}
if (mBuildIdFlag) {
mCoffNbrSections++;
}
return TRUE;
}
@ -290,6 +296,22 @@ IsHiiRsrcShdr (
return (BOOLEAN) (strcmp((CHAR8*)mEhdr + Namedr->sh_offset + Shdr->sh_name, ELF_HII_SECTION_NAME) == 0);
}
STATIC
BOOLEAN
IsBuildIdShdr (
Elf_Shdr *Shdr
)
{
Elf_Shdr *Namedr = GetShdrByIndex(mEhdr->e_shstrndx);
if (Namedr->sh_offset + Shdr->sh_name >= mFileBufferSize) {
Error (NULL, 0, 3000, "Invalid", "IsBuildIdShdr: Name offset %lu is larger then file size %lu", mEhdr->e_shstrndx, mFileBufferSize);
exit(EXIT_FAILURE);
}
return (BOOLEAN) (strcmp((CHAR8*)mEhdr + Namedr->sh_offset + Shdr->sh_name, ELF_BUILD_ID_SECTION_NAME) == 0);
}
STATIC
BOOLEAN
IsSymbolShdr (
@ -1123,6 +1145,40 @@ ScanSections64 (
}
}
//
// The build-ID section.
//
mBuildIdOffset = mCoffOffset;
mBuildIdFound = FALSE;
if (mBuildIdFlag) {
for (i = 0; i < mEhdr->e_shnum; i++) {
Elf_Shdr *shdr = GetShdrByIndex(i);
if (IsBuildIdShdr(shdr)) {
if ((shdr->sh_addralign != 0) && (shdr->sh_addralign != 1)) {
// the alignment field is valid
if ((shdr->sh_addr & (shdr->sh_addralign - 1)) == 0) {
// if the section address is aligned we must align PE/COFF
mCoffOffset = (UINT32) ((mCoffOffset + shdr->sh_addralign - 1) & ~(shdr->sh_addralign - 1));
} else {
Error (NULL, 0, 3000, "Invalid", "Section address not aligned to its own alignment.");
}
}
if (shdr->sh_size != 0) {
mBuildIdOffset = mCoffOffset;
mCoffSectionsOffset[i] = mCoffOffset;
mCoffOffset += (UINT32) shdr->sh_size;
mCoffOffset = CoffAlign(mCoffOffset);
mBuildIdFound = TRUE;
}
break;
}
}
if (!mBuildIdFound) {
Warning (NULL, 0, 0, NULL, "Build ID section is not found in %s.", mInImageName);
}
}
mRelocOffset = mCoffOffset;
//
@ -1242,18 +1298,41 @@ ScanSections64 (
}
}
if ((mRelocOffset - mHiiRsrcOffset) > 0) {
CreateSectionHeader (".rsrc", mHiiRsrcOffset, mRelocOffset - mHiiRsrcOffset,
//
// Determine the end offset for .rsrc section based on whether build-ID is present
//
if (mBuildIdFound) {
Offset = mBuildIdOffset;
} else {
Offset = mRelocOffset;
}
if ((Offset - mHiiRsrcOffset) > 0) {
CreateSectionHeader (".rsrc", mHiiRsrcOffset, Offset - mHiiRsrcOffset,
EFI_IMAGE_SCN_CNT_INITIALIZED_DATA
| EFI_IMAGE_SCN_MEM_READ);
NtHdr->Pe32Plus.OptionalHeader.DataDirectory[EFI_IMAGE_DIRECTORY_ENTRY_RESOURCE].Size = mRelocOffset - mHiiRsrcOffset;
NtHdr->Pe32Plus.OptionalHeader.DataDirectory[EFI_IMAGE_DIRECTORY_ENTRY_RESOURCE].Size = Offset - mHiiRsrcOffset;
NtHdr->Pe32Plus.OptionalHeader.DataDirectory[EFI_IMAGE_DIRECTORY_ENTRY_RESOURCE].VirtualAddress = mHiiRsrcOffset;
} else {
// Don't make a section of size 0.
NtHdr->Pe32Plus.FileHeader.NumberOfSections--;
}
//
// Add build-ID section if requested and found
//
if (mBuildIdFlag) {
if (mBuildIdFound) {
CreateSectionHeader (".bldid", mBuildIdOffset, mRelocOffset - mBuildIdOffset,
EFI_IMAGE_SCN_CNT_INITIALIZED_DATA
| EFI_IMAGE_SCN_MEM_READ);
} else {
// Don't make a section of size 0, decrement the section count
NtHdr->Pe32Plus.FileHeader.NumberOfSections--;
}
}
}
STATIC
@ -1281,6 +1360,9 @@ WriteSections64 (
case SECTION_DATA:
Filter = IsDataShdr;
break;
case SECTION_BUILD_ID:
Filter = IsBuildIdShdr;
break;
default:
return FALSE;
}
@ -1739,16 +1821,24 @@ WriteSections64 (
INT32 LoImm, HiImm;
UINT8 *PreTarg;
Elf_Rela *PreRel;
INT64 SymCoffRva;
INT64 InsnCoffRva;
INT64 PairHiCoffRva;
case R_LARCH_SOP_PUSH_ABSOLUTE:
case R_LARCH_64:
//
// Absolute relocation.
// R_LARCH_SOP_PUSH_ABSOLUTE is an absolute relocation, and
// R_LARCH_64 stores an absolute runtime address in section
// contents. Translate such values from the linked ELF section
// address space to the generated PE/COFF RVA space.
// WriteRelocations64() still emits the PE/COFF base relocation
// for load-time image rebasing.
//
*(UINT64 *)Targ = *(UINT64 *)Targ - SymShdr->sh_addr + mCoffSectionsOffset[Sym->st_shndx];
break;
case R_LARCH_MARK_LA:
case R_LARCH_64:
case R_LARCH_NONE:
case R_LARCH_32:
case R_LARCH_RELATIVE:
@ -1851,29 +1941,32 @@ WriteSections64 (
case R_LARCH_PCALA_HI20:
case R_LARCH_GOT_PC_HI20:
Offset = 0;
SymCoffRva = (INT64)Sym->st_value - (INT64)SymShdr->sh_addr + (INT64)mCoffSectionsOffset[Sym->st_shndx];
InsnCoffRva = (INT64)(UINTN)(Targ - mCoffFile);
if (ELF_R_TYPE(Rel->r_info) == R_LARCH_PCALA_HI20) {
//
// Recover the offset of the ELF PCALAU12I symbol relative to PC.
// Calculate the PE PC-relative offset. SymCoffRva is the
// referenced symbol in the generated PE/COFF RVA space, and
// InsnCoffRva is the PE/COFF RVA of this instruction.
//
Offset = (INT32)((Sym->st_value + Rel->r_addend) - (Rel->r_offset & ~0xFFF));
//
// Calculate the offset of PE PCADDU12I relative to PC.
//
Offset -= (UINTN)(Targ - mCoffFile) & 0xFFF;
Offset = (INT32)((SymCoffRva + Rel->r_addend) - InsnCoffRva);
} else if (ELF_R_TYPE(Rel->r_info) == R_LARCH_GOT_PC_HI20) {
//
// Calculate the offset of PE PCADDU12I relative to PC using the ELF symbol value.
// Convert the referenced symbol from the linked ELF section
// address space to the generated PE/COFF RVA space before
// calculating the PE PC-relative offset. Targ already points
// into the generated PE/COFF image buffer.
//
Offset = Sym->st_value - (UINTN)(Targ - mCoffFile);
Offset = SymCoffRva - InsnCoffRva;
} else {
Error (NULL, 0, 3000, "Invalid", "LoongArch PC related: wrong relocation type.");
break;
}
//
// PCALA or GOT offset is relative to the previous page boundary, whereas PCADD
// offset is relative to the instruction itself.
// So fix up the offset so it points to the page containing the symbol.
// The original PCALA/GOT_PC relocations are page based, but this
// path rewrites the HI/LO pair to PCADDU12I plus ADDI.D. Split
// the generated PE/COFF instruction-relative offset for that pair.
//
HiImm = (UINT32)((Offset + 0x800) >> 12) & 0xFFFFF;
@ -1912,11 +2005,12 @@ WriteSections64 (
}
//
// Calculate the corresponding HI relative to PC using the ELF symbol value and fix the LO offset.
// Calculate the corresponding HI relative to PC using the PE symbol RVA and fix the LO offset.
//
if (ELF_R_TYPE(Rel->r_info) == R_LARCH_PCALA_LO12 && ELF_R_TYPE(PreRel->r_info) == R_LARCH_PCALA_HI20) {
Offset = (INT32)((Sym->st_value + PreRel->r_addend) - (PreRel->r_offset & ~0xFFF));
Offset -= (UINTN)(PreTarg - mCoffFile) & 0xFFF;
SymCoffRva = (INT64)Sym->st_value - (INT64)SymShdr->sh_addr + (INT64)mCoffSectionsOffset[Sym->st_shndx];
PairHiCoffRva = (INT64)(UINTN)(PreTarg - mCoffFile);
Offset = (INT32)((SymCoffRva + PreRel->r_addend) - PairHiCoffRva);
LoImm = (UINT32)(Offset & 0xFFF);
//
// Only fill the LO offset in corresponding instructions.
@ -1924,7 +2018,9 @@ WriteSections64 (
*(UINT32 *)Targ &= 0xFFC003FF;
*(UINT32 *)Targ |= LoImm << 10;
} else if (ELF_R_TYPE(Rel->r_info) == R_LARCH_GOT_PC_LO12 && ELF_R_TYPE(PreRel->r_info) == R_LARCH_GOT_PC_HI20) {
Offset = Sym->st_value - (UINTN)(PreTarg - mCoffFile);
SymCoffRva = (INT64)Sym->st_value - (INT64)SymShdr->sh_addr + (INT64)mCoffSectionsOffset[Sym->st_shndx];
PairHiCoffRva = (INT64)(UINTN)(PreTarg - mCoffFile);
Offset = SymCoffRva - PairHiCoffRva;
LoImm = (UINT32)(Offset & 0xFFF);
//
// Convert this instruction as ADDI.D and fill the LO offset into it.

View file

@ -210,6 +210,11 @@ ConvertElf (
if (!ElfFunctions.WriteSections (SECTION_HII)) {
return FALSE;
}
if (mBuildIdFlag) {
if (!ElfFunctions.WriteSections (SECTION_BUILD_ID)) {
return FALSE;
}
}
//
// Translate and write relocations.

View file

@ -24,14 +24,16 @@ extern UINT32 mTableOffset;
extern UINT32 mOutImageType;
extern UINT32 mFileBufferSize;
extern BOOLEAN mExportFlag;
extern BOOLEAN mBuildIdFlag;
//
// Common EFI specific data.
//
#define ELF_HII_SECTION_NAME ".hii"
#define ELF_STRTAB_SECTION_NAME ".strtab"
#define MAX_COFF_ALIGNMENT 0x10000
#define ELF_SYMBOL_SECTION_NAME ".symtab"
#define ELF_HII_SECTION_NAME ".hii"
#define ELF_STRTAB_SECTION_NAME ".strtab"
#define MAX_COFF_ALIGNMENT 0x10000
#define ELF_SYMBOL_SECTION_NAME ".symtab"
#define ELF_BUILD_ID_SECTION_NAME ".build-id"
//
// Platform Runtime Mechanism (PRM) specific data.
@ -77,7 +79,8 @@ typedef enum {
SECTION_TEXT,
SECTION_HII,
SECTION_DATA,
SECTION_SYMBOL
SECTION_SYMBOL,
SECTION_BUILD_ID
} SECTION_FILTER_TYPES;
//

View file

@ -89,6 +89,7 @@ UINT32 mOutImageType = FW_DUMMY_IMAGE;
BOOLEAN mIsConvertXip = FALSE;
BOOLEAN mExportFlag = FALSE;
BOOLEAN mNoNxCompat = FALSE;
BOOLEAN mBuildIdFlag = FALSE;
STATIC
EFI_STATUS
@ -290,6 +291,10 @@ Returns:
fprintf (stdout, " --nonxcompat Do not set the IMAGE_DLLCHARACTERISTICS_NX_COMPAT bit \n\
of the optional header in the PE header even if the \n\
requirements are met.\n");
fprintf (stdout, " --build-id Preserve the .build-id section from the ELF image\n\
and copy it to a .bldid section in the PE image.\n\
This option can be used together with -e or -t.\n\
It doesn't work for other options.\n");
fprintf (stdout, " -v, --verbose Turn on verbose output with informational messages.\n");
fprintf (stdout, " -q, --quiet Disable all messages except key message and fatal error\n");
fprintf (stdout, " -d, --debug level Enable debug messages, at input debug level.\n");
@ -1576,6 +1581,13 @@ Returns:
continue;
}
if (stricmp (argv[0], "--build-id") == 0) {
mBuildIdFlag = TRUE;
argc--;
argv++;
continue;
}
if (argv[0][0] == '-') {
Error (NULL, 0, 1000, "Unknown option", argv[0]);
goto Finish;

View file

@ -218,6 +218,7 @@ class AutoGenWorkerInProcess(mp.Process):
GlobalData.gEnableGenfdsMultiThread = self.data_pipe.Get("EnableGenfdsMultiThread")
GlobalData.gPlatformFinalPcds = self.data_pipe.Get("gPlatformFinalPcds")
GlobalData.file_lock = self.file_lock
GlobalData.gLogLibraryMismatch = False
CommandTarget = self.data_pipe.Get("CommandTarget")
pcd_from_build_option = []
for pcd_tuple in self.data_pipe.Get("BuildOptPcd"):

View file

@ -3,6 +3,7 @@
#
# Copyright (c) 2019 - 2020, Intel Corporation. All rights reserved.<BR>
# Copyright (c) 2020, ARM Limited. All rights reserved.<BR>
# Copyright (c) 2026, American Megatrends International LLC. All rights reserved.<BR>
# SPDX-License-Identifier: BSD-2-Clause-Patent
#
from Common.caching import cached_property
@ -11,6 +12,7 @@ import Common.LongFilePathOs as os
from Common.BuildToolError import *
from Common.Misc import SaveFileOnChange, PathClass
from Common.Misc import TemplateString
from collections import deque
import sys
gIsFileMap = {}
@ -191,12 +193,28 @@ ${END}
return
ModuleDepDict = {}
current_source = ""
current_source_abs = ""
SourceFileAbsPathMap = self.SourceFileList
namesake_queue = {}
cc_cmd_in_output = False
if self.HasNamesakeSourceFile:
basename_to_paths = {}
for _, (_, input_file) in sorted(self.TargetFileList.items()):
basename = os.path.basename(input_file.File)
if not basename:
continue
if basename not in basename_to_paths:
basename_to_paths[basename] = []
basename_to_paths[basename].append(input_file.Path)
namesake_queue = {
k: deque(v) for k, v in basename_to_paths.items() if len(v) > 1
}
for line in DepList:
line = line.strip()
if self.HasNamesakeSourceFile:
for cc_cmd in self.CcPPCommandPathSet:
if cc_cmd in line:
cc_cmd_in_output = True
if '''"'''+cc_cmd+'''"''' in line:
cc_options = line[len(cc_cmd)+2:].split()
else:
@ -214,13 +232,18 @@ ${END}
# SourceFileAbsPathMap = {os.path.basename(item):item for item in cc_options if not item.startswith("/") and os.path.exists(item)}
if line in SourceFileAbsPathMap:
current_source = line
if current_source not in ModuleDepDict:
ModuleDepDict[SourceFileAbsPathMap[current_source]] = []
if (self.HasNamesakeSourceFile and not cc_cmd_in_output
and line in namesake_queue and namesake_queue[line]):
current_source_abs = namesake_queue[line].popleft()
else:
current_source_abs = SourceFileAbsPathMap[current_source]
if current_source_abs not in ModuleDepDict:
ModuleDepDict[current_source_abs] = []
elif "Note: including file:" == line.lstrip()[:21]:
if not current_source:
EdkLogger.error("build",BUILD_ERROR, "Parse /showIncludes output failed. line: %s. \n" % line, RaiseError=False)
else:
ModuleDepDict[SourceFileAbsPathMap[current_source]].append(line.lstrip()[22:].strip())
ModuleDepDict[current_source_abs].append(line.lstrip()[22:].strip())
for source_abs in ModuleDepDict:
if ModuleDepDict[source_abs]:

View file

@ -124,3 +124,4 @@ gSikpAutoGenCache = set()
file_lock = None
gStackCookieValues32 = []
gStackCookieValues64 = []
gLogLibraryMismatch = True

View file

@ -41,7 +41,7 @@ MODEL_IDENTIFIER_MACRO_IFDEF = 2012
MODEL_IDENTIFIER_MACRO_IFNDEF = 2013
MODEL_IDENTIFIER_MACRO_DEFINE = 2014
MODEL_IDENTIFIER_MACRO_ENDIF = 2015
MODEL_IDENTIFIER_MACRO_PROGMA = 2016
MODEL_IDENTIFIER_MACRO_PRAGMA = 2016
MODEL_IDENTIFIER_FUNCTION_CALLING = 2018
MODEL_IDENTIFIER_TYPEDEF = 2017
MODEL_IDENTIFIER_FUNCTION_DECLARATION = 2019
@ -133,7 +133,7 @@ MODEL_LIST = [('MODEL_UNKNOWN', MODEL_UNKNOWN),
('MODEL_IDENTIFIER_MACRO_IFNDEF', MODEL_IDENTIFIER_MACRO_IFNDEF),
('MODEL_IDENTIFIER_MACRO_DEFINE', MODEL_IDENTIFIER_MACRO_DEFINE),
('MODEL_IDENTIFIER_MACRO_ENDIF', MODEL_IDENTIFIER_MACRO_ENDIF),
('MODEL_IDENTIFIER_MACRO_PROGMA', MODEL_IDENTIFIER_MACRO_PROGMA),
('MODEL_IDENTIFIER_MACRO_PRAGMA', MODEL_IDENTIFIER_MACRO_PRAGMA),
('MODEL_IDENTIFIER_FUNCTION_CALLING', MODEL_IDENTIFIER_FUNCTION_CALLING),
('MODEL_IDENTIFIER_TYPEDEF', MODEL_IDENTIFIER_TYPEDEF),
('MODEL_IDENTIFIER_FUNCTION_DECLARATION', MODEL_IDENTIFIER_FUNCTION_DECLARATION),

View file

@ -249,6 +249,7 @@ class RuleClassObject :
self.FvFileType = None # for Ffs File Type
self.KeyStringList = []
self.KeepReloc = None
self.Xip = False
## Complex rule data in FDF
#

View file

@ -575,6 +575,75 @@ class Check(object):
def IncludeFileCheck(self):
self.IncludeFileCheckData()
self.IncludeFileCheckSameName()
self.IncludeFileCheckPragmaOnce()
# Check whether include files use '#pragma once' instead of a traditional #ifndef/#define include guard
def IncludeFileCheckPragmaOnce(self):
if EccGlobalData.gConfig.IncludeFileCheckPragmaOnce == '1' or EccGlobalData.gConfig.IncludeFileCheckAll == '1' or EccGlobalData.gConfig.CheckAll == '1':
EdkLogger.quiet("Checking if header file uses '#pragma once' ...")
# Build the set of header files to check, indexed by File table ID.
HeaderFileSet = {}
SqlCommand = """select ID, FullPath, ExtName from File where ExtName in ('h')"""
for Record in EccGlobalData.gDb.TblFile.Exec(SqlCommand):
if Record[2].upper() not in EccGlobalData.gConfig.BinaryExtList:
HeaderFileSet[Record[0]] = Record[1]
if not HeaderFileSet:
return
#
# The preprocessor directives of each source file are parsed into the
# identifier table(s) with their actual line numbers. Reporting against
# those rows (instead of the File table) gives an accurate line number,
# which is required by the incremental EccCheck plugin that filters
# findings by the changed line ranges of a commit.
#
for IdentifierTable in EccGlobalData.gIdentifierTableList:
SqlCommand = """select ID, Value, BelongsToFile from %s
where Model in (%s, %s, %s)
order by BelongsToFile, StartLine, ID""" \
% (IdentifierTable,
MODEL_IDENTIFIER_MACRO_IFNDEF,
MODEL_IDENTIFIER_MACRO_DEFINE,
MODEL_IDENTIFIER_MACRO_PRAGMA)
RecordSet = EccGlobalData.gDb.TblFile.Exec(SqlCommand)
# Group the parsed directives by the file they belong to.
FileRecordDict = {}
for Record in RecordSet:
if Record[2] not in HeaderFileSet:
continue
FileRecordDict.setdefault(Record[2], []).append(Record)
for FileId, Records in FileRecordDict.items():
Path = mws.relpath(HeaderFileSet[FileId], EccGlobalData.gWorkspace)
if EccGlobalData.gException.IsException(ERROR_INCLUDE_FILE_CHECK_PRAGMA_ONCE, Path):
continue
# Walk the directives in file order. '#pragma once' makes the file
# compliant. Otherwise a '#ifndef NAME' directly followed by a
# valueless '#define NAME' is treated as a traditional include guard.
PragmaOnceFound = False
GuardRecord = None
PrevIfndef = None
for Record in Records:
Content = Record[1].strip().splitlines()[0].strip() if Record[1].strip() else ''
if re.match(r'#\s*pragma\s+once\b', Content):
PragmaOnceFound = True
break
MatchIfndef = re.match(r'#\s*ifndef\s+(\w+)', Content)
if MatchIfndef:
PrevIfndef = (MatchIfndef.group(1), Record)
continue
MatchDefine = re.match(r'#\s*define\s+(\w+)\s*(//.*|/\*.*)?$', Content)
if MatchDefine and PrevIfndef and MatchDefine.group(1) == PrevIfndef[0]:
GuardRecord = PrevIfndef[1]
break
PrevIfndef = None
if not PragmaOnceFound and GuardRecord is not None:
OtherMsg = "Include file [%s] uses a traditional #ifndef/#define include guard, please use '#pragma once' instead" % Path
EccGlobalData.gDb.TblReport.Insert(ERROR_INCLUDE_FILE_CHECK_PRAGMA_ONCE, OtherMsg=OtherMsg, BelongsToTable=IdentifierTable, BelongsToItem=GuardRecord[0])
# Check whether having include files with same name
def IncludeFileCheckSameName(self):

View file

@ -71,6 +71,7 @@ _ConfigFileToInternalTranslation = {
"HeaderCheckFunction":"HeaderCheckFunction",
"IncludeFileCheckAll":"IncludeFileCheckAll",
"IncludeFileCheckData":"IncludeFileCheckData",
"IncludeFileCheckPragmaOnce":"IncludeFileCheckPragmaOnce",
"IncludeFileCheckSameName":"IncludeFileCheckSameName",
"MetaDataFileCheckAll":"MetaDataFileCheckAll",
"MetaDataFileCheckBinaryInfInFdf":"MetaDataFileCheckBinaryInfInFdf",
@ -243,6 +244,8 @@ class Configuration(object):
# Check whether include files contain only public or only private data
# Check whether include files NOT contain code or define data variables
self.IncludeFileCheckData = 1
# Check whether include files use '#pragma once' instead of a traditional #ifndef/#define include guard
self.IncludeFileCheckPragmaOnce = 1
## Declarations and Data Types Checking
self.DeclarationDataTypeCheckAll = 0

View file

@ -45,6 +45,7 @@ ERROR_C_FUNCTION_LAYOUT_CHECK_FUNCTION_PROTO_TYPE_3 = 5010
ERROR_INCLUDE_FILE_CHECK_ALL = 6000
ERROR_INCLUDE_FILE_CHECK_DATA = 6004
ERROR_INCLUDE_FILE_CHECK_NAME = 6005
ERROR_INCLUDE_FILE_CHECK_PRAGMA_ONCE = 6006
ERROR_DECLARATION_DATA_TYPE_CHECK_ALL = 7000
ERROR_DECLARATION_DATA_TYPE_CHECK_NO_USE_C_TYPE = 7001
@ -139,6 +140,7 @@ gEccErrorMessage = {
ERROR_INCLUDE_FILE_CHECK_ALL : "",
ERROR_INCLUDE_FILE_CHECK_DATA : "Include files should contain only public or only private data and cannot contain code or define data variables",
ERROR_INCLUDE_FILE_CHECK_NAME : "No permission for the include file with same names",
ERROR_INCLUDE_FILE_CHECK_PRAGMA_ONCE : "Include files should use '#pragma once' instead of a traditional #ifndef/#define include guard",
ERROR_DECLARATION_DATA_TYPE_CHECK_ALL : "",
ERROR_DECLARATION_DATA_TYPE_CHECK_NO_USE_C_TYPE : "There should be no use of int, unsigned, char, void, long in any .c, .h or .asl files",

View file

@ -75,7 +75,7 @@ def GetIdType(Str):
elif List[1] == 'endif':
Type = DataClass.MODEL_IDENTIFIER_MACRO_ENDIF
elif List[1] == 'pragma':
Type = DataClass.MODEL_IDENTIFIER_MACRO_PROGMA
Type = DataClass.MODEL_IDENTIFIER_MACRO_PRAGMA
else:
Type = DataClass.MODEL_UNKNOWN
return Type

View file

@ -137,6 +137,8 @@ IncludeFileCheckSameName = 1
# Check whether include files contain only public or only private data
# Check whether include files NOT contain code or define data variables
IncludeFileCheckData = 1
# Check whether include files use '#pragma once' instead of a traditional #ifndef/#define include guard
IncludeFileCheckPragmaOnce = 1
#
# Declarations and Data Types Checking

Some files were not shown because too many files have changed in this diff Show more