## @file
# Trim files preprocessed by compiler
#
# Copyright (c) 2007 - 2010, Intel Corporation. All rights reserved.<BR>
# This program and the accompanying materials
# are licensed and made available under the terms and conditions of the BSD License
# which accompanies this distribution. The full text of the license may be found at
#
# THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
# WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
#
##
# Import Modules
#
import os
import sys
import re
from Common.BuildToolError import *
# Version and Copyright
## Regular expression for matching Line Control directive like "#line xxx"
## Regular expression for matching "typedef struct"
## Regular expression for matching "#pragma pack"
#
# The following number pattern match will only match if following criteria is met:
# There is leading non-(alphanumeric or _) character, and no following alphanumeric or _
# as the pattern is greedily match, so it is ok for the gDecNumberPattern or gHexNumberPattern to grab the maximum match
#
## Regular expression for matching HEX number
## Regular expression for matching decimal number with 'U' postfix
## Regular expression for matching constant with 'ULL' 'LL' postfix
gLongNumberPattern = re.compile("(?<=[^a-zA-Z0-9_])(0[xX][0-9a-fA-F]+|[0-9]+)U?LL(?=$|[^a-zA-Z0-9_])")
## Regular expression for matching "Include ()" in asl file
## Regular expression for matching C style #include "XXX.asl" in asl file
## Patterns used to convert EDK conventions to EDK2 ECP conventions
[
'''\\1{
\\1 STATIC EFI_PEI_PPI_DESCRIPTOR gEcpPeiPciCfgPpiList = {
\\1 (EFI_PEI_PPI_DESCRIPTOR_PPI | EFI_PEI_PPI_DESCRIPTOR_TERMINATE_LIST),
\\1 &gEcpPeiPciCfgPpiGuid,
\\1 \\2
\\1 };
\\1 (**PeiServices).InstallPpi (PeiServices, &gEcpPeiPciCfgPpiList);
\\1}'''
],
[
'''\\1{
\\1 STATIC EFI_PEI_PPI_DESCRIPTOR gEcpPeiPciCfgPpiList = {
\\1 (EFI_PEI_PPI_DESCRIPTOR_PPI | EFI_PEI_PPI_DESCRIPTOR_TERMINATE_LIST),
\\1 &gEcpPeiPciCfgPpiGuid,
\\1 \\2
\\1 };
\\1 (**PeiServices).InstallPpi (PeiServices, &gEcpPeiPciCfgPpiList);
\\1}'''
],
[
'\\1PeiLibPciCfgModify ('
],
[
'\\1EfiLibReportStatusCode ('
],
[
'#include EFI_GUID_DEFINITION (FirmwareFileSystem)\n#include EFI_GUID_DEFINITION (FirmwareFileSystem2)'
],
[
'gEfiFirmwareFileSystem2Guid'
],
[
'EFI_FVH_PI_REVISION'
],
[
re.compile("(\s*)\S*CreateEvent\s*\([\s\n]*EFI_EVENT_SIGNAL_READY_TO_BOOT[^,]*,((?:[^;]+\n)+)(\s*\));", re.MULTILINE),
'\\1EfiCreateEventReadyToBoot (\\2\\3;'
],
[
re.compile("(\s*)\S*CreateEvent\s*\([\s\n]*EFI_EVENT_SIGNAL_LEGACY_BOOT[^,]*,((?:[^;]+\n)+)(\s*\));", re.MULTILINE),
'\\1EfiCreateEventLegacyBoot (\\2\\3;'
],
# [
# re.compile("(\W)(PEI_PCI_CFG_PPI)(\W)", re.MULTILINE),
# '\\1ECP_\\2\\3'
# ]
]
## file cache to avoid circular include in ASL file
gIncludedAslFile = []
## Trim preprocessed source code
#
# Remove extra content made by preprocessor. The preprocessor must enable the
# line number generation option when preprocessing.
#
# @param Source File to be trimmed
# @param Target File to store the trimmed content
# @param Convert If True, convert standard HEX format to MASM format
#
try:
except:
# read whole file
f.close()
PreprocessedFile = ""
InjectedFile = ""
LineIndexOfOriginalFile = None
NewLines = []
#
# Find out the name of files injected by preprocessor from the lines
# with Line Control directive
#
if MatchList != []:
# The first injetcted file must be the preprocessed file itself
if PreprocessedFile == "":
continue
continue
if LineIndexOfOriginalFile == None:
#
# Any non-empty lines must be from original preprocessed file.
# And this must be the first one.
#
% (LineIndexOfOriginalFile + 1))
# convert HEX number format if indicated
if ConvertHex:
else:
if TrimLong:
# convert Decimal number format
if LineNumber != None:
# in case preprocessor removed some lines, like blank or comment lines
# possible?
else:
LineNumber = None
else:
# in case there's no line directive or linemarker found
if (not LineControlDirectiveFound) and NewLines == []:
# save to file
try:
except:
f.close()
## Trim preprocessed VFR file
#
# Remove extra content made by preprocessor. The preprocessor doesn't need to
# enable line number generation option when preprocessing.
#
# @param Source File to be trimmed
# @param Target File to store the trimmed content
#
try:
except:
# read whole file
f.close()
Brace = 0
TypedefStart = 0
TypedefEnd = 0
# don't trim the lines from "formset" definition to the end of file
break
# empty the line number directive if it's not aomong "typedef struct"
continue
# keep "#pragram pack" directive
continue
elif FoundTypedef == False:
# found "typedef struct", keept its position and set a flag
# match { and } to find the end of typedef definition
Brace += 1
Brace -= 1
# "typedef struct" must end with a ";"
# keep all "typedef struct" except to GUID, EFI_PLABEL and PAL_CALL_RETURN
Lines[i] = "\n"
# save all lines trimmed
try:
except:
f.writelines(Lines)
f.close()
## Read the content ASL file, including ASL included, recursively
#
# @param Source File to be read
# @param Indent Spaces before the Include() statement
# @param IncludePathList The list of external include file
# @param LocalSearchPath If LocalSearchPath is specified, this path will be searched
# first for the included file; otherwise, only the path specified
# in the IncludePathList will be searched.
#
NewFileContent = []
try:
#
# Search LocalSearchPath first if it is specified.
#
if LocalSearchPath:
else:
for IncludePath in SearchPathList:
break
else:
except:
# avoid A "include" B and B "include" A
if IncludeFile in gIncludedAslFile:
return []
for Line in F:
LocalSearchPath = None
continue
#
# We should first search the local directory if current file are using pattern #include "XXX"
#
F.close()
return NewFileContent
## Trim ASL file
#
# Replace ASL include statement with the content the included file
#
# @param Source File to be trimmed
# @param Target File to store the trimmed content
# @param IncludePathFile The file to log the external include path
#
if SourceDir == '':
SourceDir = '.'
#
# Add source directory as the first search directory
#
#
# If additional include path file is specified, append them all
# to the search directory list.
#
if IncludePathFile:
try:
LineNum = 0
LineNum += 1
else:
except:
#
# Undef MIN and MAX to avoid collision in ASL source code
#
# save all lines trimmed
try:
except:
f.writelines(Lines)
f.close()
## Trim EDK source code file(s)
#
#
# @param Source File or directory to be trimmed
# @param Target File or directory to store the trimmed content
#
if '.svn' in Dirs:
elif "CVS" in Dirs:
)
else:
)
else:
## Trim one EDK source code file
#
# Do following replacement:
#
# (**PeiServices\).PciCfg = <*>;
# => {
# STATIC EFI_PEI_PPI_DESCRIPTOR gEcpPeiPciCfgPpiList = {
# (EFI_PEI_PPI_DESCRIPTOR_PPI | EFI_PEI_PPI_DESCRIPTOR_TERMINATE_LIST),
# &gEcpPeiPciCfgPpiGuid,
# <*>
# };
# (**PeiServices).InstallPpi (PeiServices, &gEcpPeiPciCfgPpiList);
#
# <*>Modify(<*>)
# => PeiLibPciCfgModify (<*>)
#
# gRT->ReportStatusCode (<*>)
# => EfiLibReportStatusCode (<*>)
#
# #include <LoadFile\.h>
# => #include <FvLoadFile.h>
#
# CreateEvent (EFI_EVENT_SIGNAL_READY_TO_BOOT, <*>)
# => EfiCreateEventReadyToBoot (<*>)
#
# CreateEvent (EFI_EVENT_SIGNAL_LEGACY_BOOT, <*>)
# => EfiCreateEventLegacyBoot (<*>)
#
# @param Source File to be trimmed
# @param Target File to store the trimmed content
#
try:
except:
# read whole file
f.close()
NewLines = None
if NewLines == None:
else:
# save all lines if trimmed
return
try:
except:
f.close()
## Parse command line options
#
# Using standard Python module optparse to parse command line option of this tool.
#
# @retval Options A optparse.Values object containing the parsed options
# @retval InputFile Path of file to be trimmed
#
def Options():
OptionList = [
help="The input file is preprocessed source code, including C or assembly code"),
help="The input file is preprocessed VFR file"),
help="The input file is ASL file"),
make_option("-8", "--Edk-source-code", dest="FileType", const="EdkSourceCode", action="store_const",
help="The input file is source code for Edk to be trimmed for ECP"),
help="Convert standard hex format (0xabcd) to MASM format (abcdh)"),
help="Remove postfix of long number"),
help="The input file is include path list to search for ASL include file"),
help="File to store the trimmed content"),
help="Run verbosely"),
help="Run with debug information"),
help="Run quietly"),
]
# use clearer usage to override default usage message
UsageString = "%prog [-s|-r|-a] [-c] [-v|-d <debug_level>|-q] [-i <include_path_file>] [-o <output_file>] <input_file>"
Parser = OptionParser(description=__copyright__, version=__version__, option_list=OptionList, usage=UsageString)
# error check
## Entrance method
#
# This method mainly dispatch specific methods per the command line options.
# If no error found, return zero value so the caller of this tool can know
# if it's executed successfully or not.
#
# @retval 0 Tool was successful
# @retval 1 Tool failed
#
def Main():
try:
else:
except FatalError, X:
return 1
try:
if CommandOptions.OutputFile == None:
if CommandOptions.OutputFile == None:
else :
if CommandOptions.OutputFile == None:
TrimPreprocessedFile(InputFile, CommandOptions.OutputFile, CommandOptions.ConvertHex, CommandOptions.TrimLong)
except FatalError, X:
import platform
import traceback
EdkLogger.quiet("(Python %s on %s) " % (platform.python_version(), sys.platform) + traceback.format_exc())
return 1
except:
import traceback
import platform
"\nTrim",
"Unknown fatal error when trimming [%s]" % InputFile,
ExtraData="\n(Please send email to edk2-buildtools-devel@lists.sourceforge.net for help, attaching following call stack trace!)\n",
)
EdkLogger.quiet("(Python %s on %s) " % (platform.python_version(), sys.platform) + traceback.format_exc())
return 1
return 0
if __name__ == '__main__':
r = Main()
## 0-127 is a safe return range, and 1 is a standard default error
if r < 0 or r > 127: r = 1