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