Commit graph

1862 commits

Author SHA1 Message Date
Joey Vagedes
c5aa7e7d94 BaseTools/Build: Output warning message for library class mismatch
Performs a check that will verify that the library instance implements
the library specified in the dsc by ensuring a LIBRARY_CLASS definition
exists in the INF [Defines] section and the value matches the library it
says it is implementing.

As an example, from a platform dsc file:
BaseBmpSupportLib|MdeModulePkg/Library/BaseBmpSupportLib/BaseBmpSupportLib.inf

BaseBmpSupportLib is supposed to be of library class BmpSupportLib, but the
dsc defines it incorrectly, the warning message will be displayed during
build.

Signed-off-by: Aaron Pop <aaronpop@microsoft.com>
Co-authored-by: Poncho Figueroa <poncho.figueroa.esqueda@intel.com>
2026-08-06 04:55:34 +00:00
Phil Noh
d45f882a1b BaseTools: Fix Clang -Wtautological-overlap-compare in PcdValueInit.c
For each structured-PCD field copied via memcpy, DscBuildData.py
emits the clamp expression, '(FieldSize > 0 && FieldSize < ValueSize) ?
FieldSize : ValueSize'. When ValueSize == 1 and FieldSize is unsigned,
it reduces to (FieldSize > 0 && FieldSize < 1) - always-false comparison.

Clang flags it under -Wtautological-overlap-compare, and because
PcdValueInit builds with -Werror, autogen fails and the build aborts with
'PcdValueInit.c: error: overlapping comparisons always evaluate to false
[-Werror,-Wtautological-overlap-compare]'. This is specific to Clang host.

To fix it, this update changes '<' to '<=' at all five generator sites in
DscBuildData.py (GenerateDefaultValueAssignFunction,
GenerateInitValueFunction, GenerateCommandLineValue,
GenerateModuleScopeValue, GenerateFdfValue). Behavior is unchanged:
both branches copy the same byte count when FieldSize == ValueSize.
GCC and MSVC builds are unaffected.

Signed-off-by: Phil Noh <Phil.Noh@amd.com>
2026-08-01 16:17:54 +00:00
Chris Fernald
27ac8fac0b BaseTools: Add support for preserving build ID
Adds an optional flag that copies the GNU build-id note from the input
ELF file into the output PE/COFF firmware image as a dedicated ".bldid"
section. The build ID is emitted by the linker as a unique fingerprint
of the binary and allows custom post-build and debugging tools to
reliably match a firmware image against its corresponding unstripped
ELF and debug symbols, without relying on file names, timestamps, or
build paths.

This notable opts to use a non-standard section name ".bldid" to store
the build ID. This approach was chosen to keep genfw and the parsers simple
since the full "build-id" name would require redirecting the section name.
While this breaks from standard conventions, this is not impactful since
GenFW is already creating a non-standard artifact for the PE image with
the associated ELF symbol file.

Signed-off-by: Chris Fernald <chfernal@microsoft.com>
2026-07-22 18:06:03 +00:00
Michael Kubacki
a59064933f BaseTools/Trim.py: Strip "#pragma once" from inlined ASL content
When Trim processes an ASL file (`--asl-file`), it textually inlines
the body of every `Include()`'d file directly into the constructed
preprocessor input, once per include site.

Its has duplicate protection in the form of a circular-include stack
(`gIncludedAslFile`), that prevents A->B->A cycles. But, as far as
the script is concerned, each `Include()` is a unique include site.

Various combinations of includes and file types are possible and
handled slightly differently.

Starting with file types as defined in
BaseTools\Conf\build_rule.template:

- `.aslc`, `.act` files fall under `Acpi-Table-Code-File` and are
  compiled, linked, and processed by genfw.
- `.asl`, `.Asl`, and `.ASL` files fall in `Acpi-Source-Language-File`
  and are processed by Trim:
  1. `Trim --asl-file` to produce a single combined .i file with
     includes inlined.
  2. `ASLPP` (ASL preprocessor, a C preprocessor) on the output of
     Trim to produce a .iii file with all macros expanded and
     conditional branches resolved. AutoGen.h is also included and
     processed here to resolve fixed PCD values if needed.
  3. `Trim --source-code` which takes the pre-processed .iii file and
     produces a .iiii file with content like linemarkers cleaned up.
  4. The ACPI compiler compiles the .iiii file to produce AML bytecode
     in a .aml file.

Because the `.aslc`/`.act` files are directly passed to normal C
processing tools, they are not part of the Trim change made in this
commit and the remainder of this message focuses on the ACPI Source
Language File case.

