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
)
41 # The following number pattern match will only match if following criteria is met:
42 # There is leading non-(alphanumeric or _) character, and no following alphanumeric or _
43 # as the pattern is greedily match, so it is ok for the gDecNumberPattern or gHexNumberPattern to grab the maximum match
45 ## Regular expression for matching HEX number
46 gHexNumberPattern
= re
.compile("(?<=[^a-zA-Z0-9_])(0[xX])([0-9a-fA-F]+)(U(?=$|[^a-zA-Z0-9_]))?")
47 ## Regular expression for matching decimal number with 'U' postfix
48 gDecNumberPattern
= re
.compile("(?<=[^a-zA-Z0-9_])([0-9]+)U(?=$|[^a-zA-Z0-9_])")
49 ## Regular expression for matching constant with 'ULL' 'LL' postfix
50 gLongNumberPattern
= re
.compile("(?<=[^a-zA-Z0-9_])(0[xX][0-9a-fA-F]+|[0-9]+)U?LL(?=$|[^a-zA-Z0-9_])")
52 ## Regular expression for matching "Include ()" in asl file
53 gAslIncludePattern
= re
.compile("^(\s*)[iI]nclude\s*\(\"?([^\"\(\)]+)\"\)", re
.MULTILINE
)
54 ## Regular expression for matching C style #include "XXX.asl" in asl file
55 gAslCIncludePattern
= re
.compile(r
'^(\s*)#include\s*[<"]\s*([-\\/\w.]+)\s*([>"])', re
.MULTILINE
)
56 ## Patterns used to convert EDK conventions to EDK2 ECP conventions
57 gImportCodePatterns
= [
59 re
.compile('^(\s*)\(\*\*PeiServices\)\.PciCfg\s*=\s*([^;\s]+);', re
.MULTILINE
),
61 \\1 STATIC EFI_PEI_PPI_DESCRIPTOR gEcpPeiPciCfgPpiList = {
62 \\1 (EFI_PEI_PPI_DESCRIPTOR_PPI | EFI_PEI_PPI_DESCRIPTOR_TERMINATE_LIST),
63 \\1 &gEcpPeiPciCfgPpiGuid,
66 \\1 (**PeiServices).InstallPpi (PeiServices, &gEcpPeiPciCfgPpiList);
71 re
.compile('^(\s*)\(\*PeiServices\)->PciCfg\s*=\s*([^;\s]+);', re
.MULTILINE
),
73 \\1 STATIC EFI_PEI_PPI_DESCRIPTOR gEcpPeiPciCfgPpiList = {
74 \\1 (EFI_PEI_PPI_DESCRIPTOR_PPI | EFI_PEI_PPI_DESCRIPTOR_TERMINATE_LIST),
75 \\1 &gEcpPeiPciCfgPpiGuid,
78 \\1 (**PeiServices).InstallPpi (PeiServices, &gEcpPeiPciCfgPpiList);
83 re
.compile("(\s*).+->Modify[\s\n]*\(", re
.MULTILINE
),
84 '\\1PeiLibPciCfgModify ('
88 re
.compile("(\W*)gRT->ReportStatusCode[\s\n]*\(", re
.MULTILINE
),
89 '\\1EfiLibReportStatusCode ('
93 re
.compile('#include\s+EFI_GUID_DEFINITION\s*\(FirmwareFileSystem\)', re
.MULTILINE
),
94 '#include EFI_GUID_DEFINITION (FirmwareFileSystem)\n#include EFI_GUID_DEFINITION (FirmwareFileSystem2)'
98 re
.compile('gEfiFirmwareFileSystemGuid', re
.MULTILINE
),
99 'gEfiFirmwareFileSystem2Guid'
103 re
.compile('EFI_FVH_REVISION', re
.MULTILINE
),
104 'EFI_FVH_PI_REVISION'
108 re
.compile("(\s*)\S*CreateEvent\s*\([\s\n]*EFI_EVENT_SIGNAL_READY_TO_BOOT[^,]*,((?:[^;]+\n)+)(\s*\));", re
.MULTILINE
),
109 '\\1EfiCreateEventReadyToBoot (\\2\\3;'
113 re
.compile("(\s*)\S*CreateEvent\s*\([\s\n]*EFI_EVENT_SIGNAL_LEGACY_BOOT[^,]*,((?:[^;]+\n)+)(\s*\));", re
.MULTILINE
),
114 '\\1EfiCreateEventLegacyBoot (\\2\\3;'
117 # re.compile("(\W)(PEI_PCI_CFG_PPI)(\W)", re.MULTILINE),
122 ## file cache to avoid circular include in ASL file
123 gIncludedAslFile
= []
125 ## Trim preprocessed source code
127 # Remove extra content made by preprocessor. The preprocessor must enable the
128 # line number generation option when preprocessing.
130 # @param Source File to be trimmed
131 # @param Target File to store the trimmed content
132 # @param Convert If True, convert standard HEX format to MASM format
134 def TrimPreprocessedFile(Source
, Target
, ConvertHex
, TrimLong
):
135 CreateDirectory(os
.path
.dirname(Target
))
137 f
= open (Source
, 'r')
139 EdkLogger
.error("Trim", FILE_OPEN_FAILURE
, ExtraData
=Source
)
142 Lines
= f
.readlines()
145 PreprocessedFile
= ""
147 LineIndexOfOriginalFile
= None
149 LineControlDirectiveFound
= False
150 for Index
in range(len(Lines
)):
153 # Find out the name of files injected by preprocessor from the lines
154 # with Line Control directive
156 MatchList
= gLineControlDirective
.findall(Line
)
158 MatchList
= MatchList
[0]
159 if len(MatchList
) == 2:
160 LineNumber
= int(MatchList
[0], 0)
161 InjectedFile
= MatchList
[1]
162 # The first injetcted file must be the preprocessed file itself
163 if PreprocessedFile
== "":
164 PreprocessedFile
= InjectedFile
165 LineControlDirectiveFound
= True
167 elif PreprocessedFile
== "" or InjectedFile
!= PreprocessedFile
:
170 if LineIndexOfOriginalFile
== None:
172 # Any non-empty lines must be from original preprocessed file.
173 # And this must be the first one.
175 LineIndexOfOriginalFile
= Index
176 EdkLogger
.verbose("Found original file content starting from line %d"
177 % (LineIndexOfOriginalFile
+ 1))
179 # convert HEX number format if indicated
181 Line
= gHexNumberPattern
.sub(r
"0\2h", Line
)
183 Line
= gHexNumberPattern
.sub(r
"\1\2", Line
)
185 Line
= gLongNumberPattern
.sub(r
"\1", Line
)
187 # convert Decimal number format
188 Line
= gDecNumberPattern
.sub(r
"\1", Line
)
190 if LineNumber
!= None:
191 EdkLogger
.verbose("Got line directive: line=%d" % LineNumber
)
192 # in case preprocessor removed some lines, like blank or comment lines
193 if LineNumber
<= len(NewLines
):
195 NewLines
[LineNumber
- 1] = Line
197 if LineNumber
> (len(NewLines
) + 1):
198 for LineIndex
in range(len(NewLines
), LineNumber
-1):
199 NewLines
.append(os
.linesep
)
200 NewLines
.append(Line
)
202 EdkLogger
.verbose("Now we have lines: %d" % len(NewLines
))
204 NewLines
.append(Line
)
206 # in case there's no line directive or linemarker found
207 if (not LineControlDirectiveFound
) and NewLines
== []:
212 f
= open (Target
, 'wb')
214 EdkLogger
.error("Trim", FILE_OPEN_FAILURE
, ExtraData
=Target
)
215 f
.writelines(NewLines
)
218 ## Trim preprocessed VFR file
220 # Remove extra content made by preprocessor. The preprocessor doesn't need to
221 # enable line number generation option when preprocessing.
223 # @param Source File to be trimmed
224 # @param Target File to store the trimmed content
226 def TrimPreprocessedVfr(Source
, Target
):
227 CreateDirectory(os
.path
.dirname(Target
))
230 f
= open (Source
,'r')
232 EdkLogger
.error("Trim", FILE_OPEN_FAILURE
, ExtraData
=Source
)
234 Lines
= f
.readlines()
241 for Index
in range(len(Lines
)):
243 # don't trim the lines from "formset" definition to the end of file
244 if Line
.strip() == 'formset':
247 if FoundTypedef
== False and (Line
.find('#line') == 0 or Line
.find('# ') == 0):
248 # empty the line number directive if it's not aomong "typedef struct"
252 if FoundTypedef
== False and gTypedefPattern
.search(Line
) == None:
253 # keep "#pragram pack" directive
254 if gPragmaPattern
.search(Line
) == None:
257 elif FoundTypedef
== False:
258 # found "typedef struct", keept its position and set a flag
262 # match { and } to find the end of typedef definition
263 if Line
.find("{") >= 0:
265 elif Line
.find("}") >= 0:
268 # "typedef struct" must end with a ";"
269 if Brace
== 0 and Line
.find(";") >= 0:
272 # keep all "typedef struct" except to GUID, EFI_PLABEL and PAL_CALL_RETURN
273 if Line
.strip("} ;\r\n") in ["GUID", "EFI_PLABEL", "PAL_CALL_RETURN"]:
274 for i
in range(TypedefStart
, TypedefEnd
+1):
277 # save all lines trimmed
279 f
= open (Target
,'w')
281 EdkLogger
.error("Trim", FILE_OPEN_FAILURE
, ExtraData
=Target
)
285 ## Read the content ASL file, including ASL included, recursively
287 # @param Source File to be read
288 # @param Indent Spaces before the Include() statement
289 # @param IncludePathList The list of external include file
290 # @param LocalSearchPath If LocalSearchPath is specified, this path will be searched
291 # first for the included file; otherwise, only the path specified
292 # in the IncludePathList will be searched.
294 def DoInclude(Source
, Indent
='', IncludePathList
=[], LocalSearchPath
=None):
299 # Search LocalSearchPath first if it is specified.
302 SearchPathList
= [LocalSearchPath
] + IncludePathList
304 SearchPathList
= IncludePathList
306 for IncludePath
in SearchPathList
:
307 IncludeFile
= os
.path
.join(IncludePath
, Source
)
308 if os
.path
.isfile(IncludeFile
):
309 F
= open(IncludeFile
, "r")
312 EdkLogger
.error("Trim", "Failed to find include file %s" % Source
)
314 EdkLogger
.error("Trim", FILE_OPEN_FAILURE
, ExtraData
=Source
)
317 # avoid A "include" B and B "include" A
318 IncludeFile
= os
.path
.abspath(os
.path
.normpath(IncludeFile
))
319 if IncludeFile
in gIncludedAslFile
:
320 EdkLogger
.warn("Trim", "Circular include",
321 ExtraData
= "%s -> %s" % (" -> ".join(gIncludedAslFile
), IncludeFile
))
323 gIncludedAslFile
.append(IncludeFile
)
326 LocalSearchPath
= None
327 Result
= gAslIncludePattern
.findall(Line
)
329 Result
= gAslCIncludePattern
.findall(Line
)
330 if len(Result
) == 0 or os
.path
.splitext(Result
[0][1])[1].lower() not in [".asl", ".asi"]:
331 NewFileContent
.append("%s%s" % (Indent
, Line
))
334 # We should first search the local directory if current file are using pattern #include "XXX"
336 if Result
[0][2] == '"':
337 LocalSearchPath
= os
.path
.dirname(IncludeFile
)
338 CurrentIndent
= Indent
+ Result
[0][0]
339 IncludedFile
= Result
[0][1]
340 NewFileContent
.extend(DoInclude(IncludedFile
, CurrentIndent
, IncludePathList
, LocalSearchPath
))
341 NewFileContent
.append("\n")
343 gIncludedAslFile
.pop()
346 return NewFileContent
351 # Replace ASL include statement with the content the included file
353 # @param Source File to be trimmed
354 # @param Target File to store the trimmed content
355 # @param IncludePathFile The file to log the external include path
357 def TrimAslFile(Source
, Target
, IncludePathFile
):
358 CreateDirectory(os
.path
.dirname(Target
))
360 SourceDir
= os
.path
.dirname(Source
)
365 # Add source directory as the first search directory
367 IncludePathList
= [SourceDir
]
370 # If additional include path file is specified, append them all
371 # to the search directory list.
376 for Line
in open(IncludePathFile
,'r'):
378 if Line
.startswith("/I") or Line
.startswith ("-I"):
379 IncludePathList
.append(Line
[2:].strip())
381 EdkLogger
.warn("Trim", "Invalid include line in include list file.", IncludePathFile
, LineNum
)
383 EdkLogger
.error("Trim", FILE_OPEN_FAILURE
, ExtraData
=IncludePathFile
)
385 Lines
= DoInclude(Source
, '', IncludePathList
)
388 # Undef MIN and MAX to avoid collision in ASL source code
390 Lines
.insert(0, "#undef MIN\n#undef MAX\n")
392 # save all lines trimmed
394 f
= open (Target
,'w')
396 EdkLogger
.error("Trim", FILE_OPEN_FAILURE
, ExtraData
=Target
)
401 ## Trim EDK source code file(s)
404 # @param Source File or directory to be trimmed
405 # @param Target File or directory to store the trimmed content
407 def TrimEdkSources(Source
, Target
):
408 if os
.path
.isdir(Source
):
409 for CurrentDir
, Dirs
, Files
in os
.walk(Source
):
415 for FileName
in Files
:
416 Dummy
, Ext
= os
.path
.splitext(FileName
)
417 if Ext
.upper() not in ['.C', '.H']: continue
418 if Target
== None or Target
== '':
420 os
.path
.join(CurrentDir
, FileName
),
421 os
.path
.join(CurrentDir
, FileName
)
425 os
.path
.join(CurrentDir
, FileName
),
426 os
.path
.join(Target
, CurrentDir
[len(Source
)+1:], FileName
)
429 TrimEdkSourceCode(Source
, Target
)
431 ## Trim one EDK source code file
433 # Do following replacement:
435 # (**PeiServices\).PciCfg = <*>;
437 # STATIC EFI_PEI_PPI_DESCRIPTOR gEcpPeiPciCfgPpiList = {
438 # (EFI_PEI_PPI_DESCRIPTOR_PPI | EFI_PEI_PPI_DESCRIPTOR_TERMINATE_LIST),
439 # &gEcpPeiPciCfgPpiGuid,
442 # (**PeiServices).InstallPpi (PeiServices, &gEcpPeiPciCfgPpiList);
445 # => PeiLibPciCfgModify (<*>)
447 # gRT->ReportStatusCode (<*>)
448 # => EfiLibReportStatusCode (<*>)
450 # #include <LoadFile\.h>
451 # => #include <FvLoadFile.h>
453 # CreateEvent (EFI_EVENT_SIGNAL_READY_TO_BOOT, <*>)
454 # => EfiCreateEventReadyToBoot (<*>)
456 # CreateEvent (EFI_EVENT_SIGNAL_LEGACY_BOOT, <*>)
457 # => EfiCreateEventLegacyBoot (<*>)
459 # @param Source File to be trimmed
460 # @param Target File to store the trimmed content
462 def TrimEdkSourceCode(Source
, Target
):
463 EdkLogger
.verbose("\t%s -> %s" % (Source
, Target
))
464 CreateDirectory(os
.path
.dirname(Target
))
467 f
= open (Source
,'rb')
469 EdkLogger
.error("Trim", FILE_OPEN_FAILURE
, ExtraData
=Source
)
475 for Re
,Repl
in gImportCodePatterns
:
477 NewLines
= Re
.sub(Repl
, Lines
)
479 NewLines
= Re
.sub(Repl
, NewLines
)
481 # save all lines if trimmed
482 if Source
== Target
and NewLines
== Lines
:
486 f
= open (Target
,'wb')
488 EdkLogger
.error("Trim", FILE_OPEN_FAILURE
, ExtraData
=Target
)
493 ## Parse command line options
495 # Using standard Python module optparse to parse command line option of this tool.
497 # @retval Options A optparse.Values object containing the parsed options
498 # @retval InputFile Path of file to be trimmed
502 make_option("-s", "--source-code", dest
="FileType", const
="SourceCode", action
="store_const",
503 help="The input file is preprocessed source code, including C or assembly code"),
504 make_option("-r", "--vfr-file", dest
="FileType", const
="Vfr", action
="store_const",
505 help="The input file is preprocessed VFR file"),
506 make_option("-a", "--asl-file", dest
="FileType", const
="Asl", action
="store_const",
507 help="The input file is ASL file"),
508 make_option("-8", "--Edk-source-code", dest
="FileType", const
="EdkSourceCode", action
="store_const",
509 help="The input file is source code for Edk to be trimmed for ECP"),
511 make_option("-c", "--convert-hex", dest
="ConvertHex", action
="store_true",
512 help="Convert standard hex format (0xabcd) to MASM format (abcdh)"),
514 make_option("-l", "--trim-long", dest
="TrimLong", action
="store_true",
515 help="Remove postfix of long number"),
516 make_option("-i", "--include-path-file", dest
="IncludePathFile",
517 help="The input file is include path list to search for ASL include file"),
518 make_option("-o", "--output", dest
="OutputFile",
519 help="File to store the trimmed content"),
520 make_option("-v", "--verbose", dest
="LogLevel", action
="store_const", const
=EdkLogger
.VERBOSE
,
521 help="Run verbosely"),
522 make_option("-d", "--debug", dest
="LogLevel", type="int",
523 help="Run with debug information"),
524 make_option("-q", "--quiet", dest
="LogLevel", action
="store_const", const
=EdkLogger
.QUIET
,
526 make_option("-?", action
="help", help="show this help message and exit"),
529 # use clearer usage to override default usage message
530 UsageString
= "%prog [-s|-r|-a] [-c] [-v|-d <debug_level>|-q] [-i <include_path_file>] [-o <output_file>] <input_file>"
532 Parser
= OptionParser(description
=__copyright__
, version
=__version__
, option_list
=OptionList
, usage
=UsageString
)
533 Parser
.set_defaults(FileType
="Vfr")
534 Parser
.set_defaults(ConvertHex
=False)
535 Parser
.set_defaults(LogLevel
=EdkLogger
.INFO
)
537 Options
, Args
= Parser
.parse_args()
541 EdkLogger
.error("Trim", OPTION_MISSING
, ExtraData
=Parser
.get_usage())
543 EdkLogger
.error("Trim", OPTION_NOT_SUPPORTED
, ExtraData
=Parser
.get_usage())
546 return Options
, InputFile
550 # This method mainly dispatch specific methods per the command line options.
551 # If no error found, return zero value so the caller of this tool can know
552 # if it's executed successfully or not.
554 # @retval 0 Tool was successful
555 # @retval 1 Tool failed
559 EdkLogger
.Initialize()
560 CommandOptions
, InputFile
= Options()
561 if CommandOptions
.LogLevel
< EdkLogger
.DEBUG_9
:
562 EdkLogger
.SetLevel(CommandOptions
.LogLevel
+ 1)
564 EdkLogger
.SetLevel(CommandOptions
.LogLevel
)
565 except FatalError
, X
:
569 if CommandOptions
.FileType
== "Vfr":
570 if CommandOptions
.OutputFile
== None:
571 CommandOptions
.OutputFile
= os
.path
.splitext(InputFile
)[0] + '.iii'
572 TrimPreprocessedVfr(InputFile
, CommandOptions
.OutputFile
)
573 elif CommandOptions
.FileType
== "Asl":
574 if CommandOptions
.OutputFile
== None:
575 CommandOptions
.OutputFile
= os
.path
.splitext(InputFile
)[0] + '.iii'
576 TrimAslFile(InputFile
, CommandOptions
.OutputFile
, CommandOptions
.IncludePathFile
)
577 elif CommandOptions
.FileType
== "EdkSourceCode":
578 TrimEdkSources(InputFile
, CommandOptions
.OutputFile
)
580 if CommandOptions
.OutputFile
== None:
581 CommandOptions
.OutputFile
= os
.path
.splitext(InputFile
)[0] + '.iii'
582 TrimPreprocessedFile(InputFile
, CommandOptions
.OutputFile
, CommandOptions
.ConvertHex
, CommandOptions
.TrimLong
)
583 except FatalError
, X
:
586 if CommandOptions
!= None and CommandOptions
.LogLevel
<= EdkLogger
.DEBUG_9
:
587 EdkLogger
.quiet("(Python %s on %s) " % (platform
.python_version(), sys
.platform
) + traceback
.format_exc())
595 "Unknown fatal error when trimming [%s]" % InputFile
,
596 ExtraData
="\n(Please send email to edk2-buildtools-devel@lists.sourceforge.net for help, attaching following call stack trace!)\n",
599 EdkLogger
.quiet("(Python %s on %s) " % (platform
.python_version(), sys
.platform
) + traceback
.format_exc())
604 if __name__
== '__main__':
606 ## 0-127 is a safe return range, and 1 is a standard default error
607 if r
< 0 or r
> 127: r
= 1