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+["<]LoadFile\.h[">]', re
.MULTILINE
),
81 '#include <FvLoadFile.h>'
85 re
.compile('#include\s+EFI_GUID_DEFINITION\s*\(FirmwareFileSystem\)', re
.MULTILINE
),
86 '#include EFI_GUID_DEFINITION (FirmwareFileSystem)\n#include EFI_GUID_DEFINITION (FirmwareFileSystem2)'
90 re
.compile('gEfiFirmwareFileSystemGuid', re
.MULTILINE
),
91 'gEfiFirmwareFileSystem2Guid'
95 re
.compile('EFI_FVH_REVISION', re
.MULTILINE
),
100 re
.compile("(\s*)\S*CreateEvent\s*\([\s\n]*EFI_EVENT_SIGNAL_READY_TO_BOOT[^,]*,((?:[^;]+\n)+)(\s*\));", re
.MULTILINE
),
101 '\\1EfiCreateEventReadyToBoot (\\2\\3;'
105 re
.compile("(\s*)\S*CreateEvent\s*\([\s\n]*EFI_EVENT_SIGNAL_LEGACY_BOOT[^,]*,((?:[^;]+\n)+)(\s*\));", re
.MULTILINE
),
106 '\\1EfiCreateEventLegacyBoot (\\2\\3;'
109 # re.compile("(\W)(PEI_PCI_CFG_PPI)(\W)", re.MULTILINE),
114 ## file cache to avoid circular include in ASL file
115 gIncludedAslFile
= []
117 ## Trim preprocessed source code
119 # Remove extra content made by preprocessor. The preprocessor must enable the
120 # line number generation option when preprocessing.
122 # @param Source File to be trimmed
123 # @param Target File to store the trimmed content
124 # @param Convert If True, convert standard HEX format to MASM format
126 def TrimPreprocessedFile(Source
, Target
, Convert
):
127 CreateDirectory(os
.path
.dirname(Target
))
129 f
= open (Source
, 'r')
131 EdkLogger
.error("Trim", FILE_OPEN_FAILURE
, ExtraData
=Source
)
134 Lines
= f
.readlines()
137 PreprocessedFile
= ""
139 LineIndexOfOriginalFile
= None
141 LineControlDirectiveFound
= False
142 for Index
in range(len(Lines
)):
145 # Find out the name of files injected by preprocessor from the lines
146 # with Line Control directive
148 MatchList
= gLineControlDirective
.findall(Line
)
150 MatchList
= MatchList
[0]
151 if len(MatchList
) == 2:
152 LineNumber
= int(MatchList
[0], 0)
153 InjectedFile
= MatchList
[1]
154 # The first injetcted file must be the preprocessed file itself
155 if PreprocessedFile
== "":
156 PreprocessedFile
= InjectedFile
157 LineControlDirectiveFound
= True
159 elif PreprocessedFile
== "" or InjectedFile
!= PreprocessedFile
:
162 if LineIndexOfOriginalFile
== None:
164 # Any non-empty lines must be from original preprocessed file.
165 # And this must be the first one.
167 LineIndexOfOriginalFile
= Index
168 EdkLogger
.verbose("Found original file content starting from line %d"
169 % (LineIndexOfOriginalFile
+ 1))
171 # convert HEX number format if indicated
173 Line
= gHexNumberPattern
.sub(r
"0\1h", Line
)
175 if LineNumber
!= None:
176 EdkLogger
.verbose("Got line directive: line=%d" % LineNumber
)
177 # in case preprocessor removed some lines, like blank or comment lines
178 if LineNumber
<= len(NewLines
):
180 NewLines
[LineNumber
- 1] = Line
182 if LineNumber
> (len(NewLines
) + 1):
183 for LineIndex
in range(len(NewLines
), LineNumber
-1):
184 NewLines
.append(os
.linesep
)
185 NewLines
.append(Line
)
187 EdkLogger
.verbose("Now we have lines: %d" % len(NewLines
))
189 NewLines
.append(Line
)
191 # in case there's no line directive or linemarker found
192 if (not LineControlDirectiveFound
) and NewLines
== []:
197 f
= open (Target
, 'wb')
199 EdkLogger
.error("Trim", FILE_OPEN_FAILURE
, ExtraData
=Target
)
200 f
.writelines(NewLines
)
203 ## Trim preprocessed VFR file
205 # Remove extra content made by preprocessor. The preprocessor doesn't need to
206 # enable line number generation option when preprocessing.
208 # @param Source File to be trimmed
209 # @param Target File to store the trimmed content
211 def TrimPreprocessedVfr(Source
, Target
):
212 CreateDirectory(os
.path
.dirname(Target
))
215 f
= open (Source
,'r')
217 EdkLogger
.error("Trim", FILE_OPEN_FAILURE
, ExtraData
=Source
)
219 Lines
= f
.readlines()
226 for Index
in range(len(Lines
)):
228 # don't trim the lines from "formset" definition to the end of file
229 if Line
.strip() == 'formset':
232 if FoundTypedef
== False and (Line
.find('#line') == 0 or Line
.find('# ') == 0):
233 # empty the line number directive if it's not aomong "typedef struct"
237 if FoundTypedef
== False and gTypedefPattern
.search(Line
) == None:
238 # keep "#pragram pack" directive
239 if gPragmaPattern
.search(Line
) == None:
242 elif FoundTypedef
== False:
243 # found "typedef struct", keept its position and set a flag
247 # match { and } to find the end of typedef definition
248 if Line
.find("{") >= 0:
250 elif Line
.find("}") >= 0:
253 # "typedef struct" must end with a ";"
254 if Brace
== 0 and Line
.find(";") >= 0:
257 # keep all "typedef struct" except to GUID, EFI_PLABEL and PAL_CALL_RETURN
258 if Line
.strip("} ;\r\n") in ["GUID", "EFI_PLABEL", "PAL_CALL_RETURN"]:
259 for i
in range(TypedefStart
, TypedefEnd
+1):
262 # save all lines trimmed
264 f
= open (Target
,'w')
266 EdkLogger
.error("Trim", FILE_OPEN_FAILURE
, ExtraData
=Target
)
270 ## Read the content ASL file, including ASL included, recursively
272 # @param Source File to be read
273 # @param Indent Spaces before the Include() statement
275 def DoInclude(Source
, Indent
=''):
277 # avoid A "include" B and B "include" A
278 if Source
in gIncludedAslFile
:
279 EdkLogger
.warn("Trim", "Circular include",
280 ExtraData
= "%s -> %s" % (" -> ".join(gIncludedAslFile
), Source
))
282 gIncludedAslFile
.append(Source
)
287 EdkLogger
.error("Trim", FILE_OPEN_FAILURE
, ExtraData
=Source
)
290 Result
= gAslIncludePattern
.findall(Line
)
292 NewFileContent
.append("%s%s" % (Indent
, Line
))
294 CurrentIndent
= Indent
+ Result
[0][0]
295 IncludedFile
= Result
[0][1]
296 NewFileContent
.extend(DoInclude(IncludedFile
, CurrentIndent
))
297 NewFileContent
.append("\n")
299 gIncludedAslFile
.pop()
302 return NewFileContent
307 # Replace ASL include statement with the content the included file
309 # @param Source File to be trimmed
310 # @param Target File to store the trimmed content
312 def TrimAslFile(Source
, Target
):
313 CreateDirectory(os
.path
.dirname(Target
))
316 SourceDir
= os
.path
.dirname(Source
)
320 Lines
= DoInclude(Source
)
323 # save all lines trimmed
325 f
= open (Target
,'w')
327 EdkLogger
.error("Trim", FILE_OPEN_FAILURE
, ExtraData
=Target
)
332 ## Trim EDK source code file(s)
335 # @param Source File or directory to be trimmed
336 # @param Target File or directory to store the trimmed content
338 def TrimR8Sources(Source
, Target
):
339 if os
.path
.isdir(Source
):
340 for CurrentDir
, Dirs
, Files
in os
.walk(Source
):
346 for FileName
in Files
:
347 Dummy
, Ext
= os
.path
.splitext(FileName
)
348 if Ext
.upper() not in ['.C', '.H']: continue
349 if Target
== None or Target
== '':
351 os
.path
.join(CurrentDir
, FileName
),
352 os
.path
.join(CurrentDir
, FileName
)
356 os
.path
.join(CurrentDir
, FileName
),
357 os
.path
.join(Target
, CurrentDir
[len(Source
)+1:], FileName
)
360 TrimR8SourceCode(Source
, Target
)
362 ## Trim one EDK source code file
364 # Do following replacement:
366 # (**PeiServices\).PciCfg = <*>;
368 # STATIC EFI_PEI_PPI_DESCRIPTOR gEcpPeiPciCfgPpiList = {
369 # (EFI_PEI_PPI_DESCRIPTOR_PPI | EFI_PEI_PPI_DESCRIPTOR_TERMINATE_LIST),
370 # &gEcpPeiPciCfgPpiGuid,
373 # (**PeiServices).InstallPpi (PeiServices, &gEcpPeiPciCfgPpiList);
376 # => PeiLibPciCfgModify (<*>)
378 # gRT->ReportStatusCode (<*>)
379 # => EfiLibReportStatusCode (<*>)
381 # #include <LoadFile\.h>
382 # => #include <FvLoadFile.h>
384 # CreateEvent (EFI_EVENT_SIGNAL_READY_TO_BOOT, <*>)
385 # => EfiCreateEventReadyToBoot (<*>)
387 # CreateEvent (EFI_EVENT_SIGNAL_LEGACY_BOOT, <*>)
388 # => EfiCreateEventLegacyBoot (<*>)
390 # @param Source File to be trimmed
391 # @param Target File to store the trimmed content
393 def TrimR8SourceCode(Source
, Target
):
394 EdkLogger
.verbose("\t%s -> %s" % (Source
, Target
))
395 CreateDirectory(os
.path
.dirname(Target
))
398 f
= open (Source
,'rb')
400 EdkLogger
.error("Trim", FILE_OPEN_FAILURE
, ExtraData
=Source
)
406 for Re
,Repl
in gImportCodePatterns
:
408 NewLines
= Re
.sub(Repl
, Lines
)
410 NewLines
= Re
.sub(Repl
, NewLines
)
412 # save all lines if trimmed
413 if Source
== Target
and NewLines
== Lines
:
417 f
= open (Target
,'wb')
419 EdkLogger
.error("Trim", FILE_OPEN_FAILURE
, ExtraData
=Target
)
424 ## Parse command line options
426 # Using standard Python module optparse to parse command line option of this tool.
428 # @retval Options A optparse.Values object containing the parsed options
429 # @retval InputFile Path of file to be trimmed
433 make_option("-s", "--source-code", dest
="FileType", const
="SourceCode", action
="store_const",
434 help="The input file is preprocessed source code, including C or assembly code"),
435 make_option("-r", "--vfr-file", dest
="FileType", const
="Vfr", action
="store_const",
436 help="The input file is preprocessed VFR file"),
437 make_option("-a", "--asl-file", dest
="FileType", const
="Asl", action
="store_const",
438 help="The input file is ASL file"),
439 make_option("-8", "--r8-source-code", dest
="FileType", const
="R8SourceCode", action
="store_const",
440 help="The input file is source code for R8 to be trimmed for ECP"),
442 make_option("-c", "--convert-hex", dest
="ConvertHex", action
="store_true",
443 help="Convert standard hex format (0xabcd) to MASM format (abcdh)"),
445 make_option("-o", "--output", dest
="OutputFile",
446 help="File to store the trimmed content"),
447 make_option("-v", "--verbose", dest
="LogLevel", action
="store_const", const
=EdkLogger
.VERBOSE
,
448 help="Run verbosely"),
449 make_option("-d", "--debug", dest
="LogLevel", type="int",
450 help="Run with debug information"),
451 make_option("-q", "--quiet", dest
="LogLevel", action
="store_const", const
=EdkLogger
.QUIET
,
453 make_option("-?", action
="help", help="show this help message and exit"),
456 # use clearer usage to override default usage message
457 UsageString
= "%prog [-s|-r|-a] [-c] [-v|-d <debug_level>|-q] [-o <output_file>] <input_file>"
459 Parser
= OptionParser(description
=__copyright__
, version
=__version__
, option_list
=OptionList
, usage
=UsageString
)
460 Parser
.set_defaults(FileType
="Vfr")
461 Parser
.set_defaults(ConvertHex
=False)
462 Parser
.set_defaults(LogLevel
=EdkLogger
.INFO
)
464 Options
, Args
= Parser
.parse_args()
468 EdkLogger
.error("Trim", OPTION_MISSING
, ExtraData
=Parser
.get_usage())
470 EdkLogger
.error("Trim", OPTION_NOT_SUPPORTED
, ExtraData
=Parser
.get_usage())
473 return Options
, InputFile
477 # This method mainly dispatch specific methods per the command line options.
478 # If no error found, return zero value so the caller of this tool can know
479 # if it's executed successfully or not.
481 # @retval 0 Tool was successful
482 # @retval 1 Tool failed
486 EdkLogger
.Initialize()
487 CommandOptions
, InputFile
= Options()
488 if CommandOptions
.LogLevel
< EdkLogger
.DEBUG_9
:
489 EdkLogger
.SetLevel(CommandOptions
.LogLevel
+ 1)
491 EdkLogger
.SetLevel(CommandOptions
.LogLevel
)
492 except FatalError
, X
:
496 if CommandOptions
.FileType
== "Vfr":
497 if CommandOptions
.OutputFile
== None:
498 CommandOptions
.OutputFile
= os
.path
.splitext(InputFile
)[0] + '.iii'
499 TrimPreprocessedVfr(InputFile
, CommandOptions
.OutputFile
)
500 elif CommandOptions
.FileType
== "Asl":
501 if CommandOptions
.OutputFile
== None:
502 CommandOptions
.OutputFile
= os
.path
.splitext(InputFile
)[0] + '.iii'
503 TrimAslFile(InputFile
, CommandOptions
.OutputFile
)
504 elif CommandOptions
.FileType
== "R8SourceCode":
505 TrimR8Sources(InputFile
, CommandOptions
.OutputFile
)
507 if CommandOptions
.OutputFile
== None:
508 CommandOptions
.OutputFile
= os
.path
.splitext(InputFile
)[0] + '.iii'
509 TrimPreprocessedFile(InputFile
, CommandOptions
.OutputFile
, CommandOptions
.ConvertHex
)
510 except FatalError
, X
:
513 if CommandOptions
!= None and CommandOptions
.LogLevel
<= EdkLogger
.DEBUG_9
:
514 EdkLogger
.quiet("(Python %s on %s) " % (platform
.python_version(), sys
.platform
) + traceback
.format_exc())
522 "Unknown fatal error when trimming [%s]" % InputFile
,
523 ExtraData
="\n(Please send email to edk2-buildtools-devel@lists.sourceforge.net for help, attaching following call stack trace!)\n",
526 EdkLogger
.quiet("(Python %s on %s) " % (platform
.python_version(), sys
.platform
) + traceback
.format_exc())
531 if __name__
== '__main__':
533 ## 0-127 is a safe return range, and 1 is a standard default error
534 if r
< 0 or r
> 127: r
= 1