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 *
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-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]+)")
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+EFI_GUID_DEFINITION\s*\(FirmwareFileSystem\)', re
.MULTILINE
),
81 '#include EFI_GUID_DEFINITION (FirmwareFileSystem)\n#include EFI_GUID_DEFINITION (FirmwareFileSystem2)'
85 re
.compile('gEfiFirmwareFileSystemGuid', re
.MULTILINE
),
86 'gEfiFirmwareFileSystem2Guid'
90 re
.compile('EFI_FVH_REVISION', re
.MULTILINE
),
95 re
.compile("(\s*)\S*CreateEvent\s*\([\s\n]*EFI_EVENT_SIGNAL_READY_TO_BOOT[^,]*,((?:[^;]+\n)+)(\s*\));", re
.MULTILINE
),
96 '\\1EfiCreateEventReadyToBoot (\\2\\3;'
100 re
.compile("(\s*)\S*CreateEvent\s*\([\s\n]*EFI_EVENT_SIGNAL_LEGACY_BOOT[^,]*,((?:[^;]+\n)+)(\s*\));", re
.MULTILINE
),
101 '\\1EfiCreateEventLegacyBoot (\\2\\3;'
104 # re.compile("(\W)(PEI_PCI_CFG_PPI)(\W)", re.MULTILINE),
109 ## file cache to avoid circular include in ASL file
110 gIncludedAslFile
= []
112 ## Trim preprocessed source code
114 # Remove extra content made by preprocessor. The preprocessor must enable the
115 # line number generation option when preprocessing.
117 # @param Source File to be trimmed
118 # @param Target File to store the trimmed content
119 # @param Convert If True, convert standard HEX format to MASM format
121 def TrimPreprocessedFile(Source
, Target
, Convert
):
122 CreateDirectory(os
.path
.dirname(Target
))
124 f
= open (Source
, 'r')
126 EdkLogger
.error("Trim", FILE_OPEN_FAILURE
, ExtraData
=Source
)
129 Lines
= f
.readlines()
132 PreprocessedFile
= ""
134 LineIndexOfOriginalFile
= None
136 LineControlDirectiveFound
= False
137 for Index
in range(len(Lines
)):
140 # Find out the name of files injected by preprocessor from the lines
141 # with Line Control directive
143 MatchList
= gLineControlDirective
.findall(Line
)
145 MatchList
= MatchList
[0]
146 if len(MatchList
) == 2:
147 LineNumber
= int(MatchList
[0], 0)
148 InjectedFile
= MatchList
[1]
149 # The first injetcted file must be the preprocessed file itself
150 if PreprocessedFile
== "":
151 PreprocessedFile
= InjectedFile
152 LineControlDirectiveFound
= True
154 elif PreprocessedFile
== "" or InjectedFile
!= PreprocessedFile
:
157 if LineIndexOfOriginalFile
== None:
159 # Any non-empty lines must be from original preprocessed file.
160 # And this must be the first one.
162 LineIndexOfOriginalFile
= Index
163 EdkLogger
.verbose("Found original file content starting from line %d"
164 % (LineIndexOfOriginalFile
+ 1))
166 # convert HEX number format if indicated
168 Line
= gHexNumberPattern
.sub(r
"0\1h", Line
)
170 if LineNumber
!= None:
171 EdkLogger
.verbose("Got line directive: line=%d" % LineNumber
)
172 # in case preprocessor removed some lines, like blank or comment lines
173 if LineNumber
<= len(NewLines
):
175 NewLines
[LineNumber
- 1] = Line
177 if LineNumber
> (len(NewLines
) + 1):
178 for LineIndex
in range(len(NewLines
), LineNumber
-1):
179 NewLines
.append(os
.linesep
)
180 NewLines
.append(Line
)
182 EdkLogger
.verbose("Now we have lines: %d" % len(NewLines
))
184 NewLines
.append(Line
)
186 # in case there's no line directive or linemarker found
187 if (not LineControlDirectiveFound
) and NewLines
== []:
192 f
= open (Target
, 'wb')
194 EdkLogger
.error("Trim", FILE_OPEN_FAILURE
, ExtraData
=Target
)
195 f
.writelines(NewLines
)
198 ## Trim preprocessed VFR file
200 # Remove extra content made by preprocessor. The preprocessor doesn't need to
201 # enable line number generation option when preprocessing.
203 # @param Source File to be trimmed
204 # @param Target File to store the trimmed content
206 def TrimPreprocessedVfr(Source
, Target
):
207 CreateDirectory(os
.path
.dirname(Target
))
210 f
= open (Source
,'r')
212 EdkLogger
.error("Trim", FILE_OPEN_FAILURE
, ExtraData
=Source
)
214 Lines
= f
.readlines()
221 for Index
in range(len(Lines
)):
223 # don't trim the lines from "formset" definition to the end of file
224 if Line
.strip() == 'formset':
227 if FoundTypedef
== False and (Line
.find('#line') == 0 or Line
.find('# ') == 0):
228 # empty the line number directive if it's not aomong "typedef struct"
232 if FoundTypedef
== False and gTypedefPattern
.search(Line
) == None:
233 # keep "#pragram pack" directive
234 if gPragmaPattern
.search(Line
) == None:
237 elif FoundTypedef
== False:
238 # found "typedef struct", keept its position and set a flag
242 # match { and } to find the end of typedef definition
243 if Line
.find("{") >= 0:
245 elif Line
.find("}") >= 0:
248 # "typedef struct" must end with a ";"
249 if Brace
== 0 and Line
.find(";") >= 0:
252 # keep all "typedef struct" except to GUID, EFI_PLABEL and PAL_CALL_RETURN
253 if Line
.strip("} ;\r\n") in ["GUID", "EFI_PLABEL", "PAL_CALL_RETURN"]:
254 for i
in range(TypedefStart
, TypedefEnd
+1):
257 # save all lines trimmed
259 f
= open (Target
,'w')
261 EdkLogger
.error("Trim", FILE_OPEN_FAILURE
, ExtraData
=Target
)
265 ## Read the content ASL file, including ASL included, recursively
267 # @param Source File to be read
268 # @param Indent Spaces before the Include() statement
270 def DoInclude(Source
, Indent
=''):
272 # avoid A "include" B and B "include" A
273 if Source
in gIncludedAslFile
:
274 EdkLogger
.warn("Trim", "Circular include",
275 ExtraData
= "%s -> %s" % (" -> ".join(gIncludedAslFile
), Source
))
277 gIncludedAslFile
.append(Source
)
282 EdkLogger
.error("Trim", FILE_OPEN_FAILURE
, ExtraData
=Source
)
285 Result
= gAslIncludePattern
.findall(Line
)
287 NewFileContent
.append("%s%s" % (Indent
, Line
))
289 CurrentIndent
= Indent
+ Result
[0][0]
290 IncludedFile
= Result
[0][1]
291 NewFileContent
.extend(DoInclude(IncludedFile
, CurrentIndent
))
292 NewFileContent
.append("\n")
294 gIncludedAslFile
.pop()
297 return NewFileContent
302 # Replace ASL include statement with the content the included file
304 # @param Source File to be trimmed
305 # @param Target File to store the trimmed content
307 def TrimAslFile(Source
, Target
):
308 CreateDirectory(os
.path
.dirname(Target
))
311 SourceDir
= os
.path
.dirname(Source
)
315 Lines
= DoInclude(Source
)
318 # save all lines trimmed
320 f
= open (Target
,'w')
322 EdkLogger
.error("Trim", FILE_OPEN_FAILURE
, ExtraData
=Target
)
327 ## Trim EDK source code file(s)
330 # @param Source File or directory to be trimmed
331 # @param Target File or directory to store the trimmed content
333 def TrimR8Sources(Source
, Target
):
334 if os
.path
.isdir(Source
):
335 for CurrentDir
, Dirs
, Files
in os
.walk(Source
):
341 for FileName
in Files
:
342 Dummy
, Ext
= os
.path
.splitext(FileName
)
343 if Ext
.upper() not in ['.C', '.H']: continue
344 if Target
== None or Target
== '':
346 os
.path
.join(CurrentDir
, FileName
),
347 os
.path
.join(CurrentDir
, FileName
)
351 os
.path
.join(CurrentDir
, FileName
),
352 os
.path
.join(Target
, CurrentDir
[len(Source
)+1:], FileName
)
355 TrimR8SourceCode(Source
, Target
)
357 ## Trim one EDK source code file
359 # Do following replacement:
361 # (**PeiServices\).PciCfg = <*>;
363 # STATIC EFI_PEI_PPI_DESCRIPTOR gEcpPeiPciCfgPpiList = {
364 # (EFI_PEI_PPI_DESCRIPTOR_PPI | EFI_PEI_PPI_DESCRIPTOR_TERMINATE_LIST),
365 # &gEcpPeiPciCfgPpiGuid,
368 # (**PeiServices).InstallPpi (PeiServices, &gEcpPeiPciCfgPpiList);
371 # => PeiLibPciCfgModify (<*>)
373 # gRT->ReportStatusCode (<*>)
374 # => EfiLibReportStatusCode (<*>)
376 # #include <LoadFile\.h>
377 # => #include <FvLoadFile.h>
379 # CreateEvent (EFI_EVENT_SIGNAL_READY_TO_BOOT, <*>)
380 # => EfiCreateEventReadyToBoot (<*>)
382 # CreateEvent (EFI_EVENT_SIGNAL_LEGACY_BOOT, <*>)
383 # => EfiCreateEventLegacyBoot (<*>)
385 # @param Source File to be trimmed
386 # @param Target File to store the trimmed content
388 def TrimR8SourceCode(Source
, Target
):
389 EdkLogger
.verbose("\t%s -> %s" % (Source
, Target
))
390 CreateDirectory(os
.path
.dirname(Target
))
393 f
= open (Source
,'rb')
395 EdkLogger
.error("Trim", FILE_OPEN_FAILURE
, ExtraData
=Source
)
401 for Re
,Repl
in gImportCodePatterns
:
403 NewLines
= Re
.sub(Repl
, Lines
)
405 NewLines
= Re
.sub(Repl
, NewLines
)
407 # save all lines if trimmed
408 if Source
== Target
and NewLines
== Lines
:
412 f
= open (Target
,'wb')
414 EdkLogger
.error("Trim", FILE_OPEN_FAILURE
, ExtraData
=Target
)
419 ## Parse command line options
421 # Using standard Python module optparse to parse command line option of this tool.
423 # @retval Options A optparse.Values object containing the parsed options
424 # @retval InputFile Path of file to be trimmed
428 make_option("-s", "--source-code", dest
="FileType", const
="SourceCode", action
="store_const",
429 help="The input file is preprocessed source code, including C or assembly code"),
430 make_option("-r", "--vfr-file", dest
="FileType", const
="Vfr", action
="store_const",
431 help="The input file is preprocessed VFR file"),
432 make_option("-a", "--asl-file", dest
="FileType", const
="Asl", action
="store_const",
433 help="The input file is ASL file"),
434 make_option("-8", "--r8-source-code", dest
="FileType", const
="R8SourceCode", action
="store_const",
435 help="The input file is source code for R8 to be trimmed for ECP"),
437 make_option("-c", "--convert-hex", dest
="ConvertHex", action
="store_true",
438 help="Convert standard hex format (0xabcd) to MASM format (abcdh)"),
440 make_option("-o", "--output", dest
="OutputFile",
441 help="File to store the trimmed content"),
442 make_option("-v", "--verbose", dest
="LogLevel", action
="store_const", const
=EdkLogger
.VERBOSE
,
443 help="Run verbosely"),
444 make_option("-d", "--debug", dest
="LogLevel", type="int",
445 help="Run with debug information"),
446 make_option("-q", "--quiet", dest
="LogLevel", action
="store_const", const
=EdkLogger
.QUIET
,
448 make_option("-?", action
="help", help="show this help message and exit"),
451 # use clearer usage to override default usage message
452 UsageString
= "%prog [-s|-r|-a] [-c] [-v|-d <debug_level>|-q] [-o <output_file>] <input_file>"
454 Parser
= OptionParser(description
=__copyright__
, version
=__version__
, option_list
=OptionList
, usage
=UsageString
)
455 Parser
.set_defaults(FileType
="Vfr")
456 Parser
.set_defaults(ConvertHex
=False)
457 Parser
.set_defaults(LogLevel
=EdkLogger
.INFO
)
459 Options
, Args
= Parser
.parse_args()
463 EdkLogger
.error("Trim", OPTION_MISSING
, ExtraData
=Parser
.get_usage())
465 EdkLogger
.error("Trim", OPTION_NOT_SUPPORTED
, ExtraData
=Parser
.get_usage())
468 return Options
, InputFile
472 # This method mainly dispatch specific methods per the command line options.
473 # If no error found, return zero value so the caller of this tool can know
474 # if it's executed successfully or not.
476 # @retval 0 Tool was successful
477 # @retval 1 Tool failed
481 EdkLogger
.Initialize()
482 CommandOptions
, InputFile
= Options()
483 if CommandOptions
.LogLevel
< EdkLogger
.DEBUG_9
:
484 EdkLogger
.SetLevel(CommandOptions
.LogLevel
+ 1)
486 EdkLogger
.SetLevel(CommandOptions
.LogLevel
)
487 except FatalError
, X
:
491 if CommandOptions
.FileType
== "Vfr":
492 if CommandOptions
.OutputFile
== None:
493 CommandOptions
.OutputFile
= os
.path
.splitext(InputFile
)[0] + '.iii'
494 TrimPreprocessedVfr(InputFile
, CommandOptions
.OutputFile
)
495 elif CommandOptions
.FileType
== "Asl":
496 if CommandOptions
.OutputFile
== None:
497 CommandOptions
.OutputFile
= os
.path
.splitext(InputFile
)[0] + '.iii'
498 TrimAslFile(InputFile
, CommandOptions
.OutputFile
)
499 elif CommandOptions
.FileType
== "R8SourceCode":
500 TrimR8Sources(InputFile
, CommandOptions
.OutputFile
)
502 if CommandOptions
.OutputFile
== None:
503 CommandOptions
.OutputFile
= os
.path
.splitext(InputFile
)[0] + '.iii'
504 TrimPreprocessedFile(InputFile
, CommandOptions
.OutputFile
, CommandOptions
.ConvertHex
)
505 except FatalError
, X
:
508 if CommandOptions
!= None and CommandOptions
.LogLevel
<= EdkLogger
.DEBUG_9
:
509 EdkLogger
.quiet("(Python %s on %s) " % (platform
.python_version(), sys
.platform
) + traceback
.format_exc())
517 "Unknown fatal error when trimming [%s]" % InputFile
,
518 ExtraData
="\n(Please send email to edk2-buildtools-devel@lists.sourceforge.net for help, attaching following call stack trace!)\n",
521 EdkLogger
.quiet("(Python %s on %s) " % (platform
.python_version(), sys
.platform
) + traceback
.format_exc())
526 if __name__
== '__main__':
528 ## 0-127 is a safe return range, and 1 is a standard default error
529 if r
< 0 or r
> 127: r
= 1