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