ASL files can use either an ASL `Include()` directive or a C-style
`#include` directive. In addition, different file types may be
included such as a `.asl` file or a `.h` file.

`Trim` handles these cases differently:

- For ASL `Include()` directives, `Trim` inlines the content of the
  included file directly into the output at the include site. This is
  done for all included ASL files regardless of their extension. The
  inlining is purely textual and does not attempt to resolve or
  preserve any preprocessor directives such as `#pragma once` or
  include guards.
- For C-style `#include` directives, `Trim` checks the file extension
  of the included file. If the file is an ASL file (`.asl` or `.asi`),
  `Trim` treats the file the same as the `Include()` case. Otherwise,
  `Trim` passes the directive through verbatim to the output, allowing
  the downstream C preprocessor (`ASLPP`) to handle it according to
  normal C preprocessor rules.

This creates a situtation in which the resulting `.i` might include:

- Inlined file content (from a `.asl` or `.h` file) depending on the
  include type and file extension.
- Verbatim `#include` directives for non-ASL files which will be
  processed by the C preprocessor.

Focusing on the "inlined" case, historically `.h` files would have
traditional C include guards (`#ifndef`/`#define`, `#endif`). However,
files might also include `#pragma once` as a guard.

In that case, the inlined content of the `.i` file could contain
multiple `#pragma once` directives, one per include site. When the
C preprocessor (`ASLPP`) processes the `.i` file, it sees multiple
`#pragma once` directives in what it considers the main file, and
could emit a warning like the following from gcc:

  warning: '#pragma once' in main file [-Wpragma-once-outside-header]

The remainder of this commit message describes the change made to
address this warning.

This change strips "#pragma once" lines on the ASL content path in
`DoInclude()` in `Trim.py` so the directive is removed before it
reaches the C preprocessor.

  - "#include" directives for non-ASL files are still passed through
    verbatim for the C preprocessor to resolve where the contents of
    those .h files might contain "#pragma once" or traditional guards.
  - Traditional include guards are untouched and continue to behave as
    before where multiple include sites might inline the same content
    in the .i file before reaching the C preprocessor.

The change:

In the case that a file is inlined with a `#pragma once` directive,
the directive is stripped from the inlined content which prevents the
warning.

This is considered acceptable because it only removes the
`#pragma once` directive from the inlined content for these specific
cases. So, the `.i` file might contain multiple inlined copies of the
same header content (like always in this inline case) but without the
`#pragma once` directives. Because actual C content was already not
processed or trimmed out (e.g. `typedef struct`) duplicate content is
not considered to be a problem (`#define` multiple times is not a
problem for the C preprocessor).

Signed-off-by: Michael Kubacki <michael.kubacki@microsoft.com>
2026-07-17 21:50:16 +00:00
kowsiks
2fc0e060ef BaseTools/build.py: Use full source file path for dependency generation
During Silent build,NMAKE suppresses the command echo entirely.
As a result, the only output in ProcOut is the
MSVC compiler’s output lines.
Without the command echo, there is no full path in the output to
identify which source file is currently being compiled.
For unique basenames this is not an issue, but for namesake files
(for example, AmdSev.c located in different directories),
it is impossible to determine which file’s includes are being listed.

This change improves dependency generation for MSVC builds by introducing
explicit handling for source files with duplicate basenames
(namesake sources). A new variable current_source_abs is added to
consistently track the resolved absolute path of the active source file
instead of repeatedly recomputing it from SourceFileAbsPathMap.
To correctly resolve namesake files in silent builds
(where compiler commands are not echoed), a namesake_queue is introduced,
which preserves source ordering and sequentially maps basename occurrences
to their corresponding full paths.
Additionally, a cc_cmd_in_output flag is implemented to detect the presence
of compiler command lines in the output stream; when present,
source paths are derived directly from command-line arguments, otherwise
the queue-based resolution is used. This ensures correct mapping of
basenames to absolute paths across the silent builds, fixing incorrect
dependency generation when multiple source files share the same name.

Signed-off-by: Kowsik S <kowsiks@ami.com>
2026-07-17 10:54:11 +00:00
Michael D Kinney
0347d3b711 BaseTools/GenFv: Preserve legacy rebase behavior when Xip is unused
Add XipFileCount to FV_INFO to track how many files have the ,XIP
suffix. Update FfsRebase() to only apply selective XIP rebase when
XipFileCount > 0. When no files have the ,XIP suffix (XipFileCount
== 0), preserve the legacy ForceRebase=TRUE behavior of rebasing all
files. This maintains backward compatibility for existing platforms
that use FvForceRebase=TRUE without any Xip rules.

