]> git.proxmox.com Git - mirror_edk2.git/blob - BaseTools/Source/Python/Trim/Trim.py
BaseTools: Generate dependent files for ASL and ASM files
[mirror_edk2.git] / BaseTools / Source / Python / Trim / Trim.py
1 ## @file
2 # Trim files preprocessed by compiler
3 #
4 # Copyright (c) 2007 - 2018, Intel Corporation. All rights reserved.<BR>
5 # SPDX-License-Identifier: BSD-2-Clause-Patent
6 #
7
8 ##
9 # Import Modules
10 #
11 import Common.LongFilePathOs as os
12 import sys
13 import re
14 from io import BytesIO
15 import codecs
16 from optparse import OptionParser
17 from optparse import make_option
18 from Common.BuildToolError import *
19 from Common.Misc import *
20 from Common.DataType import *
21 from Common.BuildVersion import gBUILD_VERSION
22 import Common.EdkLogger as EdkLogger
23 from Common.LongFilePathSupport import OpenLongFilePath as open
24
25 # Version and Copyright
26 __version_number__ = ("0.10" + " " + gBUILD_VERSION)
27 __version__ = "%prog Version " + __version_number__
28 __copyright__ = "Copyright (c) 2007-2018, Intel Corporation. All rights reserved."
29
30 ## Regular expression for matching Line Control directive like "#line xxx"
31 gLineControlDirective = re.compile('^\s*#(?:line)?\s+([0-9]+)\s+"*([^"]*)"')
32 ## Regular expression for matching "typedef struct"
33 gTypedefPattern = re.compile("^\s*typedef\s+struct(\s+\w+)?\s*[{]*$", re.MULTILINE)
34 ## Regular expression for matching "#pragma pack"
35 gPragmaPattern = re.compile("^\s*#pragma\s+pack", re.MULTILINE)
36 ## Regular expression for matching "typedef"
37 gTypedef_SinglePattern = re.compile("^\s*typedef", re.MULTILINE)
38 ## Regular expression for matching "typedef struct, typedef union, struct, union"
39 gTypedef_MulPattern = re.compile("^\s*(typedef)?\s+(struct|union)(\s+\w+)?\s*[{]*$", re.MULTILINE)
40
41 #
42 # The following number pattern match will only match if following criteria is met:
43 # There is leading non-(alphanumeric or _) character, and no following alphanumeric or _
44 # as the pattern is greedily match, so it is ok for the gDecNumberPattern or gHexNumberPattern to grab the maximum match
45 #
46 ## Regular expression for matching HEX number
47 gHexNumberPattern = re.compile("(?<=[^a-zA-Z0-9_])(0[xX])([0-9a-fA-F]+)(U(?=$|[^a-zA-Z0-9_]))?")
48 ## Regular expression for matching decimal number with 'U' postfix
49 gDecNumberPattern = re.compile("(?<=[^a-zA-Z0-9_])([0-9]+)U(?=$|[^a-zA-Z0-9_])")
50 ## Regular expression for matching constant with 'ULL' 'LL' postfix
51 gLongNumberPattern = re.compile("(?<=[^a-zA-Z0-9_])(0[xX][0-9a-fA-F]+|[0-9]+)U?LL(?=$|[^a-zA-Z0-9_])")
52
53 ## Regular expression for matching "Include ()" in asl file
54 gAslIncludePattern = re.compile("^(\s*)[iI]nclude\s*\(\"?([^\"\(\)]+)\"\)", re.MULTILINE)
55 ## Regular expression for matching C style #include "XXX.asl" in asl file
56 gAslCIncludePattern = re.compile(r'^(\s*)#include\s*[<"]\s*([-\\/\w.]+)\s*([>"])', re.MULTILINE)
57 ## Patterns used to convert EDK conventions to EDK2 ECP conventions
58
59 ## Regular expression for finding header file inclusions
60 gIncludePattern = re.compile(r"^[ \t]*[%]?[ \t]*include(?:[ \t]*(?:\\(?:\r\n|\r|\n))*[ \t]*)*(?:\(?[\"<]?[ \t]*)([-\w.\\/() \t]+)(?:[ \t]*[\">]?\)?)", re.MULTILINE | re.UNICODE | re.IGNORECASE)
61
62
63 ## file cache to avoid circular include in ASL file
64 gIncludedAslFile = []
65
66 ## Trim preprocessed source code
67 #
68 # Remove extra content made by preprocessor. The preprocessor must enable the
69 # line number generation option when preprocessing.
70 #
71 # @param Source File to be trimmed
72 # @param Target File to store the trimmed content
73 # @param Convert If True, convert standard HEX format to MASM format
74 #
75 def TrimPreprocessedFile(Source, Target, ConvertHex, TrimLong):
76 CreateDirectory(os.path.dirname(Target))
77 try:
78 with open(Source, "r") as File:
79 Lines = File.readlines()
80 except IOError:
81 EdkLogger.error("Trim", FILE_OPEN_FAILURE, ExtraData=Source)
82 except:
83 EdkLogger.error("Trim", AUTOGEN_ERROR, "TrimPreprocessedFile: Error while processing file", File=Source)
84
85 PreprocessedFile = ""
86 InjectedFile = ""
87 LineIndexOfOriginalFile = None
88 NewLines = []
89 LineControlDirectiveFound = False
90 for Index in range(len(Lines)):
91 Line = Lines[Index]
92 #
93 # Find out the name of files injected by preprocessor from the lines
94 # with Line Control directive
95 #
96 MatchList = gLineControlDirective.findall(Line)
97 if MatchList != []:
98 MatchList = MatchList[0]
99 if len(MatchList) == 2:
100 LineNumber = int(MatchList[0], 0)
101 InjectedFile = MatchList[1]
102 InjectedFile = os.path.normpath(InjectedFile)
103 InjectedFile = os.path.normcase(InjectedFile)
104 # The first injected file must be the preprocessed file itself
105 if PreprocessedFile == "":
106 PreprocessedFile = InjectedFile
107 LineControlDirectiveFound = True
108 continue
109 elif PreprocessedFile == "" or InjectedFile != PreprocessedFile:
110 continue
111
112 if LineIndexOfOriginalFile is None:
113 #
114 # Any non-empty lines must be from original preprocessed file.
115 # And this must be the first one.
116 #
117 LineIndexOfOriginalFile = Index
118 EdkLogger.verbose("Found original file content starting from line %d"
119 % (LineIndexOfOriginalFile + 1))
120
121 if TrimLong:
122 Line = gLongNumberPattern.sub(r"\1", Line)
123 # convert HEX number format if indicated
124 if ConvertHex:
125 Line = gHexNumberPattern.sub(r"0\2h", Line)
126 else:
127 Line = gHexNumberPattern.sub(r"\1\2", Line)
128
129 # convert Decimal number format
130 Line = gDecNumberPattern.sub(r"\1", Line)
131
132 if LineNumber is not None:
133 EdkLogger.verbose("Got line directive: line=%d" % LineNumber)
134 # in case preprocessor removed some lines, like blank or comment lines
135 if LineNumber <= len(NewLines):
136 # possible?
137 NewLines[LineNumber - 1] = Line
138 else:
139 if LineNumber > (len(NewLines) + 1):
140 for LineIndex in range(len(NewLines), LineNumber-1):
141 NewLines.append(TAB_LINE_BREAK)
142 NewLines.append(Line)
143 LineNumber = None
144 EdkLogger.verbose("Now we have lines: %d" % len(NewLines))
145 else:
146 NewLines.append(Line)
147
148 # in case there's no line directive or linemarker found
149 if (not LineControlDirectiveFound) and NewLines == []:
150 MulPatternFlag = False
151 SinglePatternFlag = False
152 Brace = 0
153 for Index in range(len(Lines)):
154 Line = Lines[Index]
155 if MulPatternFlag == False and gTypedef_MulPattern.search(Line) is None:
156 if SinglePatternFlag == False and gTypedef_SinglePattern.search(Line) is None:
157 # remove "#pragram pack" directive
158 if gPragmaPattern.search(Line) is None:
159 NewLines.append(Line)
160 continue
161 elif SinglePatternFlag == False:
162 SinglePatternFlag = True
163 if Line.find(";") >= 0:
164 SinglePatternFlag = False
165 elif MulPatternFlag == False:
166 # found "typedef struct, typedef union, union, struct", keep its position and set a flag
167 MulPatternFlag = True
168
169 # match { and } to find the end of typedef definition
170 if Line.find("{") >= 0:
171 Brace += 1
172 elif Line.find("}") >= 0:
173 Brace -= 1
174
175 # "typedef struct, typedef union, union, struct" must end with a ";"
176 if Brace == 0 and Line.find(";") >= 0:
177 MulPatternFlag = False
178
179 # save to file
180 try:
181 with open(Target, 'w') as File:
182 File.writelines(NewLines)
183 except:
184 EdkLogger.error("Trim", FILE_OPEN_FAILURE, ExtraData=Target)
185
186 ## Trim preprocessed VFR file
187 #
188 # Remove extra content made by preprocessor. The preprocessor doesn't need to
189 # enable line number generation option when preprocessing.
190 #
191 # @param Source File to be trimmed
192 # @param Target File to store the trimmed content
193 #
194 def TrimPreprocessedVfr(Source, Target):
195 CreateDirectory(os.path.dirname(Target))
196
197 try:
198 with open(Source, "r") as File:
199 Lines = File.readlines()
200 except:
201 EdkLogger.error("Trim", FILE_OPEN_FAILURE, ExtraData=Source)
202 # read whole file
203
204 FoundTypedef = False
205 Brace = 0
206 TypedefStart = 0
207 TypedefEnd = 0
208 for Index in range(len(Lines)):
209 Line = Lines[Index]
210 # don't trim the lines from "formset" definition to the end of file
211 if Line.strip() == 'formset':
212 break
213
214 if FoundTypedef == False and (Line.find('#line') == 0 or Line.find('# ') == 0):
215 # empty the line number directive if it's not aomong "typedef struct"
216 Lines[Index] = "\n"
217 continue
218
219 if FoundTypedef == False and gTypedefPattern.search(Line) is None:
220 # keep "#pragram pack" directive
221 if gPragmaPattern.search(Line) is None:
222 Lines[Index] = "\n"
223 continue
224 elif FoundTypedef == False:
225 # found "typedef struct", keept its position and set a flag
226 FoundTypedef = True
227 TypedefStart = Index
228
229 # match { and } to find the end of typedef definition
230 if Line.find("{") >= 0:
231 Brace += 1
232 elif Line.find("}") >= 0:
233 Brace -= 1
234
235 # "typedef struct" must end with a ";"
236 if Brace == 0 and Line.find(";") >= 0:
237 FoundTypedef = False
238 TypedefEnd = Index
239 # keep all "typedef struct" except to GUID, EFI_PLABEL and PAL_CALL_RETURN
240 if Line.strip("} ;\r\n") in [TAB_GUID, "EFI_PLABEL", "PAL_CALL_RETURN"]:
241 for i in range(TypedefStart, TypedefEnd+1):
242 Lines[i] = "\n"
243
244 # save all lines trimmed
245 try:
246 with open(Target, 'w') as File:
247 File.writelines(Lines)
248 except:
249 EdkLogger.error("Trim", FILE_OPEN_FAILURE, ExtraData=Target)
250
251 ## Read the content ASL file, including ASL included, recursively
252 #
253 # @param Source File to be read
254 # @param Indent Spaces before the Include() statement
255 # @param IncludePathList The list of external include file
256 # @param LocalSearchPath If LocalSearchPath is specified, this path will be searched
257 # first for the included file; otherwise, only the path specified
258 # in the IncludePathList will be searched.
259 #
260 def DoInclude(Source, Indent='', IncludePathList=[], LocalSearchPath=None, IncludeFileList = None, filetype=None):
261 NewFileContent = []
262 if IncludeFileList is None:
263 IncludeFileList = []
264 try:
265 #
266 # Search LocalSearchPath first if it is specified.
267 #
268 if LocalSearchPath:
269 SearchPathList = [LocalSearchPath] + IncludePathList
270 else:
271 SearchPathList = IncludePathList
272
273 for IncludePath in SearchPathList:
274 IncludeFile = os.path.join(IncludePath, Source)
275 if os.path.isfile(IncludeFile):
276 try:
277 with open(IncludeFile, "r") as File:
278 F = File.readlines()
279 except:
280 with codecs.open(IncludeFile, "r", encoding='utf-8') as File:
281 F = File.readlines()
282 break
283 else:
284 EdkLogger.error("Trim", "Failed to find include file %s" % Source)
285 except:
286 EdkLogger.error("Trim", FILE_OPEN_FAILURE, ExtraData=Source)
287
288
289 # avoid A "include" B and B "include" A
290 IncludeFile = os.path.abspath(os.path.normpath(IncludeFile))
291 if IncludeFile in gIncludedAslFile:
292 EdkLogger.warn("Trim", "Circular include",
293 ExtraData= "%s -> %s" % (" -> ".join(gIncludedAslFile), IncludeFile))
294 return []
295 gIncludedAslFile.append(IncludeFile)
296 IncludeFileList.append(IncludeFile.strip())
297 for Line in F:
298 LocalSearchPath = None
299 if filetype == "ASL":
300 Result = gAslIncludePattern.findall(Line)
301 if len(Result) == 0:
302 Result = gAslCIncludePattern.findall(Line)
303 if len(Result) == 0 or os.path.splitext(Result[0][1])[1].lower() not in [".asl", ".asi"]:
304 NewFileContent.append("%s%s" % (Indent, Line))
305 continue
306 #
307 # We should first search the local directory if current file are using pattern #include "XXX"
308 #
309 if Result[0][2] == '"':
310 LocalSearchPath = os.path.dirname(IncludeFile)
311 CurrentIndent = Indent + Result[0][0]
312 IncludedFile = Result[0][1]
313 NewFileContent.extend(DoInclude(IncludedFile, CurrentIndent, IncludePathList, LocalSearchPath,IncludeFileList,filetype))
314 NewFileContent.append("\n")
315 elif filetype == "ASM":
316 Result = gIncludePattern.findall(Line)
317 if len(Result) == 0:
318 NewFileContent.append("%s%s" % (Indent, Line))
319 continue
320
321 IncludedFile = Result[0]
322
323 IncludedFile = IncludedFile.strip()
324 IncludedFile = os.path.normpath(IncludedFile)
325 NewFileContent.extend(DoInclude(IncludedFile, '', IncludePathList, LocalSearchPath,IncludeFileList,filetype))
326 NewFileContent.append("\n")
327
328 gIncludedAslFile.pop()
329
330 return NewFileContent
331
332
333 ## Trim ASL file
334 #
335 # Replace ASL include statement with the content the included file
336 #
337 # @param Source File to be trimmed
338 # @param Target File to store the trimmed content
339 # @param IncludePathFile The file to log the external include path
340 #
341 def TrimAslFile(Source, Target, IncludePathFile,AslDeps = False):
342 CreateDirectory(os.path.dirname(Target))
343
344 SourceDir = os.path.dirname(Source)
345 if SourceDir == '':
346 SourceDir = '.'
347
348 #
349 # Add source directory as the first search directory
350 #
351 IncludePathList = [SourceDir]
352
353 #
354 # If additional include path file is specified, append them all
355 # to the search directory list.
356 #
357 if IncludePathFile:
358 try:
359 LineNum = 0
360 with open(IncludePathFile, 'r') as File:
361 FileLines = File.readlines()
362 for Line in FileLines:
363 LineNum += 1
364 if Line.startswith("/I") or Line.startswith ("-I"):
365 IncludePathList.append(Line[2:].strip())
366 else:
367 EdkLogger.warn("Trim", "Invalid include line in include list file.", IncludePathFile, LineNum)
368 except:
369 EdkLogger.error("Trim", FILE_OPEN_FAILURE, ExtraData=IncludePathFile)
370 AslIncludes = []
371 Lines = DoInclude(Source, '', IncludePathList,IncludeFileList=AslIncludes,filetype='ASL')
372 AslIncludes = [item for item in AslIncludes if item !=Source]
373 if AslDeps and AslIncludes:
374 SaveFileOnChange(os.path.join(os.path.dirname(Target),os.path.basename(Source))+".trim.deps", " \\\n".join([Source+":"] +AslIncludes),False)
375
376 #
377 # Undef MIN and MAX to avoid collision in ASL source code
378 #
379 Lines.insert(0, "#undef MIN\n#undef MAX\n")
380
381 # save all lines trimmed
382 try:
383 with open(Target, 'w') as File:
384 File.writelines(Lines)
385 except:
386 EdkLogger.error("Trim", FILE_OPEN_FAILURE, ExtraData=Target)
387
388 ## Trim ASM file
389 #
390 # Output ASM include statement with the content the included file
391 #
392 # @param Source File to be trimmed
393 # @param Target File to store the trimmed content
394 # @param IncludePathFile The file to log the external include path
395 #
396 def TrimAsmFile(Source, Target, IncludePathFile):
397 CreateDirectory(os.path.dirname(Target))
398
399 SourceDir = os.path.dirname(Source)
400 if SourceDir == '':
401 SourceDir = '.'
402
403 #
404 # Add source directory as the first search directory
405 #
406 IncludePathList = [SourceDir]
407 #
408 # If additional include path file is specified, append them all
409 # to the search directory list.
410 #
411 if IncludePathFile:
412 try:
413 LineNum = 0
414 with open(IncludePathFile, 'r') as File:
415 FileLines = File.readlines()
416 for Line in FileLines:
417 LineNum += 1
418 if Line.startswith("/I") or Line.startswith ("-I"):
419 IncludePathList.append(Line[2:].strip())
420 else:
421 EdkLogger.warn("Trim", "Invalid include line in include list file.", IncludePathFile, LineNum)
422 except:
423 EdkLogger.error("Trim", FILE_OPEN_FAILURE, ExtraData=IncludePathFile)
424 AsmIncludes = []
425 Lines = DoInclude(Source, '', IncludePathList,IncludeFileList=AsmIncludes,filetype='ASM')
426 AsmIncludes = [item for item in AsmIncludes if item != Source]
427 if AsmIncludes:
428 SaveFileOnChange(os.path.join(os.path.dirname(Target),os.path.basename(Source))+".trim.deps", " \\\n".join([Source+":"] +AsmIncludes),False)
429 # save all lines trimmed
430 try:
431 with open(Target, 'w') as File:
432 File.writelines(Lines)
433 except:
434 EdkLogger.error("Trim", FILE_OPEN_FAILURE, ExtraData=Target)
435
436 def GenerateVfrBinSec(ModuleName, DebugDir, OutputFile):
437 VfrNameList = []
438 if os.path.isdir(DebugDir):
439 for CurrentDir, Dirs, Files in os.walk(DebugDir):
440 for FileName in Files:
441 Name, Ext = os.path.splitext(FileName)
442 if Ext == '.c' and Name != 'AutoGen':
443 VfrNameList.append (Name + 'Bin')
444
445 VfrNameList.append (ModuleName + 'Strings')
446
447 EfiFileName = os.path.join(DebugDir, ModuleName + '.efi')
448 MapFileName = os.path.join(DebugDir, ModuleName + '.map')
449 VfrUniOffsetList = GetVariableOffset(MapFileName, EfiFileName, VfrNameList)
450
451 if not VfrUniOffsetList:
452 return
453
454 try:
455 fInputfile = open(OutputFile, "wb+")
456 except:
457 EdkLogger.error("Trim", FILE_OPEN_FAILURE, "File open failed for %s" %OutputFile, None)
458
459 # Use a instance of BytesIO to cache data
460 fStringIO = BytesIO()
461
462 for Item in VfrUniOffsetList:
463 if (Item[0].find("Strings") != -1):
464 #
465 # UNI offset in image.
466 # GUID + Offset
467 # { 0x8913c5e0, 0x33f6, 0x4d86, { 0x9b, 0xf1, 0x43, 0xef, 0x89, 0xfc, 0x6, 0x66 } }
468 #
469 UniGuid = b'\xe0\xc5\x13\x89\xf63\x86M\x9b\xf1C\xef\x89\xfc\x06f'
470 fStringIO.write(UniGuid)
471 UniValue = pack ('Q', int (Item[1], 16))
472 fStringIO.write (UniValue)
473 else:
474 #
475 # VFR binary offset in image.
476 # GUID + Offset
477 # { 0xd0bc7cb4, 0x6a47, 0x495f, { 0xaa, 0x11, 0x71, 0x7, 0x46, 0xda, 0x6, 0xa2 } };
478 #
479 VfrGuid = b'\xb4|\xbc\xd0Gj_I\xaa\x11q\x07F\xda\x06\xa2'
480 fStringIO.write(VfrGuid)
481 type (Item[1])
482 VfrValue = pack ('Q', int (Item[1], 16))
483 fStringIO.write (VfrValue)
484
485 #
486 # write data into file.
487 #
488 try :
489 fInputfile.write (fStringIO.getvalue())
490 except:
491 EdkLogger.error("Trim", FILE_WRITE_FAILURE, "Write data to file %s failed, please check whether the file been locked or using by other applications." %OutputFile, None)
492
493 fStringIO.close ()
494 fInputfile.close ()
495
496
497 ## Parse command line options
498 #
499 # Using standard Python module optparse to parse command line option of this tool.
500 #
501 # @retval Options A optparse.Values object containing the parsed options
502 # @retval InputFile Path of file to be trimmed
503 #
504 def Options():
505 OptionList = [
506 make_option("-s", "--source-code", dest="FileType", const="SourceCode", action="store_const",
507 help="The input file is preprocessed source code, including C or assembly code"),
508 make_option("-r", "--vfr-file", dest="FileType", const="Vfr", action="store_const",
509 help="The input file is preprocessed VFR file"),
510 make_option("--Vfr-Uni-Offset", dest="FileType", const="VfrOffsetBin", action="store_const",
511 help="The input file is EFI image"),
512 make_option("--asl-deps", dest="AslDeps", const="True", action="store_const",
513 help="Generate Asl dependent files."),
514 make_option("-a", "--asl-file", dest="FileType", const="Asl", action="store_const",
515 help="The input file is ASL file"),
516 make_option( "--asm-file", dest="FileType", const="Asm", action="store_const",
517 help="The input file is asm file"),
518 make_option("-c", "--convert-hex", dest="ConvertHex", action="store_true",
519 help="Convert standard hex format (0xabcd) to MASM format (abcdh)"),
520
521 make_option("-l", "--trim-long", dest="TrimLong", action="store_true",
522 help="Remove postfix of long number"),
523 make_option("-i", "--include-path-file", dest="IncludePathFile",
524 help="The input file is include path list to search for ASL include file"),
525 make_option("-o", "--output", dest="OutputFile",
526 help="File to store the trimmed content"),
527 make_option("--ModuleName", dest="ModuleName", help="The module's BASE_NAME"),
528 make_option("--DebugDir", dest="DebugDir",
529 help="Debug Output directory to store the output files"),
530 make_option("-v", "--verbose", dest="LogLevel", action="store_const", const=EdkLogger.VERBOSE,
531 help="Run verbosely"),
532 make_option("-d", "--debug", dest="LogLevel", type="int",
533 help="Run with debug information"),
534 make_option("-q", "--quiet", dest="LogLevel", action="store_const", const=EdkLogger.QUIET,
535 help="Run quietly"),
536 make_option("-?", action="help", help="show this help message and exit"),
537 ]
538
539 # use clearer usage to override default usage message
540 UsageString = "%prog [-s|-r|-a|--Vfr-Uni-Offset] [-c] [-v|-d <debug_level>|-q] [-i <include_path_file>] [-o <output_file>] [--ModuleName <ModuleName>] [--DebugDir <DebugDir>] [<input_file>]"
541
542 Parser = OptionParser(description=__copyright__, version=__version__, option_list=OptionList, usage=UsageString)
543 Parser.set_defaults(FileType="Vfr")
544 Parser.set_defaults(ConvertHex=False)
545 Parser.set_defaults(LogLevel=EdkLogger.INFO)
546
547 Options, Args = Parser.parse_args()
548
549 # error check
550 if Options.FileType == 'VfrOffsetBin':
551 if len(Args) == 0:
552 return Options, ''
553 elif len(Args) > 1:
554 EdkLogger.error("Trim", OPTION_NOT_SUPPORTED, ExtraData=Parser.get_usage())
555 if len(Args) == 0:
556 EdkLogger.error("Trim", OPTION_MISSING, ExtraData=Parser.get_usage())
557 if len(Args) > 1:
558 EdkLogger.error("Trim", OPTION_NOT_SUPPORTED, ExtraData=Parser.get_usage())
559
560 InputFile = Args[0]
561 return Options, InputFile
562
563 ## Entrance method
564 #
565 # This method mainly dispatch specific methods per the command line options.
566 # If no error found, return zero value so the caller of this tool can know
567 # if it's executed successfully or not.
568 #
569 # @retval 0 Tool was successful
570 # @retval 1 Tool failed
571 #
572 def Main():
573 try:
574 EdkLogger.Initialize()
575 CommandOptions, InputFile = Options()
576 if CommandOptions.LogLevel < EdkLogger.DEBUG_9:
577 EdkLogger.SetLevel(CommandOptions.LogLevel + 1)
578 else:
579 EdkLogger.SetLevel(CommandOptions.LogLevel)
580 except FatalError as X:
581 return 1
582
583 try:
584 if CommandOptions.FileType == "Vfr":
585 if CommandOptions.OutputFile is None:
586 CommandOptions.OutputFile = os.path.splitext(InputFile)[0] + '.iii'
587 TrimPreprocessedVfr(InputFile, CommandOptions.OutputFile)
588 elif CommandOptions.FileType == "Asl":
589 if CommandOptions.OutputFile is None:
590 CommandOptions.OutputFile = os.path.splitext(InputFile)[0] + '.iii'
591 TrimAslFile(InputFile, CommandOptions.OutputFile, CommandOptions.IncludePathFile,CommandOptions.AslDeps)
592 elif CommandOptions.FileType == "VfrOffsetBin":
593 GenerateVfrBinSec(CommandOptions.ModuleName, CommandOptions.DebugDir, CommandOptions.OutputFile)
594 elif CommandOptions.FileType == "Asm":
595 TrimAsmFile(InputFile, CommandOptions.OutputFile, CommandOptions.IncludePathFile)
596 else :
597 if CommandOptions.OutputFile is None:
598 CommandOptions.OutputFile = os.path.splitext(InputFile)[0] + '.iii'
599 TrimPreprocessedFile(InputFile, CommandOptions.OutputFile, CommandOptions.ConvertHex, CommandOptions.TrimLong)
600 except FatalError as X:
601 import platform
602 import traceback
603 if CommandOptions is not None and CommandOptions.LogLevel <= EdkLogger.DEBUG_9:
604 EdkLogger.quiet("(Python %s on %s) " % (platform.python_version(), sys.platform) + traceback.format_exc())
605 return 1
606 except:
607 import traceback
608 import platform
609 EdkLogger.error(
610 "\nTrim",
611 CODE_ERROR,
612 "Unknown fatal error when trimming [%s]" % InputFile,
613 ExtraData="\n(Please send email to %s for help, attaching following call stack trace!)\n" % MSG_EDKII_MAIL_ADDR,
614 RaiseError=False
615 )
616 EdkLogger.quiet("(Python %s on %s) " % (platform.python_version(), sys.platform) + traceback.format_exc())
617 return 1
618
619 return 0
620
621 if __name__ == '__main__':
622 r = Main()
623 ## 0-127 is a safe return range, and 1 is a standard default error
624 if r < 0 or r > 127: r = 1
625 sys.exit(r)
626