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