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