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