Signed-off-by: Michael D Kinney <michael.d.kinney@intel.com>
2026-07-15 21:37:05 +00:00
Christopher Zurcher
a62292ba94 BaseTools/GenFds: Print INF name on Depex eval failure
Signed-off-by: Christopher Zurcher <christopher.zurcher@microsoft.com>
2026-07-09 09:58:04 +00:00
Michael Kubacki
35b5565764 BaseTools/Ecc: Add check for traditional include guards
Adds a new ECC check, `IncludeFileCheckPragmaOnce` (error code 6006),
that flags header files using a traditional `#ifndef`/`#define`
include guard and recommends `#pragma once` instead.

A guard is detected when a '#ifndef NAME' is immediately followed by a
valueless '#define NAME' using the same macro name. Feature macros
such as '#define FOO 1' and files already using '#pragma once' are not
flagged.

The check reports against the parsed preprocessor directive rows in
the identifier tables rather than the File table. Those rows carry the
actual source line number, whereas File-level findings resolve to
"line 1" in the report. This gives an accurate line number, to the
EccCheck CI plugin, so it can reconcile findings with the changed line
ranges of a commit.

It uses the binary extension list and the exception list, consistent
with the other include file checks.

Signed-off-by: Michael Kubacki <michael.kubacki@microsoft.com>
2026-06-26 02:18:38 +00:00
Michael Kubacki
4b27e8e20b BaseTools: Fix MODEL_IDENTIFIER_MACRO_PROGMA typo
Fixes typo in the constant name.

Signed-off-by: Michael Kubacki <michael.kubacki@microsoft.com>
2026-06-26 02:18:38 +00:00
Kirk Chou
34a3cc89de BaseTools/Build: Fix arch macro expansion scope in DSC parser
Signed-off-by: Kirk Chou <kirk.chou@hpe.com>
2026-06-23 02:21:25 +00:00
Michael D Kinney
57164cdc87 BaseTools/GenFds: Fix FV attribute parser to allow any keyword order
Fix _GetFvAttributes() to return True when it has successfully parsed
at least one attribute before encountering a non-attribute keyword.
Previously it always returned False on encountering an unrecognized
word, even after consuming prior attributes. This caused the outer
parsing loop to break prematurely when FvForceRebase, FvBaseAddress,
or FvAlignment appeared between FV attribute flags (e.g. between
ERASE_POLARITY and MEMORY_MAPPED), resulting in a Python stack trace.

Move IsWordToken assignment to after successful attribute parsing and
change the early return from 'return False' to 'return IsWordToken'.

Signed-off-by: Michael D Kinney <michael.d.kinney@intel.com>
2026-06-22 15:18:12 +00:00
Michael D Kinney
d6eb4c4965 BaseTools/GenFds: Allow PE32 section keywords in any order
Replace sequential if-statements for Align, Xip, and
RELOCS_STRIPPED/RELOCS_RETAINED parsing in _GetEfiSection() with a
while-loop that accepts these keywords in any permutation. Previously,
specifying Xip before Align in a [Rule] PE32 section caused a Python
stack trace.

Signed-off-by: Michael D Kinney <michael.d.kinney@intel.com>
2026-06-22 15:18:12 +00:00
Michael D Kinney
3ee3b60eb8 BaseTools/GenFv: Parse ,XIP suffix for per-file rebase control
Update ParseFvInf() to detect and strip ",XIP" suffix from
EFI_FILE_NAME values in the FV INF file. Store the per-file XIP
flag in the new XipFile[] array in the FV_INFO structure.

Add FileIndex parameter to FfsRebase() so it can look up the XIP
flag for the current file. When ForceRebase is TRUE, only rebase
files that have their XipFile[] entry set to TRUE.

Signed-off-by: Michael D Kinney <michael.d.kinney@intel.com>
2026-06-22 15:18:12 +00:00
Michael D Kinney
adc5e8d009 BaseTools/GenFds: Propagate Xip flag to FV INF via ,XIP suffix
Add Xip attribute to FDF Rule class and parse the Xip keyword in
EFI section rules of FDF files. Add XipEnabled attribute to
FfsInfStatement that is determined from the applicable FDF Rule's
section Xip setting. When generating the FV INF file, append ",XIP"
to EFI_FILE_NAME entries for modules whose Rule specifies Xip=TRUE.

This enables per-file XIP rebase control in GenFv by communicating
which files require XIP rebase directly in the FV INF file format.

Signed-off-by: Michael D Kinney <michael.d.kinney@intel.com>
2026-06-22 15:18:12 +00:00
Dongyan Qian
0225975462 BaseTools/GenFw: Fix LoongArch ELF-to-PE RVA conversion
GenFw converts linked ELF images to PE/COFF images using a new section
layout. The generated PE/COFF section RVAs are not required to match the
linked ELF section addresses, so relocation fixups that rewrite section
contents must use the generated PE/COFF RVA space.

