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