2 # Trim files preprocessed by compiler
4 # Copyright (c) 2007 - 2010, Intel Corporation. All rights reserved.<BR>
5 # This program and the accompanying materials
6 # are licensed and made available under the terms and conditions of the BSD License
7 # which accompanies this distribution. The full text of the license may be found at
8 # http://opensource.org/licenses/bsd-license.php
10 # THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
11 # WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
21 from optparse
import OptionParser
22 from optparse
import make_option
23 from Common
.BuildToolError
import *
24 from Common
.Misc
import *
25 from Common
.BuildVersion
import gBUILD_VERSION
26 import Common
.EdkLogger
as EdkLogger
28 # Version and Copyright
29 __version_number__
= ("0.10" + " " + gBUILD_VERSION
)
30 __version__
= "%prog Version " + __version_number__
31 __copyright__
= "Copyright (c) 2007-2010, Intel Corporation. All rights reserved."
33 ## Regular expression for matching Line Control directive like "#line xxx"
34 gLineControlDirective
= re
.compile('^\s*#(?:line)?\s+([0-9]+)\s+"*([^"]*)"')
35 ## Regular expression for matching "typedef struct"
36 gTypedefPattern
= re
.compile("^\s*typedef\s+struct(\s+\w+)?\s*[{]*$", re
.MULTILINE
)
37 ## Regular expression for matching "#pragma pack"
38 gPragmaPattern
= re
.compile("^\s*#pragma\s+pack", re
.MULTILINE
)
39 ## Regular expression for matching HEX number
40 gHexNumberPattern
= re
.compile("(0[xX])([0-9a-fA-F]+)U?")
41 ## Regular expression for matching decimal number with 'U' postfix
42 gDecNumberPattern
= re
.compile("([0-9]+)U")
43 ## Regular expression for matching "Include ()" in asl file
44 gAslIncludePattern
= re
.compile("^(\s*)[iI]nclude\s*\(\"?([^\"\(\)]+)\"\)", re
.MULTILINE
)
45 ## Regular expression for matching C style #include "XXX.asl" in asl file
46 gAslCIncludePattern
= re
.compile(r
'^(\s*)#include\s*[<"]\s*([-\\/\w.]+)\s*([>"])', re
.MULTILINE
)
47 ## Regular expression for matching constant with 'ULL' and 'UL', 'LL', 'L' postfix
48 gLongNumberPattern
= re
.compile("(0[xX][0-9a-fA-F]+|[0-9]+)U?LL", re
.MULTILINE
)
49 ## Patterns used to convert EDK conventions to EDK2 ECP conventions
50 gImportCodePatterns
= [
52 re
.compile('^(\s*)\(\*\*PeiServices\)\.PciCfg\s*=\s*([^;\s]+);', re
.MULTILINE
),
54 \\1 STATIC EFI_PEI_PPI_DESCRIPTOR gEcpPeiPciCfgPpiList = {
55 \\1 (EFI_PEI_PPI_DESCRIPTOR_PPI | EFI_PEI_PPI_DESCRIPTOR_TERMINATE_LIST),
56 \\1 &gEcpPeiPciCfgPpiGuid,
59 \\1 (**PeiServices).InstallPpi (PeiServices, &gEcpPeiPciCfgPpiList);
64 re
.compile('^(\s*)\(\*PeiServices\)->PciCfg\s*=\s*([^;\s]+);', re
.MULTILINE
),
66 \\1 STATIC EFI_PEI_PPI_DESCRIPTOR gEcpPeiPciCfgPpiList = {
67 \\1 (EFI_PEI_PPI_DESCRIPTOR_PPI | EFI_PEI_PPI_DESCRIPTOR_TERMINATE_LIST),
68 \\1 &gEcpPeiPciCfgPpiGuid,
71 \\1 (**PeiServices).InstallPpi (PeiServices, &gEcpPeiPciCfgPpiList);
76 re
.compile("(\s*).+->Modify[\s\n]*\(", re
.MULTILINE
),
77 '\\1PeiLibPciCfgModify ('
81 re
.compile("(\W*)gRT->ReportStatusCode[\s\n]*\(", re
.MULTILINE
),
82 '\\1EfiLibReportStatusCode ('
86 re
.compile('#include\s+EFI_GUID_DEFINITION\s*\(FirmwareFileSystem\)', re
.MULTILINE
),
87 '#include EFI_GUID_DEFINITION (FirmwareFileSystem)\n#include EFI_GUID_DEFINITION (FirmwareFileSystem2)'
91 re
.compile('gEfiFirmwareFileSystemGuid', re
.MULTILINE
),
92 'gEfiFirmwareFileSystem2Guid'
96 re
.compile('EFI_FVH_REVISION', re
.MULTILINE
),
101 re
.compile("(\s*)\S*CreateEvent\s*\([\s\n]*EFI_EVENT_SIGNAL_READY_TO_BOOT[^,]*,((?:[^;]+\n)+)(\s*\));", re
.MULTILINE
),
102 '\\1EfiCreateEventReadyToBoot (\\2\\3;'
106 re
.compile("(\s*)\S*CreateEvent\s*\([\s\n]*EFI_EVENT_SIGNAL_LEGACY_BOOT[^,]*,((?:[^;]+\n)+)(\s*\));", re
.MULTILINE
),
107 '\\1EfiCreateEventLegacyBoot (\\2\\3;'
110 # re.compile("(\W)(PEI_PCI_CFG_PPI)(\W)", re.MULTILINE),
115 ## file cache to avoid circular include in ASL file
116 gIncludedAslFile
= []
118 ## Trim preprocessed source code
120 # Remove extra content made by preprocessor. The preprocessor must enable the
121 # line number generation option when preprocessing.
123 # @param Source File to be trimmed
124 # @param Target File to store the trimmed content
125 # @param Convert If True, convert standard HEX format to MASM format
127 def TrimPreprocessedFile(Source
, Target
, ConvertHex
, TrimLong
):
128 CreateDirectory(os
.path
.dirname(Target
))
130 f
= open (Source
, 'r')
132 EdkLogger
.error("Trim", FILE_OPEN_FAILURE
, ExtraData
=Source
)
135 Lines
= f
.readlines()
138 PreprocessedFile
= ""
140 LineIndexOfOriginalFile
= None
142 LineControlDirectiveFound
= False
143 for Index
in range(len(Lines
)):
146 # Find out the name of files injected by preprocessor from the lines
147 # with Line Control directive
149 MatchList
= gLineControlDirective
.findall(Line
)
151 MatchList
= MatchList
[0]
152 if len(MatchList
) == 2:
153 LineNumber
= int(MatchList
[0], 0)
154 InjectedFile
= MatchList
[1]
155 # The first injetcted file must be the preprocessed file itself
156 if PreprocessedFile
== "":
157 PreprocessedFile
= InjectedFile
158 LineControlDirectiveFound
= True
160 elif PreprocessedFile
== "" or InjectedFile
!= PreprocessedFile
:
163 if LineIndexOfOriginalFile
== None:
165 # Any non-empty lines must be from original preprocessed file.
166 # And this must be the first one.
168 LineIndexOfOriginalFile
= Index
169 EdkLogger
.verbose("Found original file content starting from line %d"
170 % (LineIndexOfOriginalFile
+ 1))
172 # convert HEX number format if indicated
174 Line
= gHexNumberPattern
.sub(r
"0\2h", Line
)
176 Line
= gHexNumberPattern
.sub(r
"\1\2", Line
)
178 Line
= gLongNumberPattern
.sub(r
"\1", Line
)
180 # convert Decimal number format
181 Line
= gDecNumberPattern
.sub(r
"\1", Line
)
183 if LineNumber
!= None:
184 EdkLogger
.verbose("Got line directive: line=%d" % LineNumber
)
185 # in case preprocessor removed some lines, like blank or comment lines
186 if LineNumber
<= len(NewLines
):
188 NewLines
[LineNumber
- 1] = Line
190 if LineNumber
> (len(NewLines
) + 1):
191 for LineIndex
in range(len(NewLines
), LineNumber
-1):
192 NewLines
.append(os
.linesep
)
193 NewLines
.append(Line
)
195 EdkLogger
.verbose("Now we have lines: %d" % len(NewLines
))
197 NewLines
.append(Line
)
199 # in case there's no line directive or linemarker found
200 if (not LineControlDirectiveFound
) and NewLines
== []:
205 f
= open (Target
, 'wb')
207 EdkLogger
.error("Trim", FILE_OPEN_FAILURE
, ExtraData
=Target
)
208 f
.writelines(NewLines
)
211 ## Trim preprocessed VFR file
213 # Remove extra content made by preprocessor. The preprocessor doesn't need to
214 # enable line number generation option when preprocessing.
216 # @param Source File to be trimmed
217 # @param Target File to store the trimmed content
219 def TrimPreprocessedVfr(Source
, Target
):
220 CreateDirectory(os
.path
.dirname(Target
))
223 f
= open (Source
,'r')
225 EdkLogger
.error("Trim", FILE_OPEN_FAILURE
, ExtraData
=Source
)
227 Lines
= f
.readlines()
234 for Index
in range(len(Lines
)):
236 # don't trim the lines from "formset" definition to the end of file
237 if Line
.strip() == 'formset':
240 if FoundTypedef
== False and (Line
.find('#line') == 0 or Line
.find('# ') == 0):
241 # empty the line number directive if it's not aomong "typedef struct"
245 if FoundTypedef
== False and gTypedefPattern
.search(Line
) == None:
246 # keep "#pragram pack" directive
247 if gPragmaPattern
.search(Line
) == None:
250 elif FoundTypedef
== False:
251 # found "typedef struct", keept its position and set a flag
255 # match { and } to find the end of typedef definition
256 if Line
.find("{") >= 0:
258 elif Line
.find("}") >= 0:
261 # "typedef struct" must end with a ";"
262 if Brace
== 0 and Line
.find(";") >= 0:
265 # keep all "typedef struct" except to GUID, EFI_PLABEL and PAL_CALL_RETURN
266 if Line
.strip("} ;\r\n") in ["GUID", "EFI_PLABEL", "PAL_CALL_RETURN"]:
267 for i
in range(TypedefStart
, TypedefEnd
+1):
270 # save all lines trimmed
272 f
= open (Target
,'w')
274 EdkLogger
.error("Trim", FILE_OPEN_FAILURE
, ExtraData
=Target
)
278 ## Read the content ASL file, including ASL included, recursively
280 # @param Source File to be read
281 # @param Indent Spaces before the Include() statement
282 # @param IncludePathList The list of external include file
283 # @param LocalSearchPath If LocalSearchPath is specified, this path will be searched
284 # first for the included file; otherwise, only the path specified
285 # in the IncludePathList will be searched.
287 def DoInclude(Source
, Indent
='', IncludePathList
=[], LocalSearchPath
=None):
292 # Search LocalSearchPath first if it is specified.
295 SearchPathList
= [LocalSearchPath
] + IncludePathList
297 SearchPathList
= IncludePathList
299 for IncludePath
in SearchPathList
:
300 IncludeFile
= os
.path
.join(IncludePath
, Source
)
301 if os
.path
.isfile(IncludeFile
):
302 F
= open(IncludeFile
, "r")
305 EdkLogger
.error("Trim", "Failed to find include file %s" % Source
)
307 EdkLogger
.error("Trim", FILE_OPEN_FAILURE
, ExtraData
=Source
)
310 # avoid A "include" B and B "include" A
311 IncludeFile
= os
.path
.abspath(os
.path
.normpath(IncludeFile
))
312 if IncludeFile
in gIncludedAslFile
:
313 EdkLogger
.warn("Trim", "Circular include",
314 ExtraData
= "%s -> %s" % (" -> ".join(gIncludedAslFile
), IncludeFile
))
316 gIncludedAslFile
.append(IncludeFile
)
319 LocalSearchPath
= None
320 Result
= gAslIncludePattern
.findall(Line
)
322 Result
= gAslCIncludePattern
.findall(Line
)
323 if len(Result
) == 0 or os
.path
.splitext(Result
[0][1])[1].lower() not in [".asl", ".asi"]:
324 NewFileContent
.append("%s%s" % (Indent
, Line
))
327 # We should first search the local directory if current file are using pattern #include "XXX"
329 if Result
[0][2] == '"':
330 LocalSearchPath
= os
.path
.dirname(IncludeFile
)
331 CurrentIndent
= Indent
+ Result
[0][0]
332 IncludedFile
= Result
[0][1]
333 NewFileContent
.extend(DoInclude(IncludedFile
, CurrentIndent
, IncludePathList
, LocalSearchPath
))
334 NewFileContent
.append("\n")
336 gIncludedAslFile
.pop()
339 return NewFileContent
344 # Replace ASL include statement with the content the included file
346 # @param Source File to be trimmed
347 # @param Target File to store the trimmed content
348 # @param IncludePathFile The file to log the external include path
350 def TrimAslFile(Source
, Target
, IncludePathFile
):
351 CreateDirectory(os
.path
.dirname(Target
))
353 SourceDir
= os
.path
.dirname(Source
)
358 # Add source directory as the first search directory
360 IncludePathList
= [SourceDir
]
363 # If additional include path file is specified, append them all
364 # to the search directory list.
369 for Line
in open(IncludePathFile
,'r'):
371 if Line
.startswith("/I") or Line
.startswith ("-I"):
372 IncludePathList
.append(Line
[2:].strip())
374 EdkLogger
.warn("Trim", "Invalid include line in include list file.", IncludePathFile
, LineNum
)
376 EdkLogger
.error("Trim", FILE_OPEN_FAILURE
, ExtraData
=IncludePathFile
)
378 Lines
= DoInclude(Source
, '', IncludePathList
)
381 # Undef MIN and MAX to avoid collision in ASL source code
383 Lines
.insert(0, "#undef MIN\n#undef MAX\n")
385 # save all lines trimmed
387 f
= open (Target
,'w')
389 EdkLogger
.error("Trim", FILE_OPEN_FAILURE
, ExtraData
=Target
)
394 ## Trim EDK source code file(s)
397 # @param Source File or directory to be trimmed
398 # @param Target File or directory to store the trimmed content
400 def TrimEdkSources(Source
, Target
):
401 if os
.path
.isdir(Source
):
402 for CurrentDir
, Dirs
, Files
in os
.walk(Source
):
408 for FileName
in Files
:
409 Dummy
, Ext
= os
.path
.splitext(FileName
)
410 if Ext
.upper() not in ['.C', '.H']: continue
411 if Target
== None or Target
== '':
413 os
.path
.join(CurrentDir
, FileName
),
414 os
.path
.join(CurrentDir
, FileName
)
418 os
.path
.join(CurrentDir
, FileName
),
419 os
.path
.join(Target
, CurrentDir
[len(Source
)+1:], FileName
)
422 TrimEdkSourceCode(Source
, Target
)
424 ## Trim one EDK source code file
426 # Do following replacement:
428 # (**PeiServices\).PciCfg = <*>;
430 # STATIC EFI_PEI_PPI_DESCRIPTOR gEcpPeiPciCfgPpiList = {
431 # (EFI_PEI_PPI_DESCRIPTOR_PPI | EFI_PEI_PPI_DESCRIPTOR_TERMINATE_LIST),
432 # &gEcpPeiPciCfgPpiGuid,
435 # (**PeiServices).InstallPpi (PeiServices, &gEcpPeiPciCfgPpiList);
438 # => PeiLibPciCfgModify (<*>)
440 # gRT->ReportStatusCode (<*>)
441 # => EfiLibReportStatusCode (<*>)
443 # #include <LoadFile\.h>
444 # => #include <FvLoadFile.h>
446 # CreateEvent (EFI_EVENT_SIGNAL_READY_TO_BOOT, <*>)
447 # => EfiCreateEventReadyToBoot (<*>)
449 # CreateEvent (EFI_EVENT_SIGNAL_LEGACY_BOOT, <*>)
450 # => EfiCreateEventLegacyBoot (<*>)
452 # @param Source File to be trimmed
453 # @param Target File to store the trimmed content
455 def TrimEdkSourceCode(Source
, Target
):
456 EdkLogger
.verbose("\t%s -> %s" % (Source
, Target
))
457 CreateDirectory(os
.path
.dirname(Target
))
460 f
= open (Source
,'rb')
462 EdkLogger
.error("Trim", FILE_OPEN_FAILURE
, ExtraData
=Source
)
468 for Re
,Repl
in gImportCodePatterns
:
470 NewLines
= Re
.sub(Repl
, Lines
)
472 NewLines
= Re
.sub(Repl
, NewLines
)
474 # save all lines if trimmed
475 if Source
== Target
and NewLines
== Lines
:
479 f
= open (Target
,'wb')
481 EdkLogger
.error("Trim", FILE_OPEN_FAILURE
, ExtraData
=Target
)
486 ## Parse command line options
488 # Using standard Python module optparse to parse command line option of this tool.
490 # @retval Options A optparse.Values object containing the parsed options
491 # @retval InputFile Path of file to be trimmed
495 make_option("-s", "--source-code", dest
="FileType", const
="SourceCode", action
="store_const",
496 help="The input file is preprocessed source code, including C or assembly code"),
497 make_option("-r", "--vfr-file", dest
="FileType", const
="Vfr", action
="store_const",
498 help="The input file is preprocessed VFR file"),
499 make_option("-a", "--asl-file", dest
="FileType", const
="Asl", action
="store_const",
500 help="The input file is ASL file"),
501 make_option("-8", "--Edk-source-code", dest
="FileType", const
="EdkSourceCode", action
="store_const",
502 help="The input file is source code for Edk to be trimmed for ECP"),
504 make_option("-c", "--convert-hex", dest
="ConvertHex", action
="store_true",
505 help="Convert standard hex format (0xabcd) to MASM format (abcdh)"),
507 make_option("-l", "--trim-long", dest
="TrimLong", action
="store_true",
508 help="Remove postfix of long number"),
509 make_option("-i", "--include-path-file", dest
="IncludePathFile",
510 help="The input file is include path list to search for ASL include file"),
511 make_option("-o", "--output", dest
="OutputFile",
512 help="File to store the trimmed content"),
513 make_option("-v", "--verbose", dest
="LogLevel", action
="store_const", const
=EdkLogger
.VERBOSE
,
514 help="Run verbosely"),
515 make_option("-d", "--debug", dest
="LogLevel", type="int",
516 help="Run with debug information"),
517 make_option("-q", "--quiet", dest
="LogLevel", action
="store_const", const
=EdkLogger
.QUIET
,
519 make_option("-?", action
="help", help="show this help message and exit"),
522 # use clearer usage to override default usage message
523 UsageString
= "%prog [-s|-r|-a] [-c] [-v|-d <debug_level>|-q] [-i <include_path_file>] [-o <output_file>] <input_file>"
525 Parser
= OptionParser(description
=__copyright__
, version
=__version__
, option_list
=OptionList
, usage
=UsageString
)
526 Parser
.set_defaults(FileType
="Vfr")
527 Parser
.set_defaults(ConvertHex
=False)
528 Parser
.set_defaults(LogLevel
=EdkLogger
.INFO
)
530 Options
, Args
= Parser
.parse_args()
534 EdkLogger
.error("Trim", OPTION_MISSING
, ExtraData
=Parser
.get_usage())
536 EdkLogger
.error("Trim", OPTION_NOT_SUPPORTED
, ExtraData
=Parser
.get_usage())
539 return Options
, InputFile
543 # This method mainly dispatch specific methods per the command line options.
544 # If no error found, return zero value so the caller of this tool can know
545 # if it's executed successfully or not.
547 # @retval 0 Tool was successful
548 # @retval 1 Tool failed
552 EdkLogger
.Initialize()
553 CommandOptions
, InputFile
= Options()
554 if CommandOptions
.LogLevel
< EdkLogger
.DEBUG_9
:
555 EdkLogger
.SetLevel(CommandOptions
.LogLevel
+ 1)
557 EdkLogger
.SetLevel(CommandOptions
.LogLevel
)
558 except FatalError
, X
:
562 if CommandOptions
.FileType
== "Vfr":
563 if CommandOptions
.OutputFile
== None:
564 CommandOptions
.OutputFile
= os
.path
.splitext(InputFile
)[0] + '.iii'
565 TrimPreprocessedVfr(InputFile
, CommandOptions
.OutputFile
)
566 elif CommandOptions
.FileType
== "Asl":
567 if CommandOptions
.OutputFile
== None:
568 CommandOptions
.OutputFile
= os
.path
.splitext(InputFile
)[0] + '.iii'
569 TrimAslFile(InputFile
, CommandOptions
.OutputFile
, CommandOptions
.IncludePathFile
)
570 elif CommandOptions
.FileType
== "EdkSourceCode":
571 TrimEdkSources(InputFile
, CommandOptions
.OutputFile
)
573 if CommandOptions
.OutputFile
== None:
574 CommandOptions
.OutputFile
= os
.path
.splitext(InputFile
)[0] + '.iii'
575 TrimPreprocessedFile(InputFile
, CommandOptions
.OutputFile
, CommandOptions
.ConvertHex
, CommandOptions
.TrimLong
)
576 except FatalError
, X
:
579 if CommandOptions
!= None and CommandOptions
.LogLevel
<= EdkLogger
.DEBUG_9
:
580 EdkLogger
.quiet("(Python %s on %s) " % (platform
.python_version(), sys
.platform
) + traceback
.format_exc())
588 "Unknown fatal error when trimming [%s]" % InputFile
,
589 ExtraData
="\n(Please send email to edk2-buildtools-devel@lists.sourceforge.net for help, attaching following call stack trace!)\n",
592 EdkLogger
.quiet("(Python %s on %s) " % (platform
.python_version(), sys
.platform
) + traceback
.format_exc())
597 if __name__
== '__main__':
599 ## 0-127 is a safe return range, and 1 is a standard default error
600 if r
< 0 or r
> 127: r
= 1