A linker script layout change can expose this on LoongArch64 when .text
and .data are linked with 0x1000 alignment while .hii still keeps a
0x4000 alignment. GenFw then keeps a 0x4000 PE/COFF section alignment
because of .hii, producing different ELF and PE/COFF layouts.

Fix two LoongArch relocation paths exposed by this layout mismatch.
R_LARCH_64 entries stored in section contents, such as switch jump
tables, must be translated from the linked ELF section address space to
the generated PE/COFF RVA space. R_LARCH_PCALA_* and R_LARCH_GOT_PC_*
must also convert the referenced symbol to its generated PE/COFF RVA
before calculating the PC-relative offset.

The LoongArch ELF ABI defines PCALA/GOT_PC relocations as page-based,
but this GenFw path rewrites the HI/LO pair to PCADDU12I plus ADDI.D.
After that rewrite, the offset split must be based on the generated
PE/COFF instruction-relative offset.

For example, in the failing LogoDxe image, _gUefiDriverRevision is at
ELF address 0x5400 in .text, and the relocation referencing it is at ELF
address 0x104c. With ELF .text at 0x1000 and PE/COFF .text at 0x4000,
the generated PE/COFF RVAs are 0x8400 for the symbol and 0x404c for the
relocation site. Mixing the ELF symbol address with the PE/COFF
relocation-site RVA makes the entry wrapper read PE/COFF RVA 0x5400
instead of 0x8400, causing EFI_INCOMPATIBLE_VERSION.

Use PE/COFF RVAs consistently when rewriting LoongArch absolute and
PC-relative references during WriteSections64(). The existing
WriteRelocations64() base relocation emission is kept for load-time
image rebasing.

Reported-by: Chao Li <lichao@loongson.cn>
Signed-off-by: Dongyan Qian <qiandongyan@loongson.cn>
Signed-off-by: Chao Li <lichao@loongson.cn>
Tested-by: Dongyan Qian <qiandongyan@loongson.cn>
2026-06-22 03:36:43 +00:00
Chao Li
1416dcb8df BaseTools: Adjust the LoongArch PC related static relocation
The relocation methods of R_LARCH_PCALA_HI20, R_LARCH_PCALA_LO12,
R_LARCH_GOT_PC_HI20 and R_LARCH_GOT_PC_LO12 have been optimized to
support cases where HI is not adjacent to LO and where one HI
corresponds to multiple LOs.

Signed-off-by: Chao Li <lichao@loongson.cn>
Cc: Liming Gao <gaoliming@byosoft.com.cn>
Cc: Guillermo Antonio Palomino Sosa <guillermo.a.palomino.sosa@intel.com>
Cc: Yuwei Chen <yuwei.chen@intel.com>
Cc: Poncho Figueroa <poncho.figueroa.esqueda@intel.com>
Cc: Mike Beaton <mjsbeaton@gmail.com>
2026-05-26 13:07:30 +00:00
Jason1 Lin
ddd94f778b BaseTools/Capsule: Prevent to Read the STDOUT Content as Signature
- Within the capsule generate script, it is using the STDOUT result
  as signature while signing the hash digest via OpenSSL tool.

- There would have incorrect result when the user terminal have
  the output when executing the startup script.

- Incorrect the content of signature would make the verification failed.

- Use the "-output" flag to export the signature then read it back
  as the resolution.

Signed-off-by: Jason1 Lin <jason1.lin@intel.com>
2026-05-26 06:51:14 +00:00
Qihang Gao
5e2bea1a74 BaseTools: Add missing machine types while dumping Option Rom
When dumping LOONGARCH64 or RISCV64 Option Rom by `EfiRom -d test.rom`
command, the machine type is showed as `unknown`. This patch adds type
lookup strings for the two architectures.

Signed-off-by: Qihang Gao <gaoqihang@loongson.cn>
2026-04-23 05:31:47 +00:00
Oliver Smith-Denny
be4fc071eb BaseTools: Reject Inline Comments in tools_def
There is a bug in BaseTools currently when an inline
comment is used in tools_def. The comment is not
stripped out and wreaks havoc down the line,
causing BaseTools to get confused elsewhere and
drop build options it should be applying.

This fixes that behavior by following the build spec
which states:

Comments are only allows on separate lines and may not
be appended appear on actual entry lines.

Inline comments are now not allowed and the build will
fail and specify why and where.

