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