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