Signed-off-by: Oliver Smith-Denny <osde@microsoft.com>
2026-04-21 00:18:43 +00:00
Oliver Smith-Denny
35c03c1c9f BaseTools: Ecc: Update to ANTLR 4.13.2
ANTLR 4.9 is broken in python 3.13 because
it uses a library in the autogenerated files
that is removed.

This updates to 4.13.2 and also updates the autogen
files, which contain support for python 3.13 as well
as backwards compat.

Signed-off-by: Oliver Smith-Denny <osde@microsoft.com>
2026-04-08 22:23:35 +00:00
Oliver Smith-Denny
9b676f7cc2 BaseTools: Ecc: Use SPDX in AutoGen Template
The ANTLR autogen files are currently created
without an SPDX identifer. Add the BSD-2-Clause-Patent
ID.

While here, correct the command to do the autogeneration
by using the right filename.

Signed-off-by: Oliver Smith-Denny <osde@microsoft.com>
2026-04-08 22:23:35 +00:00
Oliver Smith-Denny
229600664e BaseTools: Ecc: Drop ANTLR 3 Support
BaseTools hasn't been using ANTLR3 since at
least 2019. Drop the files.

Signed-off-by: Oliver Smith-Denny <osde@microsoft.com>
2026-04-08 22:23:35 +00:00
Kun Qin
ef23e3c9e7 BaseTools: Enable control flow guard for Windows builds
Certain environments require Control Flow Guard (CFG) to be enabled at
build time as part of their security hardening requirements.

This change adds the necessary compiler and linker flags to enable CFG
support.

Signed-off-by: Kun Qin <kun.qin@microsoft.com>
2026-03-26 02:28:23 +00:00
Kun Qin
4e0376c48b BaseTools: Suppress C4028 warning to support older VS toolchain builds
Add conditional suppression of MSVC warning C4028 (formal parameter
different from declaration) when building with Visual Studio 2017 or
earlier toolchain.

This warning is triggered by brotli submodule and not emitted by newer
compilers, hence a conditional supression is used.

Signed-off-by: Kun Qin <kun.qin@microsoft.com>
2026-03-26 02:28:23 +00:00
Kun Qin
8c298e1104 BaseTools: GenFfs/GenFv/GenSec: Fixing Warning 4319 from MSVC
This change fixes a warning newly emitted by the latest MSVC, which now
treats this warning as an error and causes the build to fail.

This change aligns operand types in bitwise expressions by casting sizeof
results to UINT32, and promoting a UINT32 to UINTN where required to
correctly apply the bitmask.

Signed-off-by: Kun Qin <kun.qin@microsoft.com>
2026-03-13 19:14:49 +00:00
Michael D Kinney
e22f4a61c9 BaseTools/Source/Python/Trim: Add -f/--source-code-format option
Add --source-code-format option that can be NASM or not
specified. This can be used for file format specific actions
when --source-code is used.

A NASM specific action is added to convert #line to %line to
preserve reference the originating NASM source file for source
level debug in NASM format.

Without this change, the source level debug of NASM files
loads the generated intermediate file in the build output
directory.

Signed-off-by: Michael D Kinney <michael.d.kinney@intel.com>
2026-03-06 19:47:31 +00:00
Sherry Fan
75cce8c66f BaseTools: fix mdlint issues
Fix markdownlint formatting issues in READMEs.

Signed-off-by: Sherry Fan <sherryfan@microsoft.com>
2026-03-04 22:02:33 +00:00
Michael Kubacki
801abc03cd BaseTools/Eot: Apply CParser4 ANTLR 4.9 regeneration whitespace changes
Whitespace-only changes produced by the ANTLR 4.9 code generator.

Signed-off-by: Michael Kubacki <michael.kubacki@microsoft.com>
2026-02-27 23:18:15 +00:00
Michael Kubacki
0cdbc92544 BaseTools/Eot: Regenerate CParser4 files with ANTLR 4.9
The CParser4 Python parser files (CLexer.py, CParser.py, CListener.py)
were generated 7 years ago with ANTLR 4.7.1.

Meanwhile, pip-requirements.txt pins antlr4-python3-runtime to version
4.9 in commit 4a7dd50, but the files were patched, not fully
regenerated. This version mismatch could result in failures when
running against non-trivial C code.

This change regenerates the CParser4 files with ANTLR 4.9 to resolve
the version mismatch. It also updates import statements to correctly
reference Eot instead of Ecc.

Steps used to regenerate the files:

  1. Download the ANTLR 4.9 complete tool JAR:
     - `https://www.antlr.org/download/antlr-4.9-complete.jar`

  2. Generate Python3 parser files

