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