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 ## Regular expression for matching C style #include "XXX.asl" in asl file
44 gAslCIncludePattern
= re
.compile(r
'^(\s*)#include\s*[<"]\s*([-\\/\w.]+)\s*([>"])', re
.MULTILINE
)
45 ## Regular expression for matching constant with 'ULL' and 'UL', 'LL', 'L' postfix
46 gLongNumberPattern
= re
.compile("(0[xX][0-9a-fA-F]+|[0-9]+)U?LL", re
.MULTILINE
)
47 ## Patterns used to convert EDK conventions to EDK2 ECP conventions
48 gImportCodePatterns
= [
50 re
.compile('^(\s*)\(\*\*PeiServices\)\.PciCfg\s*=\s*([^;\s]+);', re
.MULTILINE
),
52 \\1 STATIC EFI_PEI_PPI_DESCRIPTOR gEcpPeiPciCfgPpiList = {
53 \\1 (EFI_PEI_PPI_DESCRIPTOR_PPI | EFI_PEI_PPI_DESCRIPTOR_TERMINATE_LIST),
54 \\1 &gEcpPeiPciCfgPpiGuid,
57 \\1 (**PeiServices).InstallPpi (PeiServices, &gEcpPeiPciCfgPpiList);
62 re
.compile('^(\s*)\(\*PeiServices\)->PciCfg\s*=\s*([^;\s]+);', re
.MULTILINE
),
64 \\1 STATIC EFI_PEI_PPI_DESCRIPTOR gEcpPeiPciCfgPpiList = {
65 \\1 (EFI_PEI_PPI_DESCRIPTOR_PPI | EFI_PEI_PPI_DESCRIPTOR_TERMINATE_LIST),
66 \\1 &gEcpPeiPciCfgPpiGuid,
69 \\1 (**PeiServices).InstallPpi (PeiServices, &gEcpPeiPciCfgPpiList);
74 re
.compile("(\s*).+->Modify[\s\n]*\(", re
.MULTILINE
),
75 '\\1PeiLibPciCfgModify ('
79 re
.compile("(\W*)gRT->ReportStatusCode[\s\n]*\(", re
.MULTILINE
),
80 '\\1EfiLibReportStatusCode ('
84 re
.compile('#include\s+EFI_GUID_DEFINITION\s*\(FirmwareFileSystem\)', re
.MULTILINE
),
85 '#include EFI_GUID_DEFINITION (FirmwareFileSystem)\n#include EFI_GUID_DEFINITION (FirmwareFileSystem2)'
89 re
.compile('gEfiFirmwareFileSystemGuid', re
.MULTILINE
),
90 'gEfiFirmwareFileSystem2Guid'
94 re
.compile('EFI_FVH_REVISION', re
.MULTILINE
),
99 re
.compile("(\s*)\S*CreateEvent\s*\([\s\n]*EFI_EVENT_SIGNAL_READY_TO_BOOT[^,]*,((?:[^;]+\n)+)(\s*\));", re
.MULTILINE
),
100 '\\1EfiCreateEventReadyToBoot (\\2\\3;'
104 re
.compile("(\s*)\S*CreateEvent\s*\([\s\n]*EFI_EVENT_SIGNAL_LEGACY_BOOT[^,]*,((?:[^;]+\n)+)(\s*\));", re
.MULTILINE
),
105 '\\1EfiCreateEventLegacyBoot (\\2\\3;'
108 # re.compile("(\W)(PEI_PCI_CFG_PPI)(\W)", re.MULTILINE),
113 ## file cache to avoid circular include in ASL file
114 gIncludedAslFile
= []
116 ## Trim preprocessed source code
118 # Remove extra content made by preprocessor. The preprocessor must enable the
119 # line number generation option when preprocessing.
121 # @param Source File to be trimmed
122 # @param Target File to store the trimmed content
123 # @param Convert If True, convert standard HEX format to MASM format
125 def TrimPreprocessedFile(Source
, Target
, ConvertHex
, TrimLong
):
126 CreateDirectory(os
.path
.dirname(Target
))
128 f
= open (Source
, 'r')
130 EdkLogger
.error("Trim", FILE_OPEN_FAILURE
, ExtraData
=Source
)
133 Lines
= f
.readlines()
136 PreprocessedFile
= ""
138 LineIndexOfOriginalFile
= None
140 LineControlDirectiveFound
= False
141 for Index
in range(len(Lines
)):
144 # Find out the name of files injected by preprocessor from the lines
145 # with Line Control directive
147 MatchList
= gLineControlDirective
.findall(Line
)
149 MatchList
= MatchList
[0]
150 if len(MatchList
) == 2:
151 LineNumber
= int(MatchList
[0], 0)
152 InjectedFile
= MatchList
[1]
153 # The first injetcted file must be the preprocessed file itself
154 if PreprocessedFile
== "":
155 PreprocessedFile
= InjectedFile
156 LineControlDirectiveFound
= True
158 elif PreprocessedFile
== "" or InjectedFile
!= PreprocessedFile
:
161 if LineIndexOfOriginalFile
== None:
163 # Any non-empty lines must be from original preprocessed file.
164 # And this must be the first one.
166 LineIndexOfOriginalFile
= Index
167 EdkLogger
.verbose("Found original file content starting from line %d"
168 % (LineIndexOfOriginalFile
+ 1))
170 # convert HEX number format if indicated
172 Line
= gHexNumberPattern
.sub(r
"0\1h", Line
)
174 Line
= gLongNumberPattern
.sub(r
"\1", Line
)
176 if LineNumber
!= None:
177 EdkLogger
.verbose("Got line directive: line=%d" % LineNumber
)
178 # in case preprocessor removed some lines, like blank or comment lines
179 if LineNumber
<= len(NewLines
):
181 NewLines
[LineNumber
- 1] = Line
183 if LineNumber
> (len(NewLines
) + 1):
184 for LineIndex
in range(len(NewLines
), LineNumber
-1):
185 NewLines
.append(os
.linesep
)
186 NewLines
.append(Line
)
188 EdkLogger
.verbose("Now we have lines: %d" % len(NewLines
))
190 NewLines
.append(Line
)
192 # in case there's no line directive or linemarker found
193 if (not LineControlDirectiveFound
) and NewLines
== []:
198 f
= open (Target
, 'wb')
200 EdkLogger
.error("Trim", FILE_OPEN_FAILURE
, ExtraData
=Target
)
201 f
.writelines(NewLines
)
204 ## Trim preprocessed VFR file
206 # Remove extra content made by preprocessor. The preprocessor doesn't need to
207 # enable line number generation option when preprocessing.
209 # @param Source File to be trimmed
210 # @param Target File to store the trimmed content
212 def TrimPreprocessedVfr(Source
, Target
):
213 CreateDirectory(os
.path
.dirname(Target
))
216 f
= open (Source
,'r')
218 EdkLogger
.error("Trim", FILE_OPEN_FAILURE
, ExtraData
=Source
)
220 Lines
= f
.readlines()
227 for Index
in range(len(Lines
)):
229 # don't trim the lines from "formset" definition to the end of file
230 if Line
.strip() == 'formset':
233 if FoundTypedef
== False and (Line
.find('#line') == 0 or Line
.find('# ') == 0):
234 # empty the line number directive if it's not aomong "typedef struct"
238 if FoundTypedef
== False and gTypedefPattern
.search(Line
) == None:
239 # keep "#pragram pack" directive
240 if gPragmaPattern
.search(Line
) == None:
243 elif FoundTypedef
== False:
244 # found "typedef struct", keept its position and set a flag
248 # match { and } to find the end of typedef definition
249 if Line
.find("{") >= 0:
251 elif Line
.find("}") >= 0:
254 # "typedef struct" must end with a ";"
255 if Brace
== 0 and Line
.find(";") >= 0:
258 # keep all "typedef struct" except to GUID, EFI_PLABEL and PAL_CALL_RETURN
259 if Line
.strip("} ;\r\n") in ["GUID", "EFI_PLABEL", "PAL_CALL_RETURN"]:
260 for i
in range(TypedefStart
, TypedefEnd
+1):
263 # save all lines trimmed
265 f
= open (Target
,'w')
267 EdkLogger
.error("Trim", FILE_OPEN_FAILURE
, ExtraData
=Target
)
271 ## Read the content ASL file, including ASL included, recursively
273 # @param Source File to be read
274 # @param Indent Spaces before the Include() statement
275 # @param IncludePathList The list of external include file
276 # @param LocalSearchPath If LocalSearchPath is specified, this path will be searched
277 # first for the included file; otherwise, only the path specified
278 # in the IncludePathList will be searched.
280 def DoInclude(Source
, Indent
='', IncludePathList
=[], LocalSearchPath
=None):
285 # Search LocalSearchPath first if it is specified.
288 SearchPathList
= [LocalSearchPath
] + IncludePathList
290 SearchPathList
= IncludePathList
292 for IncludePath
in SearchPathList
:
293 IncludeFile
= os
.path
.join(IncludePath
, Source
)
294 if os
.path
.isfile(IncludeFile
):
295 F
= open(IncludeFile
, "r")
298 EdkLogger
.error("Trim", "Failed to find include file %s" % Source
)
300 EdkLogger
.error("Trim", FILE_OPEN_FAILURE
, ExtraData
=Source
)
303 # avoid A "include" B and B "include" A
304 IncludeFile
= os
.path
.abspath(os
.path
.normpath(IncludeFile
))
305 if IncludeFile
in gIncludedAslFile
:
306 EdkLogger
.warn("Trim", "Circular include",
307 ExtraData
= "%s -> %s" % (" -> ".join(gIncludedAslFile
), IncludeFile
))
309 gIncludedAslFile
.append(IncludeFile
)
312 LocalSearchPath
= None
313 Result
= gAslIncludePattern
.findall(Line
)
315 Result
= gAslCIncludePattern
.findall(Line
)
316 if len(Result
) == 0 or os
.path
.splitext(Result
[0][1])[1].lower() not in [".asl", ".asi"]:
317 NewFileContent
.append("%s%s" % (Indent
, Line
))
320 # We should first search the local directory if current file are using pattern #include "XXX"
322 if Result
[0][2] == '"':
323 LocalSearchPath
= os
.path
.dirname(IncludeFile
)
324 CurrentIndent
= Indent
+ Result
[0][0]
325 IncludedFile
= Result
[0][1]
326 NewFileContent
.extend(DoInclude(IncludedFile
, CurrentIndent
, IncludePathList
, LocalSearchPath
))
327 NewFileContent
.append("\n")
329 gIncludedAslFile
.pop()
332 return NewFileContent
337 # Replace ASL include statement with the content the included file
339 # @param Source File to be trimmed
340 # @param Target File to store the trimmed content
341 # @param IncludePathFile The file to log the external include path
343 def TrimAslFile(Source
, Target
, IncludePathFile
):
344 CreateDirectory(os
.path
.dirname(Target
))
346 SourceDir
= os
.path
.dirname(Source
)
351 # Add source directory as the first search directory
353 IncludePathList
= [SourceDir
]
356 # If additional include path file is specified, append them all
357 # to the search directory list.
362 for Line
in open(IncludePathFile
,'r'):
364 if Line
.startswith("/I") or Line
.startswith ("-I"):
365 IncludePathList
.append(Line
[2:].strip())
367 EdkLogger
.warn("Trim", "Invalid include line in include list file.", IncludePathFile
, LineNum
)
369 EdkLogger
.error("Trim", FILE_OPEN_FAILURE
, ExtraData
=IncludePathFile
)
371 Lines
= DoInclude(Source
, '', IncludePathList
)
374 # Undef MIN and MAX to avoid collision in ASL source code
376 Lines
.insert(0, "#undef MIN\n#undef MAX\n")
378 # save all lines trimmed
380 f
= open (Target
,'w')
382 EdkLogger
.error("Trim", FILE_OPEN_FAILURE
, ExtraData
=Target
)
387 ## Trim EDK source code file(s)
390 # @param Source File or directory to be trimmed
391 # @param Target File or directory to store the trimmed content
393 def TrimR8Sources(Source
, Target
):
394 if os
.path
.isdir(Source
):
395 for CurrentDir
, Dirs
, Files
in os
.walk(Source
):
401 for FileName
in Files
:
402 Dummy
, Ext
= os
.path
.splitext(FileName
)
403 if Ext
.upper() not in ['.C', '.H']: continue
404 if Target
== None or Target
== '':
406 os
.path
.join(CurrentDir
, FileName
),
407 os
.path
.join(CurrentDir
, FileName
)
411 os
.path
.join(CurrentDir
, FileName
),
412 os
.path
.join(Target
, CurrentDir
[len(Source
)+1:], FileName
)
415 TrimR8SourceCode(Source
, Target
)
417 ## Trim one EDK source code file
419 # Do following replacement:
421 # (**PeiServices\).PciCfg = <*>;
423 # STATIC EFI_PEI_PPI_DESCRIPTOR gEcpPeiPciCfgPpiList = {
424 # (EFI_PEI_PPI_DESCRIPTOR_PPI | EFI_PEI_PPI_DESCRIPTOR_TERMINATE_LIST),
425 # &gEcpPeiPciCfgPpiGuid,
428 # (**PeiServices).InstallPpi (PeiServices, &gEcpPeiPciCfgPpiList);
431 # => PeiLibPciCfgModify (<*>)
433 # gRT->ReportStatusCode (<*>)
434 # => EfiLibReportStatusCode (<*>)
436 # #include <LoadFile\.h>
437 # => #include <FvLoadFile.h>
439 # CreateEvent (EFI_EVENT_SIGNAL_READY_TO_BOOT, <*>)
440 # => EfiCreateEventReadyToBoot (<*>)
442 # CreateEvent (EFI_EVENT_SIGNAL_LEGACY_BOOT, <*>)
443 # => EfiCreateEventLegacyBoot (<*>)
445 # @param Source File to be trimmed
446 # @param Target File to store the trimmed content
448 def TrimR8SourceCode(Source
, Target
):
449 EdkLogger
.verbose("\t%s -> %s" % (Source
, Target
))
450 CreateDirectory(os
.path
.dirname(Target
))
453 f
= open (Source
,'rb')
455 EdkLogger
.error("Trim", FILE_OPEN_FAILURE
, ExtraData
=Source
)
461 for Re
,Repl
in gImportCodePatterns
:
463 NewLines
= Re
.sub(Repl
, Lines
)
465 NewLines
= Re
.sub(Repl
, NewLines
)
467 # save all lines if trimmed
468 if Source
== Target
and NewLines
== Lines
:
472 f
= open (Target
,'wb')
474 EdkLogger
.error("Trim", FILE_OPEN_FAILURE
, ExtraData
=Target
)
479 ## Parse command line options
481 # Using standard Python module optparse to parse command line option of this tool.
483 # @retval Options A optparse.Values object containing the parsed options
484 # @retval InputFile Path of file to be trimmed
488 make_option("-s", "--source-code", dest
="FileType", const
="SourceCode", action
="store_const",
489 help="The input file is preprocessed source code, including C or assembly code"),
490 make_option("-r", "--vfr-file", dest
="FileType", const
="Vfr", action
="store_const",
491 help="The input file is preprocessed VFR file"),
492 make_option("-a", "--asl-file", dest
="FileType", const
="Asl", action
="store_const",
493 help="The input file is ASL file"),
494 make_option("-8", "--r8-source-code", dest
="FileType", const
="R8SourceCode", action
="store_const",
495 help="The input file is source code for R8 to be trimmed for ECP"),
497 make_option("-c", "--convert-hex", dest
="ConvertHex", action
="store_true",
498 help="Convert standard hex format (0xabcd) to MASM format (abcdh)"),
500 make_option("-l", "--trim-long", dest
="TrimLong", action
="store_true",
501 help="Remove postfix of long number"),
502 make_option("-i", "--include-path-file", dest
="IncludePathFile",
503 help="The input file is include path list to search for ASL include file"),
504 make_option("-o", "--output", dest
="OutputFile",
505 help="File to store the trimmed content"),
506 make_option("-v", "--verbose", dest
="LogLevel", action
="store_const", const
=EdkLogger
.VERBOSE
,
507 help="Run verbosely"),
508 make_option("-d", "--debug", dest
="LogLevel", type="int",
509 help="Run with debug information"),
510 make_option("-q", "--quiet", dest
="LogLevel", action
="store_const", const
=EdkLogger
.QUIET
,
512 make_option("-?", action
="help", help="show this help message and exit"),
515 # use clearer usage to override default usage message
516 UsageString
= "%prog [-s|-r|-a] [-c] [-v|-d <debug_level>|-q] [-i <include_path_file>] [-o <output_file>] <input_file>"
518 Parser
= OptionParser(description
=__copyright__
, version
=__version__
, option_list
=OptionList
, usage
=UsageString
)
519 Parser
.set_defaults(FileType
="Vfr")
520 Parser
.set_defaults(ConvertHex
=False)
521 Parser
.set_defaults(LogLevel
=EdkLogger
.INFO
)
523 Options
, Args
= Parser
.parse_args()
527 EdkLogger
.error("Trim", OPTION_MISSING
, ExtraData
=Parser
.get_usage())
529 EdkLogger
.error("Trim", OPTION_NOT_SUPPORTED
, ExtraData
=Parser
.get_usage())
532 return Options
, InputFile
536 # This method mainly dispatch specific methods per the command line options.
537 # If no error found, return zero value so the caller of this tool can know
538 # if it's executed successfully or not.
540 # @retval 0 Tool was successful
541 # @retval 1 Tool failed
545 EdkLogger
.Initialize()
546 CommandOptions
, InputFile
= Options()
547 if CommandOptions
.LogLevel
< EdkLogger
.DEBUG_9
:
548 EdkLogger
.SetLevel(CommandOptions
.LogLevel
+ 1)
550 EdkLogger
.SetLevel(CommandOptions
.LogLevel
)
551 except FatalError
, X
:
555 if CommandOptions
.FileType
== "Vfr":
556 if CommandOptions
.OutputFile
== None:
557 CommandOptions
.OutputFile
= os
.path
.splitext(InputFile
)[0] + '.iii'
558 TrimPreprocessedVfr(InputFile
, CommandOptions
.OutputFile
)
559 elif CommandOptions
.FileType
== "Asl":
560 if CommandOptions
.OutputFile
== None:
561 CommandOptions
.OutputFile
= os
.path
.splitext(InputFile
)[0] + '.iii'
562 TrimAslFile(InputFile
, CommandOptions
.OutputFile
, CommandOptions
.IncludePathFile
)
563 elif CommandOptions
.FileType
== "R8SourceCode":
564 TrimR8Sources(InputFile
, CommandOptions
.OutputFile
)
566 if CommandOptions
.OutputFile
== None:
567 CommandOptions
.OutputFile
= os
.path
.splitext(InputFile
)[0] + '.iii'
568 TrimPreprocessedFile(InputFile
, CommandOptions
.OutputFile
, CommandOptions
.ConvertHex
, CommandOptions
.TrimLong
)
569 except FatalError
, X
:
572 if CommandOptions
!= None and CommandOptions
.LogLevel
<= EdkLogger
.DEBUG_9
:
573 EdkLogger
.quiet("(Python %s on %s) " % (platform
.python_version(), sys
.platform
) + traceback
.format_exc())
581 "Unknown fatal error when trimming [%s]" % InputFile
,
582 ExtraData
="\n(Please send email to edk2-buildtools-devel@lists.sourceforge.net for help, attaching following call stack trace!)\n",
585 EdkLogger
.quiet("(Python %s on %s) " % (platform
.python_version(), sys
.platform
) + traceback
.format_exc())
590 if __name__
== '__main__':
592 ## 0-127 is a safe return range, and 1 is a standard default error
593 if r
< 0 or r
> 127: r
= 1