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