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