Signed-off-by: Michael Kubacki <michael.kubacki@microsoft.com>
2026-02-27 23:18:15 +00:00
Michael Kubacki
ba8010bc6c BaseTools/Ecc: Apply CParser4 ANTLR 4.9 regeneration whitespace changes
Whitespace-only changes produced by the ANTLR 4.9 code generator.

Signed-off-by: Michael Kubacki <michael.kubacki@microsoft.com>
2026-02-27 23:18:15 +00:00
Michael Kubacki
ae24028512 BaseTools/Ecc: Regenerate CParser4 files with ANTLR 4.9
The CParser4 Python parser files (CLexer.py, CParser.py, CListener.py)
were generated 7 years ago with ANTLR 4.7.1.

Meanwhile, pip-requirements.txt pins antlr4-python3-runtime to version
4.9 in commit 4a7dd50, but the files were patched, not fully
regenerated. This version mismatch produced two failures when running
EccMain.py against non-trivial C code:

1. A runtime warning on every file parsed:
   "ANTLR runtime and generated code versions disagree: 4.9!=4.7.1"

2. A crash when parsing complex C constructs that exercise the
   struct/union definition rule in CParser.py:

   TypeError: '<' not supported between instances of 'tuple' and 'int'

   This occurs in antlr4/BufferedTokenStream.py getText() because the
   4.9 runtime changed the expected argument types for that method,
   and the 4.7.1-generated parser was passing a tuple where an int is
   now required.

This change regenerates the CParser4 files with ANTLR 4.9 to resolve
the version mismatch.

Steps used to regenerate the files:

  1. Download the ANTLR 4.9 complete tool JAR:
     - `https://www.antlr.org/download/antlr-4.9-complete.jar`

  2. Generate Python3 parser files from the grammar:

     ```
     java -jar antlr-4.9-complete.jar `
       -Dlanguage=Python3 -visitor `
       -o BaseTools/Source/Python/Ecc/CParser4_new `
       BaseTools/Source/Python/Ecc/CParser4/C.g4
     ```

Signed-off-by: Michael Kubacki <michael.kubacki@microsoft.com>
2026-02-27 23:18:15 +00:00
Michael D Kinney
3eb2ff24b9 BaseTools/Source/C/Include/Common: Add back include guard
Add include guards back to include files that use the same
include guard macro in BaseTools/Source/C/Include/Common
and MdePkg or MdeModulePkg.

Signed-off-by: Michael D Kinney <michael.d.kinney@intel.com>
2026-02-27 07:15:11 +00:00
Michael D Kinney
9fc0aca51e BaseTools/Source/C/VfrCompile: Fix parallel make failures
Update makefile rules to run antlr and dlg to completion
before compiling any of the generated cpp files.

Without this change, parallel make may start compiling some
of the cpp files before both antlr and dlg have finished
which produces syntax errors from compilation with partially
generated files.

Also use &: so the targets are treated as a group and the
rule is only executed once for the entire group. Without
this change, parallel make may run the rule actions more
than once and modify the output while it is being used by
another rule.

Signed-off-by: Michael D Kinney <michael.d.kinney@intel.com>
2026-02-27 04:54:43 +00:00
Michael Kubacki
0e6d10de1c BaseTools: Replace include guards with #pragma once
Replace traditional `#ifndef`/`#define`/`#endif` include guards with
`#pragma` once.

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

Note: Some files in BaseTools are excluded from the change if they
are autogenerated or direcly related to a header from a subproject,
etc. In particular, headers in these directories were ignored:

- BaseTools/Source/C/LzmaCompress/Sdk/
- BaseTools/Source/C/VfrCompile/Pccts/

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

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

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

However, this is considered acceptable given:

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

Approximate compiler support dates:

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

Signed-off-by: Michael Kubacki <michael.kubacki@microsoft.com>
2026-02-23 21:01:28 +00:00
Michael Kubacki
5ce48c03cb BaseTools/Ecc: Remove #ifndef include guard checks
The codebase has moved from traditional `#ifndef` include guards to
`#pragma once`. Remove the ECC checks that validated include guard
presence and naming conventions since they are no longer applicable.

The following checks are removed:

- IncludeFileCheckIfndefStatement: Verified all header file contents
  were guarded by a `#ifndef` statement, that the `#ifndef` was the
  first line of code after the file header comment, and that the
  `#endif` appeared on the last line.

- NamingConventionCheckIfndefStatement: Verified that the `#ifndef`
  guard name at the start of an include file used a postfix underscore
  and no prefix underscore character.

Also removed related error codes and configuration settings that were
specific to these checks.

