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