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