Signed-off-by: Michael Kubacki <michael.kubacki@microsoft.com>
2026-02-23 21:01:28 +00:00
Michael Kubacki
3f81a4902a BaseTools/VfrCompile: Add #pragma once support
The C preprocessor turns each .vfr file into a pre-processed .i
file. At this step, the C preprocessor processes `#pragma once`.
Then, VfrCompile is called (with `-n` to prevent preprocessing)
to parse the pre-processed .i files.

The .i files may still contain `#pragma once` lines. Currently,
VfrCompile treats `once` as an unknown token, causing parse failures.

Originally, this change was going to add a `PragmaOnce` token rule
to the VFR lexer grammar (in VfrSyntax.g) that matched `#pragma once`
lines and silently skipped them using `skip()` and `newline()`. The
`newline()` call would keep line numbers stable for error reporting.
This was consistent with how other preprocessor artifacts were already
handled like `#line` directives (`LineDefinition` and
`GccLineDefinition` tokens) and `extern` declarations (skipped with
`mode(CPP_COMMENT)`).

Writing a regular expression to match `#pragma once` was simple
enough, but it makes overall pragma token recognition more fragile
at the lexer level. When the lexer is walking the DFA state table,
it could begin to match a `#pragma ` line but then not be able to
match remaining characters to recognize tokens other than `once`.

Instead, this change handles `#pragma once` lines in the VFR parser
grammar in `vfrPragmaDefinition` alongside where `pack` is already
handled.

Signed-off-by: Michael Kubacki <michael.kubacki@microsoft.com>
2026-02-23 21:01:28 +00:00
Michael D Kinney
12f785f106 Revert "BaseTools: Add support for out-of-tree builds"
This reverts commit 3fe1d56cc9.

PR https://github.com/tianocore/edk2/pull/11757 introduced a
"Breaking Change" feature for out of tree builds of tools.

This breaking change is blocking testing of edk2-stable202602
due to side effects on building FitGen tool in edk2-platforms.

Revert this feature for the edk2-stable202602 release and
work on this feature after the release.

Signed-off-by: Michael D Kinney <michael.d.kinney@intel.com>
2026-02-11 22:53:29 +00:00
Michael D Kinney
e1c56cf5d5 Revert "BaseTools/Source/C/Makefile: Update OBJECTS using OS specific SEP"
This reverts commit f0542ae07d.

PR https://github.com/tianocore/edk2/pull/11757 introduced a
"Breaking Change" feature for out of tree builds of tools.

This breaking change is blocking testing of edk2-stable202602
due to side effects on building FitGen tool in edk2-platforms.

Revert this feature for the edk2-stable202602 release and
work on this feature after the release.

Signed-off-by: Michael D Kinney <michael.d.kinney@intel.com>
2026-02-11 22:53:29 +00:00
Michael D Kinney
f0542ae07d BaseTools/Source/C/Makefile: Update OBJECTS using OS specific SEP
Use $(SEP) with addprefix of $(OBJDIR) to support Windows MINGW
CLANG builds that use Windows path separators with GNU makefiles.

This fixes Windows MINGW CLANG builds of the PcdValueInit
application that is required for structured PCDs.

Signed-off-by: Michael D Kinney <michael.d.kinney@intel.com>
2026-02-06 04:40:03 +00:00
Oleksandr Tymoshenko
3fe1d56cc9 BaseTools: Add support for out-of-tree builds
Main EDK2 build supports out-of-tree builds but BaseTools make process
still creates tools and object files in-tree. In order to make
out-of-tree build support complete move the generated tools and
interim obj files to $WORKSPACE location as well.

This patch also changes the location of BaseTools for in-tree builds
(default behavior when WORKSPACE is not provided before calling
edksetup) to $WORKSPACE/BaseTools/Build/... It may potentially break
external workflows that invoke tools from the default location outside
of the build tool.

Signed-off-by: Oleksandr Tymoshenko <ovt@google.com>
2026-02-02 08:56:31 +00:00
Oleksandr Tymoshenko
4cfa0c4911 BaseTools: Remove unused rules and dependencies
VfrLexer.h is built as a part of VfrCompile build and
shouldn't be present at the BaseTools/Source/C level.

Signed-off-by: Oleksandr Tymoshenko <ovt@google.com>
2026-02-02 08:56:31 +00:00
Gerd Hoffmann
9af06ef3cb BaseTools/EfiRom: fix compiler warning
New warning after updating gcc:

EfiRom.c: In function ‘main’:
EfiRom.c:78:17: error: assignment discards ‘const’ qualifier from pointer target type [-Werror=discarded-qualifiers]

The assigned value is not used, so fix the warning by just removing it.

