2 # Trim files preprocessed by compiler
4 # Copyright (c) 2007, Intel Corporation
5 # All rights reserved. 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 *
26 import Common
.EdkLogger
as EdkLogger
28 # Version and Copyright
29 __version_number__
= "0.10"
30 __version__
= "%prog Version " + __version_number__
31 __copyright__
= "Copyright (c) 2007-2008, 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*[{]*$", 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]+)")
41 ## Regular expression for matching "Include ()" in asl file
42 gAslIncludePattern
= re
.compile("^(\s*)[iI]nclude\s*\(\"?([^\"\(\)]+)\"\)", re
.MULTILINE
)
43 ## Patterns used to convert EDK conventions to EDK2 ECP conventions
44 gImportCodePatterns
= [
46 re
.compile('^(\s*)\(\*\*PeiServices\)\.PciCfg\s*=\s*([^;\s]+);', re
.MULTILINE
),
48 \\1 STATIC EFI_PEI_PPI_DESCRIPTOR gEcpPeiPciCfgPpiList = {
49 \\1 (EFI_PEI_PPI_DESCRIPTOR_PPI | EFI_PEI_PPI_DESCRIPTOR_TERMINATE_LIST),
50 \\1 &gEcpPeiPciCfgPpiGuid,
53 \\1 (**PeiServices).InstallPpi (PeiServices, &gEcpPeiPciCfgPpiList);
58 re
.compile('^(\s*)\(\*PeiServices\)->PciCfg\s*=\s*([^;\s]+);', re
.MULTILINE
),
60 \\1 STATIC EFI_PEI_PPI_DESCRIPTOR gEcpPeiPciCfgPpiList = {
61 \\1 (EFI_PEI_PPI_DESCRIPTOR_PPI | EFI_PEI_PPI_DESCRIPTOR_TERMINATE_LIST),
62 \\1 &gEcpPeiPciCfgPpiGuid,
65 \\1 (**PeiServices).InstallPpi (PeiServices, &gEcpPeiPciCfgPpiList);
70 re
.compile("(\s*).+->Modify[\s\n]*\(", re
.MULTILINE
),
71 '\\1PeiLibPciCfgModify ('
75 re
.compile("(\W*)gRT->ReportStatusCode[\s\n]*\(", re
.MULTILINE
),
76 '\\1EfiLibReportStatusCode ('
80 re
.compile('#include\s+["<]LoadFile\.h[">]', re
.MULTILINE
),
81 '#include <FvLoadFile.h>'
85 re
.compile("(\s*)\S*CreateEvent\s*\([\s\n]*EFI_EVENT_SIGNAL_READY_TO_BOOT[^,]*,((?:[^;]+\n)+)(\s*\));", re
.MULTILINE
),
86 '\\1EfiCreateEventReadyToBoot (\\2\\3;'
90 re
.compile("(\s*)\S*CreateEvent\s*\([\s\n]*EFI_EVENT_SIGNAL_LEGACY_BOOT[^,]*,((?:[^;]+\n)+)(\s*\));", re
.MULTILINE
),
91 '\\1EfiCreateEventLegacyBoot (\\2\\3;'
94 # re.compile("(\W)(PEI_PCI_CFG_PPI)(\W)", re.MULTILINE),
99 ## file cache to avoid circular include in ASL file
100 gIncludedAslFile
= []
102 ## Trim preprocessed source code
104 # Remove extra content made by preprocessor. The preprocessor must enable the
105 # line number generation option when preprocessing.
107 # @param Source File to be trimmed
108 # @param Target File to store the trimmed content
109 # @param Convert If True, convert standard HEX format to MASM format
111 def TrimPreprocessedFile(Source
, Target
, Convert
):
112 CreateDirectory(os
.path
.dirname(Target
))
114 f
= open (Source
, 'r')
116 EdkLogger
.error("Trim", FILE_OPEN_FAILURE
, ExtraData
=Source
)
119 Lines
= f
.readlines()
122 PreprocessedFile
= ""
124 LineIndexOfOriginalFile
= None
126 LineControlDirectiveFound
= False
127 for Index
in range(len(Lines
)):
130 # Find out the name of files injected by preprocessor from the lines
131 # with Line Control directive
133 MatchList
= gLineControlDirective
.findall(Line
)
135 MatchList
= MatchList
[0]
136 if len(MatchList
) == 2:
137 LineNumber
= int(MatchList
[0], 0)
138 InjectedFile
= MatchList
[1]
139 # The first injetcted file must be the preprocessed file itself
140 if PreprocessedFile
== "":
141 PreprocessedFile
= InjectedFile
142 LineControlDirectiveFound
= True
144 elif PreprocessedFile
== "" or InjectedFile
!= PreprocessedFile
:
147 if LineIndexOfOriginalFile
== None:
149 # Any non-empty lines must be from original preprocessed file.
150 # And this must be the first one.
152 LineIndexOfOriginalFile
= Index
153 EdkLogger
.verbose("Found original file content starting from line %d"
154 % (LineIndexOfOriginalFile
+ 1))
156 # convert HEX number format if indicated
158 Line
= gHexNumberPattern
.sub(r
"0\1h", Line
)
160 if LineNumber
!= None:
161 EdkLogger
.verbose("Got line directive: line=%d" % LineNumber
)
162 # in case preprocessor removed some lines, like blank or comment lines
163 if LineNumber
<= len(NewLines
):
165 NewLines
[LineNumber
- 1] = Line
167 if LineNumber
> (len(NewLines
) + 1):
168 for LineIndex
in range(len(NewLines
), LineNumber
-1):
169 NewLines
.append(os
.linesep
)
170 NewLines
.append(Line
)
172 EdkLogger
.verbose("Now we have lines: %d" % len(NewLines
))
174 NewLines
.append(Line
)
176 # in case there's no line directive or linemarker found
177 if (not LineControlDirectiveFound
) and NewLines
== []:
182 f
= open (Target
, 'wb')
184 EdkLogger
.error("Trim", FILE_OPEN_FAILURE
, ExtraData
=Target
)
185 f
.writelines(NewLines
)
188 ## Trim preprocessed VFR file
190 # Remove extra content made by preprocessor. The preprocessor doesn't need to
191 # enable line number generation option when preprocessing.
193 # @param Source File to be trimmed
194 # @param Target File to store the trimmed content
196 def TrimPreprocessedVfr(Source
, Target
):
197 CreateDirectory(os
.path
.dirname(Target
))
200 f
= open (Source
,'r')
202 EdkLogger
.error("Trim", FILE_OPEN_FAILURE
, ExtraData
=Source
)
204 Lines
= f
.readlines()
211 for Index
in range(len(Lines
)):
213 # don't trim the lines from "formset" definition to the end of file
214 if Line
.strip() == 'formset':
217 if FoundTypedef
== False and (Line
.find('#line') == 0 or Line
.find('# ') == 0):
218 # empty the line number directive if it's not aomong "typedef struct"
222 if FoundTypedef
== False and gTypedefPattern
.search(Line
) == None:
223 # keep "#pragram pack" directive
224 if gPragmaPattern
.search(Line
) == None:
227 elif FoundTypedef
== False:
228 # found "typedef struct", keept its position and set a flag
232 # match { and } to find the end of typedef definition
233 if Line
.find("{") >= 0:
235 elif Line
.find("}") >= 0:
238 # "typedef struct" must end with a ";"
239 if Brace
== 0 and Line
.find(";") >= 0:
242 # keep all "typedef struct" except to GUID, EFI_PLABEL and PAL_CALL_RETURN
243 if Line
.strip("} ;\r\n") in ["GUID", "EFI_PLABEL", "PAL_CALL_RETURN"]:
244 for i
in range(TypedefStart
, TypedefEnd
+1):
247 # save all lines trimmed
249 f
= open (Target
,'w')
251 EdkLogger
.error("Trim", FILE_OPEN_FAILURE
, ExtraData
=Target
)
255 ## Read the content ASL file, including ASL included, recursively
257 # @param Source File to be read
258 # @param Indent Spaces before the Include() statement
260 def DoInclude(Source
, Indent
=''):
262 # avoid A "include" B and B "include" A
263 if Source
in gIncludedAslFile
:
264 EdkLogger
.warn("Trim", "Circular include",
265 ExtraData
= "%s -> %s" % (" -> ".join(gIncludedAslFile
), Source
))
267 gIncludedAslFile
.append(Source
)
272 EdkLogger
.error("Trim", FILE_OPEN_FAILURE
, ExtraData
=Source
)
275 Result
= gAslIncludePattern
.findall(Line
)
277 NewFileContent
.append("%s%s" % (Indent
, Line
))
279 CurrentIndent
= Indent
+ Result
[0][0]
280 IncludedFile
= Result
[0][1]
281 NewFileContent
.extend(DoInclude(IncludedFile
, CurrentIndent
))
283 gIncludedAslFile
.pop()
286 return NewFileContent
291 # Replace ASL include statement with the content the included file
293 # @param Source File to be trimmed
294 # @param Target File to store the trimmed content
296 def TrimAslFile(Source
, Target
):
297 CreateDirectory(os
.path
.dirname(Target
))
300 SourceDir
= os
.path
.dirname(Source
)
304 Lines
= DoInclude(Source
)
307 # save all lines trimmed
309 f
= open (Target
,'w')
311 EdkLogger
.error("Trim", FILE_OPEN_FAILURE
, ExtraData
=Target
)
316 ## Trim EDK source code file(s)
319 # @param Source File or directory to be trimmed
320 # @param Target File or directory to store the trimmed content
322 def TrimR8Sources(Source
, Target
):
323 if os
.path
.isdir(Source
):
324 for CurrentDir
, Dirs
, Files
in os
.walk(Source
):
330 for FileName
in Files
:
331 Dummy
, Ext
= os
.path
.splitext(FileName
)
332 if Ext
.upper() not in ['.C', '.H']: continue
333 if Target
== None or Target
== '':
335 os
.path
.join(CurrentDir
, FileName
),
336 os
.path
.join(CurrentDir
, FileName
)
340 os
.path
.join(CurrentDir
, FileName
),
341 os
.path
.join(Target
, CurrentDir
[len(Source
)+1:], FileName
)
344 TrimR8SourceCode(Source
, Target
)
346 ## Trim one EDK source code file
348 # Do following replacement:
350 # (**PeiServices\).PciCfg = <*>;
352 # STATIC EFI_PEI_PPI_DESCRIPTOR gEcpPeiPciCfgPpiList = {
353 # (EFI_PEI_PPI_DESCRIPTOR_PPI | EFI_PEI_PPI_DESCRIPTOR_TERMINATE_LIST),
354 # &gEcpPeiPciCfgPpiGuid,
357 # (**PeiServices).InstallPpi (PeiServices, &gEcpPeiPciCfgPpiList);
360 # => PeiLibPciCfgModify (<*>)
362 # gRT->ReportStatusCode (<*>)
363 # => EfiLibReportStatusCode (<*>)
365 # #include <LoadFile\.h>
366 # => #include <FvLoadFile.h>
368 # CreateEvent (EFI_EVENT_SIGNAL_READY_TO_BOOT, <*>)
369 # => EfiCreateEventReadyToBoot (<*>)
371 # CreateEvent (EFI_EVENT_SIGNAL_LEGACY_BOOT, <*>)
372 # => EfiCreateEventLegacyBoot (<*>)
374 # @param Source File to be trimmed
375 # @param Target File to store the trimmed content
377 def TrimR8SourceCode(Source
, Target
):
378 EdkLogger
.verbose("\t%s -> %s" % (Source
, Target
))
379 CreateDirectory(os
.path
.dirname(Target
))
382 f
= open (Source
,'rb')
384 EdkLogger
.error("Trim", FILE_OPEN_FAILURE
, ExtraData
=Source
)
390 for Re
,Repl
in gImportCodePatterns
:
392 NewLines
= Re
.sub(Repl
, Lines
)
394 NewLines
= Re
.sub(Repl
, NewLines
)
396 # save all lines if trimmed
397 if Source
== Target
and NewLines
== Lines
:
401 f
= open (Target
,'wb')
403 EdkLogger
.error("Trim", FILE_OPEN_FAILURE
, ExtraData
=Target
)
408 ## Parse command line options
410 # Using standard Python module optparse to parse command line option of this tool.
412 # @retval Options A optparse.Values object containing the parsed options
413 # @retval InputFile Path of file to be trimmed
417 make_option("-s", "--source-code", dest
="FileType", const
="SourceCode", action
="store_const",
418 help="The input file is preprocessed source code, including C or assembly code"),
419 make_option("-r", "--vfr-file", dest
="FileType", const
="Vfr", action
="store_const",
420 help="The input file is preprocessed VFR file"),
421 make_option("-a", "--asl-file", dest
="FileType", const
="Asl", action
="store_const",
422 help="The input file is ASL file"),
423 make_option("-8", "--r8-source-code", dest
="FileType", const
="R8SourceCode", action
="store_const",
424 help="The input file is source code for R8 to be trimmed for ECP"),
426 make_option("-c", "--convert-hex", dest
="ConvertHex", action
="store_true",
427 help="Convert standard hex format (0xabcd) to MASM format (abcdh)"),
429 make_option("-o", "--output", dest
="OutputFile",
430 help="File to store the trimmed content"),
431 make_option("-v", "--verbose", dest
="LogLevel", action
="store_const", const
=EdkLogger
.VERBOSE
,
432 help="Run verbosely"),
433 make_option("-d", "--debug", dest
="LogLevel", type="int",
434 help="Run with debug information"),
435 make_option("-q", "--quiet", dest
="LogLevel", action
="store_const", const
=EdkLogger
.QUIET
,
437 make_option("-?", action
="help", help="show this help message and exit"),
440 # use clearer usage to override default usage message
441 UsageString
= "%prog [-s|-r|-a] [-c] [-v|-d <debug_level>|-q] [-o <output_file>] <input_file>"
443 Parser
= OptionParser(description
=__copyright__
, version
=__version__
, option_list
=OptionList
, usage
=UsageString
)
444 Parser
.set_defaults(FileType
="Vfr")
445 Parser
.set_defaults(ConvertHex
=False)
446 Parser
.set_defaults(LogLevel
=EdkLogger
.INFO
)
448 Options
, Args
= Parser
.parse_args()
452 EdkLogger
.error("Trim", OPTION_MISSING
, ExtraData
=Parser
.get_usage())
454 EdkLogger
.error("Trim", OPTION_NOT_SUPPORTED
, ExtraData
=Parser
.get_usage())
457 return Options
, InputFile
461 # This method mainly dispatch specific methods per the command line options.
462 # If no error found, return zero value so the caller of this tool can know
463 # if it's executed successfully or not.
465 # @retval 0 Tool was successful
466 # @retval 1 Tool failed
470 EdkLogger
.Initialize()
471 CommandOptions
, InputFile
= Options()
472 if CommandOptions
.LogLevel
< EdkLogger
.DEBUG_9
:
473 EdkLogger
.SetLevel(CommandOptions
.LogLevel
+ 1)
475 EdkLogger
.SetLevel(CommandOptions
.LogLevel
)
476 except FatalError
, X
:
480 if CommandOptions
.FileType
== "Vfr":
481 if CommandOptions
.OutputFile
== None:
482 CommandOptions
.OutputFile
= os
.path
.splitext(InputFile
)[0] + '.iii'
483 TrimPreprocessedVfr(InputFile
, CommandOptions
.OutputFile
)
484 elif CommandOptions
.FileType
== "Asl":
485 if CommandOptions
.OutputFile
== None:
486 CommandOptions
.OutputFile
= os
.path
.splitext(InputFile
)[0] + '.iii'
487 TrimAslFile(InputFile
, CommandOptions
.OutputFile
)
488 elif CommandOptions
.FileType
== "R8SourceCode":
489 TrimR8Sources(InputFile
, CommandOptions
.OutputFile
)
491 if CommandOptions
.OutputFile
== None:
492 CommandOptions
.OutputFile
= os
.path
.splitext(InputFile
)[0] + '.iii'
493 TrimPreprocessedFile(InputFile
, CommandOptions
.OutputFile
, CommandOptions
.ConvertHex
)
494 except FatalError
, X
:
497 if CommandOptions
!= None and CommandOptions
.LogLevel
<= EdkLogger
.DEBUG_9
:
498 EdkLogger
.quiet("(Python %s on %s) " % (platform
.python_version(), sys
.platform
) + traceback
.format_exc())
506 "Unknown fatal error when trimming [%s]" % InputFile
,
507 ExtraData
="\n(Please send email to dev@buildtools.tianocore.org for help, attaching following call stack trace!)\n",
510 EdkLogger
.quiet("(Python %s on %s) " % (platform
.python_version(), sys
.platform
) + traceback
.format_exc())
515 if __name__
== '__main__':
517 ## 0-127 is a safe return range, and 1 is a standard default error
518 if r
< 0 or r
> 127: r
= 1