Signed-off-by: Gerd Hoffmann <kraxel@redhat.com>
2026-02-01 20:30:31 +00:00
Gerd Hoffmann
3597306191 BaseTools/StringFuncs: fix gcc 16 warning
StringFuncs.c: In function ‘SplitStringByWhitespace’:
StringFuncs.c:113:15: error: variable ‘Item’ set but not used [-Werror=unused-but-set-variable=]
  113 |   UINTN       Item;
      |               ^~~~

Signed-off-by: Gerd Hoffmann <kraxel@redhat.com>
2026-02-01 20:30:31 +00:00
PaddyDeng
c2915d24a1 BaseTools: Prevent Subsection PCDs from polluting global expressions
The PCD value defined in module subsections can be added to global PCD
database. Therefore the unsolved expressions, even belongs to the global
scope, can incorrectly refer to the value from module subsection.

This only happens when the referred PCD has no value assignment in the
platform dsc file. Which also should raise an error.

Signed-off-by: Paddy Deng <paddydeng@ami.com>
2026-01-30 09:55:39 +00:00
Michael D Kinney
f26760f5e2 BaseTools/Source/C/Makefiles: Detect cycle in pids
Update _get_win32_parent_processes() to detect a
cycle in parent process ids that can cause
_get_win32_parent_processes() to never return.

If a pid cycle is detected, then return the list
of parent process ids detected up to the point
the cycle is detected.

GitHub Actions builds using windows-2025 can
reproduce this issue once in a while. It shows
up as job that runs until a timeout. If the job
is canceled, the logs show a python stack in the
loop in _get_win32_parent_processes().

Signed-off-by: Michael D Kinney <michael.d.kinney@intel.com>
2026-01-06 06:27:41 +00:00
Michael D Kinney
a0002ddc53 BaseTools/build: Add defines for Windows build environments
The stuart tools automatically add -D WIN_HOST_BUILD to
edk2 build command line if a Windows build environment
is detected. This behavior is added to build.py so that
builds of the EmulatorPkg using build.py are not required
to add the option -D WIN_HOST_BUILD when building in a
Windows environment. This aligns Linux and Windows builds
of the EmulatorPkg removing the need to specify extra
defines.

In order to build the EmulatorPkg for Windows Mingw
environments, EmulatorPkg DSC/FDF files require a way
to detect if Windows Mingw environment is present.
The Windows Mingw environment can be detected if
CLANG_BIN is set and mingw32-make.exe is detected
in the CLANG_BIN directory.

If a Windows Mingw environment is detected, add
-D WIN_MINGW32_BUILD to the edk2 build command line.

Signed-off-by: Michael D Kinney <michael.d.kinney@intel.com>
2026-01-06 04:44:08 +00:00
Ard Biesheuvel
8d0afac1d2 BaseTools/GenFw: Ignore R_*_NONE relocations on all architectures
The ELF psABIs for all architectures stipulate that R_*_NONE relocations
require no action at relocation time, and merely exist to declare a
dependency on a symbol in a way that cannot be conveyed by the code
itself (i.e., using an actual symbol reference). Given that EFI PE/COFF
images are always fully linked binaries, such a dependency cannot be
translated, and there are no known reasons why this would be necessary.

So instead of ignoring such relocations specifically on x86_64 only,
ignore them on all architectures when converting ELF binaries to
PE/COFF.

Fixes: #11878

Signed-off-by: Ard Biesheuvel <ardb@kernel.org>
2025-12-24 10:58:20 +00:00
Ard Biesheuvel
ddd7855a7a BaseTools,UefiPayloadPkg: Replace deprecated R_AARCH64_NONE value
For nebulous reasons, the original ELF psABI deviated from common sense,
and decided to #define R_AARCH64_NONE as '256', in spite of the fact
that no other architecture uses anything other than 0x0.

This has now been fixed in the psABI, so fix it in our code as well.

Continuous-integration-options: PatchCheck.ignore-multi-package
Signed-off-by: Ard Biesheuvel <ardb@kernel.org>
2025-12-24 10:58:20 +00:00
Michael D Kinney
79fdd2b82a BaseTools: GNUMakefiles must use CMD.EXE in Windows
Use $(OS) in all GNUMakefiles to detect if the GNUMakefile
is being used in a Windows OS. If a Windows OS is detected,
then override SHELL to use cmd.exe. This prevents make
utility from using sh.exe if sh.exe happens to be in PATH.

If sh.exe is used, then backslash (\) characters in file
paths are removed and builds break for files not found.

Signed-off-by: Michael D Kinney <michael.d.kinney@intel.com>
2025-12-24 02:03:38 +00:00
20000419
7c9fd884be BaseTools: Fix multiple security vulnerabilities (Defense in Depth)
Signed-off-by: 20000419 <lzy00419@163.com>
2025-12-22 04:53:27 +00:00