]> git.proxmox.com Git - mirror_edk2.git/blame - BaseTools/Source/Python/GenFds/GenFds.py
BaseTools: Rsa2048Sha256Sign add new option to support Monotonic count
[mirror_edk2.git] / BaseTools / Source / Python / GenFds / GenFds.py
CommitLineData
f51461c8
LG
1## @file\r
2# generate flash image\r
3#\r
3a0f8bde 4# Copyright (c) 2007 - 2016, Intel Corporation. All rights reserved.<BR>\r
f51461c8
LG
5#\r
6# This program and the accompanying materials\r
7# are licensed and made available under the terms and conditions of the BSD License\r
8# which accompanies this distribution. The full text of the license may be found at\r
9# http://opensource.org/licenses/bsd-license.php\r
10#\r
11# THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,\r
12# WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.\r
13#\r
14\r
15##\r
16# Import Modules\r
17#\r
18from optparse import OptionParser\r
19import sys\r
1be2ed90 20import Common.LongFilePathOs as os\r
f51461c8
LG
21import linecache\r
22import FdfParser\r
23import Common.BuildToolError as BuildToolError\r
24from GenFdsGlobalVariable import GenFdsGlobalVariable\r
25from Workspace.WorkspaceDatabase import WorkspaceDatabase\r
26from Workspace.BuildClassObject import PcdClassObject\r
27from Workspace.BuildClassObject import ModuleBuildClassObject\r
28import RuleComplexFile\r
29from EfiSection import EfiSection\r
30import StringIO\r
31import Common.TargetTxtClassObject as TargetTxtClassObject\r
32import Common.ToolDefClassObject as ToolDefClassObject\r
33import Common.DataType\r
34import Common.GlobalData as GlobalData\r
35from Common import EdkLogger\r
36from Common.String import *\r
47fea6af 37from Common.Misc import DirCache, PathClass\r
f51461c8 38from Common.Misc import SaveFileOnChange\r
97fa0ee9 39from Common.Misc import ClearDuplicatedInf\r
e4ac870f 40from Common.Misc import GuidStructureStringToGuidString\r
6b17c11b 41from Common.Misc import CheckPcdDatum\r
f51461c8 42from Common.BuildVersion import gBUILD_VERSION\r
05cc51ad 43from Common.MultipleWorkspace import MultipleWorkspace as mws\r
f51461c8
LG
44\r
45## Version and Copyright\r
46versionNumber = "1.0" + ' ' + gBUILD_VERSION\r
47__version__ = "%prog Version " + versionNumber\r
6b17c11b 48__copyright__ = "Copyright (c) 2007 - 2016, Intel Corporation All rights reserved."\r
f51461c8
LG
49\r
50## Tool entrance method\r
51#\r
52# This method mainly dispatch specific methods per the command line options.\r
53# If no error found, return zero value so the caller of this tool can know\r
54# if it's executed successfully or not.\r
55#\r
56# @retval 0 Tool was successful\r
57# @retval 1 Tool failed\r
58#\r
59def main():\r
60 global Options\r
61 Options = myOptionParser()\r
62\r
63 global Workspace\r
64 Workspace = ""\r
65 ArchList = None\r
66 ReturnCode = 0\r
67\r
68 EdkLogger.Initialize()\r
69 try:\r
70 if Options.verbose != None:\r
71 EdkLogger.SetLevel(EdkLogger.VERBOSE)\r
72 GenFdsGlobalVariable.VerboseMode = True\r
73 \r
74 if Options.FixedAddress != None:\r
75 GenFdsGlobalVariable.FixedLoadAddress = True\r
76 \r
77 if Options.quiet != None:\r
78 EdkLogger.SetLevel(EdkLogger.QUIET)\r
79 if Options.debug != None:\r
80 EdkLogger.SetLevel(Options.debug + 1)\r
81 GenFdsGlobalVariable.DebugLevel = Options.debug\r
82 else:\r
83 EdkLogger.SetLevel(EdkLogger.INFO)\r
84\r
85 if (Options.Workspace == None):\r
86 EdkLogger.error("GenFds", OPTION_MISSING, "WORKSPACE not defined",\r
87 ExtraData="Please use '-w' switch to pass it or set the WORKSPACE environment variable.")\r
88 elif not os.path.exists(Options.Workspace):\r
89 EdkLogger.error("GenFds", PARAMETER_INVALID, "WORKSPACE is invalid",\r
90 ExtraData="Please use '-w' switch to pass it or set the WORKSPACE environment variable.")\r
91 else:\r
92 Workspace = os.path.normcase(Options.Workspace)\r
93 GenFdsGlobalVariable.WorkSpaceDir = Workspace\r
94 if 'EDK_SOURCE' in os.environ.keys():\r
95 GenFdsGlobalVariable.EdkSourceDir = os.path.normcase(os.environ['EDK_SOURCE'])\r
96 if (Options.debug):\r
47fea6af 97 GenFdsGlobalVariable.VerboseLogger("Using Workspace:" + Workspace)\r
f51461c8 98 os.chdir(GenFdsGlobalVariable.WorkSpaceDir)\r
05cc51ad
LY
99 \r
100 # set multiple workspace\r
101 PackagesPath = os.getenv("PACKAGES_PATH")\r
102 mws.setWs(GenFdsGlobalVariable.WorkSpaceDir, PackagesPath)\r
f51461c8
LG
103\r
104 if (Options.filename):\r
105 FdfFilename = Options.filename\r
106 FdfFilename = GenFdsGlobalVariable.ReplaceWorkspaceMacro(FdfFilename)\r
107\r
108 if FdfFilename[0:2] == '..':\r
109 FdfFilename = os.path.realpath(FdfFilename)\r
47fea6af 110 if not os.path.isabs(FdfFilename):\r
05cc51ad 111 FdfFilename = mws.join(GenFdsGlobalVariable.WorkSpaceDir, FdfFilename)\r
f51461c8
LG
112 if not os.path.exists(FdfFilename):\r
113 EdkLogger.error("GenFds", FILE_NOT_FOUND, ExtraData=FdfFilename)\r
f51461c8
LG
114\r
115 GenFdsGlobalVariable.FdfFile = FdfFilename\r
116 GenFdsGlobalVariable.FdfFileTimeStamp = os.path.getmtime(FdfFilename)\r
117 else:\r
118 EdkLogger.error("GenFds", OPTION_MISSING, "Missing FDF filename")\r
119\r
120 if (Options.BuildTarget):\r
121 GenFdsGlobalVariable.TargetName = Options.BuildTarget\r
f51461c8
LG
122\r
123 if (Options.ToolChain):\r
124 GenFdsGlobalVariable.ToolChainTag = Options.ToolChain\r
f51461c8
LG
125\r
126 if (Options.activePlatform):\r
127 ActivePlatform = Options.activePlatform\r
128 ActivePlatform = GenFdsGlobalVariable.ReplaceWorkspaceMacro(ActivePlatform)\r
129\r
130 if ActivePlatform[0:2] == '..':\r
131 ActivePlatform = os.path.realpath(ActivePlatform)\r
132\r
133 if not os.path.isabs (ActivePlatform):\r
05cc51ad 134 ActivePlatform = mws.join(GenFdsGlobalVariable.WorkSpaceDir, ActivePlatform)\r
f51461c8
LG
135\r
136 if not os.path.exists(ActivePlatform) :\r
137 EdkLogger.error("GenFds", FILE_NOT_FOUND, "ActivePlatform doesn't exist!")\r
f51461c8
LG
138 else:\r
139 EdkLogger.error("GenFds", OPTION_MISSING, "Missing active platform")\r
140\r
e642ceb8 141 GenFdsGlobalVariable.ActivePlatform = PathClass(NormPath(ActivePlatform))\r
f51461c8 142\r
97fa0ee9
YL
143 if (Options.ConfDirectory):\r
144 # Get alternate Conf location, if it is absolute, then just use the absolute directory name\r
145 ConfDirectoryPath = os.path.normpath(Options.ConfDirectory)\r
146 if ConfDirectoryPath.startswith('"'):\r
147 ConfDirectoryPath = ConfDirectoryPath[1:]\r
148 if ConfDirectoryPath.endswith('"'):\r
149 ConfDirectoryPath = ConfDirectoryPath[:-1]\r
150 if not os.path.isabs(ConfDirectoryPath):\r
151 # Since alternate directory name is not absolute, the alternate directory is located within the WORKSPACE\r
152 # This also handles someone specifying the Conf directory in the workspace. Using --conf=Conf\r
153 ConfDirectoryPath = os.path.join(GenFdsGlobalVariable.WorkSpaceDir, ConfDirectoryPath)\r
154 else:\r
00bcb5c2
YZ
155 if "CONF_PATH" in os.environ.keys():\r
156 ConfDirectoryPath = os.path.normcase(os.environ["CONF_PATH"])\r
157 else:\r
158 # Get standard WORKSPACE/Conf, use the absolute path to the WORKSPACE/Conf\r
159 ConfDirectoryPath = mws.join(GenFdsGlobalVariable.WorkSpaceDir, 'Conf')\r
97fa0ee9
YL
160 GenFdsGlobalVariable.ConfDir = ConfDirectoryPath\r
161 BuildConfigurationFile = os.path.normpath(os.path.join(ConfDirectoryPath, "target.txt"))\r
f51461c8 162 if os.path.isfile(BuildConfigurationFile) == True:\r
e4979bee
YZ
163 TargetTxt = TargetTxtClassObject.TargetTxtClassObject()\r
164 TargetTxt.LoadTargetTxtFile(BuildConfigurationFile)\r
165 # if no build target given in command line, get it from target.txt\r
166 if not GenFdsGlobalVariable.TargetName:\r
167 BuildTargetList = TargetTxt.TargetTxtDictionary[DataType.TAB_TAT_DEFINES_TARGET]\r
168 if len(BuildTargetList) != 1:\r
169 EdkLogger.error("GenFds", OPTION_VALUE_INVALID, ExtraData="Only allows one instance for Target.")\r
170 GenFdsGlobalVariable.TargetName = BuildTargetList[0]\r
171\r
172 # if no tool chain given in command line, get it from target.txt\r
173 if not GenFdsGlobalVariable.ToolChainTag:\r
174 ToolChainList = TargetTxt.TargetTxtDictionary[DataType.TAB_TAT_DEFINES_TOOL_CHAIN_TAG]\r
175 if ToolChainList == None or len(ToolChainList) == 0:\r
176 EdkLogger.error("GenFds", RESOURCE_NOT_AVAILABLE, ExtraData="No toolchain given. Don't know how to build.")\r
177 if len(ToolChainList) != 1:\r
178 EdkLogger.error("GenFds", OPTION_VALUE_INVALID, ExtraData="Only allows one instance for ToolChain.")\r
179 GenFdsGlobalVariable.ToolChainTag = ToolChainList[0]\r
f51461c8
LG
180 else:\r
181 EdkLogger.error("GenFds", FILE_NOT_FOUND, ExtraData=BuildConfigurationFile)\r
182\r
97fa0ee9
YL
183 #Set global flag for build mode\r
184 GlobalData.gIgnoreSource = Options.IgnoreSources\r
185\r
f51461c8
LG
186 if Options.Macros:\r
187 for Pair in Options.Macros:\r
97fa0ee9
YL
188 if Pair.startswith('"'):\r
189 Pair = Pair[1:]\r
190 if Pair.endswith('"'):\r
191 Pair = Pair[:-1]\r
f51461c8
LG
192 List = Pair.split('=')\r
193 if len(List) == 2:\r
e4979bee
YZ
194 if not List[1].strip():\r
195 EdkLogger.error("GenFds", OPTION_VALUE_INVALID, ExtraData="No Value given for Macro %s" %List[0])\r
f51461c8
LG
196 if List[0].strip() == "EFI_SOURCE":\r
197 GlobalData.gEfiSource = List[1].strip()\r
198 GlobalData.gGlobalDefines["EFI_SOURCE"] = GlobalData.gEfiSource\r
199 continue\r
200 elif List[0].strip() == "EDK_SOURCE":\r
201 GlobalData.gEdkSource = List[1].strip()\r
202 GlobalData.gGlobalDefines["EDK_SOURCE"] = GlobalData.gEdkSource\r
203 continue\r
204 elif List[0].strip() in ["WORKSPACE", "TARGET", "TOOLCHAIN"]:\r
205 GlobalData.gGlobalDefines[List[0].strip()] = List[1].strip()\r
206 else:\r
207 GlobalData.gCommandLineDefines[List[0].strip()] = List[1].strip()\r
208 else:\r
209 GlobalData.gCommandLineDefines[List[0].strip()] = "TRUE"\r
210 os.environ["WORKSPACE"] = Workspace\r
211\r
e4979bee
YZ
212 # Use the -t and -b option as gGlobalDefines's TOOLCHAIN and TARGET if they are not defined\r
213 if "TARGET" not in GlobalData.gGlobalDefines.keys():\r
214 GlobalData.gGlobalDefines["TARGET"] = GenFdsGlobalVariable.TargetName\r
215 if "TOOLCHAIN" not in GlobalData.gGlobalDefines.keys():\r
216 GlobalData.gGlobalDefines["TOOLCHAIN"] = GenFdsGlobalVariable.ToolChainTag\r
217 if "TOOL_CHAIN_TAG" not in GlobalData.gGlobalDefines.keys():\r
218 GlobalData.gGlobalDefines['TOOL_CHAIN_TAG'] = GenFdsGlobalVariable.ToolChainTag\r
219\r
f51461c8 220 """call Workspace build create database"""\r
97fa0ee9
YL
221 GlobalData.gDatabasePath = os.path.normpath(os.path.join(ConfDirectoryPath, GlobalData.gDatabasePath))\r
222 BuildWorkSpace = WorkspaceDatabase(GlobalData.gDatabasePath)\r
f51461c8
LG
223 BuildWorkSpace.InitDatabase()\r
224 \r
225 #\r
226 # Get files real name in workspace dir\r
227 #\r
228 GlobalData.gAllFiles = DirCache(Workspace)\r
229 GlobalData.gWorkspace = Workspace\r
230\r
231 if (Options.archList) :\r
232 ArchList = Options.archList.split(',')\r
233 else:\r
234# EdkLogger.error("GenFds", OPTION_MISSING, "Missing build ARCH")\r
235 ArchList = BuildWorkSpace.BuildObject[GenFdsGlobalVariable.ActivePlatform, 'COMMON', Options.BuildTarget, Options.ToolChain].SupArchList\r
236\r
237 TargetArchList = set(BuildWorkSpace.BuildObject[GenFdsGlobalVariable.ActivePlatform, 'COMMON', Options.BuildTarget, Options.ToolChain].SupArchList) & set(ArchList)\r
238 if len(TargetArchList) == 0:\r
239 EdkLogger.error("GenFds", GENFDS_ERROR, "Target ARCH %s not in platform supported ARCH %s" % (str(ArchList), str(BuildWorkSpace.BuildObject[GenFdsGlobalVariable.ActivePlatform, 'COMMON'].SupArchList)))\r
240 \r
241 for Arch in ArchList:\r
242 GenFdsGlobalVariable.OutputDirFromDscDict[Arch] = NormPath(BuildWorkSpace.BuildObject[GenFdsGlobalVariable.ActivePlatform, Arch, Options.BuildTarget, Options.ToolChain].OutputDirectory)\r
243 GenFdsGlobalVariable.PlatformName = BuildWorkSpace.BuildObject[GenFdsGlobalVariable.ActivePlatform, Arch, Options.BuildTarget, Options.ToolChain].PlatformName\r
244\r
245 if (Options.outputDir):\r
246 OutputDirFromCommandLine = GenFdsGlobalVariable.ReplaceWorkspaceMacro(Options.outputDir)\r
247 if not os.path.isabs (OutputDirFromCommandLine):\r
248 OutputDirFromCommandLine = os.path.join(GenFdsGlobalVariable.WorkSpaceDir, OutputDirFromCommandLine)\r
249 for Arch in ArchList:\r
250 GenFdsGlobalVariable.OutputDirDict[Arch] = OutputDirFromCommandLine\r
251 else:\r
252 for Arch in ArchList:\r
253 GenFdsGlobalVariable.OutputDirDict[Arch] = os.path.join(GenFdsGlobalVariable.OutputDirFromDscDict[Arch], GenFdsGlobalVariable.TargetName + '_' + GenFdsGlobalVariable.ToolChainTag)\r
254\r
255 for Key in GenFdsGlobalVariable.OutputDirDict:\r
256 OutputDir = GenFdsGlobalVariable.OutputDirDict[Key]\r
257 if OutputDir[0:2] == '..':\r
258 OutputDir = os.path.realpath(OutputDir)\r
259\r
260 if OutputDir[1] != ':':\r
261 OutputDir = os.path.join (GenFdsGlobalVariable.WorkSpaceDir, OutputDir)\r
262\r
263 if not os.path.exists(OutputDir):\r
264 EdkLogger.error("GenFds", FILE_NOT_FOUND, ExtraData=OutputDir)\r
265 GenFdsGlobalVariable.OutputDirDict[Key] = OutputDir\r
266\r
267 """ Parse Fdf file, has to place after build Workspace as FDF may contain macros from DSC file """\r
268 FdfParserObj = FdfParser.FdfParser(FdfFilename)\r
269 FdfParserObj.ParseFile()\r
270\r
271 if FdfParserObj.CycleReferenceCheck():\r
272 EdkLogger.error("GenFds", FORMAT_NOT_SUPPORTED, "Cycle Reference Detected in FDF file")\r
273\r
274 if (Options.uiFdName) :\r
275 if Options.uiFdName.upper() in FdfParserObj.Profile.FdDict.keys():\r
276 GenFds.OnlyGenerateThisFd = Options.uiFdName\r
277 else:\r
278 EdkLogger.error("GenFds", OPTION_VALUE_INVALID,\r
279 "No such an FD in FDF file: %s" % Options.uiFdName)\r
280\r
281 if (Options.uiFvName) :\r
282 if Options.uiFvName.upper() in FdfParserObj.Profile.FvDict.keys():\r
283 GenFds.OnlyGenerateThisFv = Options.uiFvName\r
284 else:\r
285 EdkLogger.error("GenFds", OPTION_VALUE_INVALID,\r
286 "No such an FV in FDF file: %s" % Options.uiFvName)\r
287\r
288 if (Options.uiCapName) :\r
289 if Options.uiCapName.upper() in FdfParserObj.Profile.CapsuleDict.keys():\r
290 GenFds.OnlyGenerateThisCap = Options.uiCapName\r
291 else:\r
292 EdkLogger.error("GenFds", OPTION_VALUE_INVALID,\r
293 "No such a Capsule in FDF file: %s" % Options.uiCapName)\r
294\r
6b17c11b
YZ
295 GenFdsGlobalVariable.WorkSpace = BuildWorkSpace\r
296 if ArchList != None:\r
297 GenFdsGlobalVariable.ArchList = ArchList\r
298\r
299 if Options.OptionPcd:\r
300 GlobalData.BuildOptionPcd = Options.OptionPcd\r
301 CheckBuildOptionPcd()\r
302\r
f51461c8
LG
303 """Modify images from build output if the feature of loading driver at fixed address is on."""\r
304 if GenFdsGlobalVariable.FixedLoadAddress:\r
305 GenFds.PreprocessImage(BuildWorkSpace, GenFdsGlobalVariable.ActivePlatform)\r
306 """Call GenFds"""\r
307 GenFds.GenFd('', FdfParserObj, BuildWorkSpace, ArchList)\r
308\r
309 """Generate GUID cross reference file"""\r
310 GenFds.GenerateGuidXRefFile(BuildWorkSpace, ArchList)\r
311\r
312 """Display FV space info."""\r
313 GenFds.DisplayFvSpaceInfo(FdfParserObj)\r
314\r
315 except FdfParser.Warning, X:\r
47fea6af 316 EdkLogger.error(X.ToolName, FORMAT_INVALID, File=X.FileName, Line=X.LineNumber, ExtraData=X.Message, RaiseError=False)\r
f51461c8
LG
317 ReturnCode = FORMAT_INVALID\r
318 except FatalError, X:\r
319 if Options.debug != None:\r
320 import traceback\r
321 EdkLogger.quiet(traceback.format_exc())\r
322 ReturnCode = X.args[0]\r
323 except:\r
324 import traceback\r
325 EdkLogger.error(\r
326 "\nPython",\r
327 CODE_ERROR,\r
328 "Tools code failure",\r
3a0f8bde 329 ExtraData="Please send email to edk2-devel@lists.01.org for help, attaching following call stack trace!\n",\r
f51461c8
LG
330 RaiseError=False\r
331 )\r
332 EdkLogger.quiet(traceback.format_exc())\r
333 ReturnCode = CODE_ERROR\r
97fa0ee9
YL
334 finally:\r
335 ClearDuplicatedInf()\r
f51461c8
LG
336 return ReturnCode\r
337\r
338gParamCheck = []\r
339def SingleCheckCallback(option, opt_str, value, parser):\r
340 if option not in gParamCheck:\r
341 setattr(parser.values, option.dest, value)\r
342 gParamCheck.append(option)\r
343 else:\r
344 parser.error("Option %s only allows one instance in command line!" % option)\r
6b17c11b
YZ
345\r
346def CheckBuildOptionPcd():\r
347 for Arch in GenFdsGlobalVariable.ArchList:\r
348 PkgList = GenFdsGlobalVariable.WorkSpace.GetPackageList(GenFdsGlobalVariable.ActivePlatform, Arch, GenFdsGlobalVariable.TargetName, GenFdsGlobalVariable.ToolChainTag)\r
349 for i, pcd in enumerate(GlobalData.BuildOptionPcd):\r
350 if type(pcd) is tuple:\r
351 continue\r
352 (pcdname, pcdvalue) = pcd.split('=')\r
353 if not pcdvalue:\r
354 EdkLogger.error('GenFds', OPTION_MISSING, "No Value specified for the PCD %s." % (pcdname))\r
355 if '.' in pcdname:\r
356 (TokenSpaceGuidCName, TokenCName) = pcdname.split('.')\r
357 HasTokenSpace = True\r
358 else:\r
359 TokenCName = pcdname\r
360 TokenSpaceGuidCName = ''\r
361 HasTokenSpace = False\r
362 TokenSpaceGuidCNameList = []\r
363 FoundFlag = False\r
364 PcdDatumType = ''\r
365 NewValue = ''\r
366 for package in PkgList:\r
367 for key in package.Pcds:\r
368 PcdItem = package.Pcds[key]\r
369 if HasTokenSpace:\r
370 if (PcdItem.TokenCName, PcdItem.TokenSpaceGuidCName) == (TokenCName, TokenSpaceGuidCName):\r
371 PcdDatumType = PcdItem.DatumType\r
372 NewValue = BuildOptionPcdValueFormat(TokenSpaceGuidCName, TokenCName, PcdDatumType, pcdvalue)\r
373 FoundFlag = True\r
374 else:\r
375 if PcdItem.TokenCName == TokenCName:\r
376 if not PcdItem.TokenSpaceGuidCName in TokenSpaceGuidCNameList:\r
377 if len (TokenSpaceGuidCNameList) < 1:\r
378 TokenSpaceGuidCNameList.append(PcdItem.TokenSpaceGuidCName)\r
379 PcdDatumType = PcdItem.DatumType\r
380 TokenSpaceGuidCName = PcdItem.TokenSpaceGuidCName\r
381 NewValue = BuildOptionPcdValueFormat(TokenSpaceGuidCName, TokenCName, PcdDatumType, pcdvalue)\r
382 FoundFlag = True\r
383 else:\r
384 EdkLogger.error(\r
385 'GenFds',\r
386 PCD_VALIDATION_INFO_ERROR,\r
387 "The Pcd %s is found under multiple different TokenSpaceGuid: %s and %s." % (TokenCName, PcdItem.TokenSpaceGuidCName, TokenSpaceGuidCNameList[0])\r
388 )\r
389\r
390 GlobalData.BuildOptionPcd[i] = (TokenSpaceGuidCName, TokenCName, NewValue)\r
391\r
392def BuildOptionPcdValueFormat(TokenSpaceGuidCName, TokenCName, PcdDatumType, Value):\r
393 if PcdDatumType == 'VOID*':\r
394 if Value.startswith('L'):\r
395 if not Value[1]:\r
396 EdkLogger.error('GenFds', OPTION_VALUE_INVALID, 'For Void* type PCD, when specify the Value in the command line, please use the following format: "string", L"string", B"{...}"')\r
397 Value = Value[0] + '"' + Value[1:] + '"'\r
398 elif Value.startswith('B'):\r
399 if not Value[1]:\r
400 EdkLogger.error('GenFds', OPTION_VALUE_INVALID, 'For Void* type PCD, when specify the Value in the command line, please use the following format: "string", L"string", B"{...}"')\r
401 Value = Value[1:]\r
402 else:\r
403 if not Value[0]:\r
404 EdkLogger.error('GenFds', OPTION_VALUE_INVALID, 'For Void* type PCD, when specify the Value in the command line, please use the following format: "string", L"string", B"{...}"')\r
405 Value = '"' + Value + '"'\r
406\r
407 IsValid, Cause = CheckPcdDatum(PcdDatumType, Value)\r
408 if not IsValid:\r
409 EdkLogger.error('build', FORMAT_INVALID, Cause, ExtraData="%s.%s" % (TokenSpaceGuidCName, TokenCName))\r
410 if PcdDatumType == 'BOOLEAN':\r
411 Value = Value.upper()\r
412 if Value == 'TRUE' or Value == '1':\r
413 Value = '1'\r
414 elif Value == 'FALSE' or Value == '0':\r
415 Value = '0'\r
416 return Value\r
417\r
f51461c8
LG
418 \r
419## Parse command line options\r
420#\r
421# Using standard Python module optparse to parse command line option of this tool.\r
422#\r
423# @retval Opt A optparse.Values object containing the parsed options\r
424# @retval Args Target of build command\r
425#\r
426def myOptionParser():\r
427 usage = "%prog [options] -f input_file -a arch_list -b build_target -p active_platform -t tool_chain_tag -D \"MacroName [= MacroValue]\""\r
47fea6af 428 Parser = OptionParser(usage=usage, description=__copyright__, version="%prog " + str(versionNumber))\r
f51461c8
LG
429 Parser.add_option("-f", "--file", dest="filename", type="string", help="Name of FDF file to convert", action="callback", callback=SingleCheckCallback)\r
430 Parser.add_option("-a", "--arch", dest="archList", help="comma separated list containing one or more of: IA32, X64, IPF, ARM, AARCH64 or EBC which should be built, overrides target.txt?s TARGET_ARCH")\r
431 Parser.add_option("-q", "--quiet", action="store_true", type=None, help="Disable all messages except FATAL ERRORS.")\r
432 Parser.add_option("-v", "--verbose", action="store_true", type=None, help="Turn on verbose output with informational messages printed.")\r
433 Parser.add_option("-d", "--debug", action="store", type="int", help="Enable debug messages at specified level.")\r
434 Parser.add_option("-p", "--platform", type="string", dest="activePlatform", help="Set the ACTIVE_PLATFORM, overrides target.txt ACTIVE_PLATFORM setting.",\r
435 action="callback", callback=SingleCheckCallback)\r
436 Parser.add_option("-w", "--workspace", type="string", dest="Workspace", default=os.environ.get('WORKSPACE'), help="Set the WORKSPACE",\r
437 action="callback", callback=SingleCheckCallback)\r
438 Parser.add_option("-o", "--outputDir", type="string", dest="outputDir", help="Name of Build Output directory",\r
439 action="callback", callback=SingleCheckCallback)\r
440 Parser.add_option("-r", "--rom_image", dest="uiFdName", help="Build the image using the [FD] section named by FdUiName.")\r
441 Parser.add_option("-i", "--FvImage", dest="uiFvName", help="Build the FV image using the [FV] section named by UiFvName")\r
442 Parser.add_option("-C", "--CapsuleImage", dest="uiCapName", help="Build the Capsule image using the [Capsule] section named by UiCapName")\r
443 Parser.add_option("-b", "--buildtarget", type="string", dest="BuildTarget", help="Set the build TARGET, overrides target.txt TARGET setting.",\r
444 action="callback", callback=SingleCheckCallback)\r
445 Parser.add_option("-t", "--tagname", type="string", dest="ToolChain", help="Using the tools: TOOL_CHAIN_TAG name to build the platform.",\r
446 action="callback", callback=SingleCheckCallback)\r
447 Parser.add_option("-D", "--define", action="append", type="string", dest="Macros", help="Macro: \"Name [= Value]\".")\r
448 Parser.add_option("-s", "--specifyaddress", dest="FixedAddress", action="store_true", type=None, help="Specify driver load address.")\r
97fa0ee9
YL
449 Parser.add_option("--conf", action="store", type="string", dest="ConfDirectory", help="Specify the customized Conf directory.")\r
450 Parser.add_option("--ignore-sources", action="store_true", dest="IgnoreSources", default=False, help="Focus to a binary build and ignore all source files")\r
6b17c11b 451 Parser.add_option("--pcd", action="append", dest="OptionPcd", help="Set PCD value by command line. Format: \"PcdName=Value\" ")\r
97fa0ee9 452\r
f51461c8
LG
453 (Options, args) = Parser.parse_args()\r
454 return Options\r
455\r
456## The class implementing the EDK2 flash image generation process\r
457#\r
458# This process includes:\r
459# 1. Collect workspace information, includes platform and module information\r
460# 2. Call methods of Fd class to generate FD\r
461# 3. Call methods of Fv class to generate FV that not belong to FD\r
462#\r
463class GenFds :\r
464 FdfParsef = None\r
465 # FvName, FdName, CapName in FDF, Image file name\r
466 ImageBinDict = {}\r
467 OnlyGenerateThisFd = None\r
468 OnlyGenerateThisFv = None\r
469 OnlyGenerateThisCap = None\r
470\r
471 ## GenFd()\r
472 #\r
473 # @param OutputDir Output directory\r
474 # @param FdfParser FDF contents parser\r
475 # @param Workspace The directory of workspace\r
476 # @param ArchList The Arch list of platform\r
477 #\r
478 def GenFd (OutputDir, FdfParser, WorkSpace, ArchList):\r
479 GenFdsGlobalVariable.SetDir ('', FdfParser, WorkSpace, ArchList)\r
480\r
481 GenFdsGlobalVariable.VerboseLogger(" Generate all Fd images and their required FV and Capsule images!")\r
482 if GenFds.OnlyGenerateThisCap != None and GenFds.OnlyGenerateThisCap.upper() in GenFdsGlobalVariable.FdfParser.Profile.CapsuleDict.keys():\r
483 CapsuleObj = GenFdsGlobalVariable.FdfParser.Profile.CapsuleDict.get(GenFds.OnlyGenerateThisCap.upper())\r
484 if CapsuleObj != None:\r
485 CapsuleObj.GenCapsule()\r
486 return\r
487\r
488 if GenFds.OnlyGenerateThisFd != None and GenFds.OnlyGenerateThisFd.upper() in GenFdsGlobalVariable.FdfParser.Profile.FdDict.keys():\r
489 FdObj = GenFdsGlobalVariable.FdfParser.Profile.FdDict.get(GenFds.OnlyGenerateThisFd.upper())\r
490 if FdObj != None:\r
491 FdObj.GenFd()\r
492 return\r
493 elif GenFds.OnlyGenerateThisFd == None and GenFds.OnlyGenerateThisFv == None:\r
494 for FdName in GenFdsGlobalVariable.FdfParser.Profile.FdDict.keys():\r
495 FdObj = GenFdsGlobalVariable.FdfParser.Profile.FdDict[FdName]\r
496 FdObj.GenFd()\r
497\r
498 GenFdsGlobalVariable.VerboseLogger("\n Generate other FV images! ")\r
499 if GenFds.OnlyGenerateThisFv != None and GenFds.OnlyGenerateThisFv.upper() in GenFdsGlobalVariable.FdfParser.Profile.FvDict.keys():\r
500 FvObj = GenFdsGlobalVariable.FdfParser.Profile.FvDict.get(GenFds.OnlyGenerateThisFv.upper())\r
501 if FvObj != None:\r
502 Buffer = StringIO.StringIO()\r
503 FvObj.AddToBuffer(Buffer)\r
504 Buffer.close()\r
505 return\r
506 elif GenFds.OnlyGenerateThisFv == None:\r
507 for FvName in GenFdsGlobalVariable.FdfParser.Profile.FvDict.keys():\r
508 Buffer = StringIO.StringIO('')\r
509 FvObj = GenFdsGlobalVariable.FdfParser.Profile.FvDict[FvName]\r
510 FvObj.AddToBuffer(Buffer)\r
511 Buffer.close()\r
512 \r
513 if GenFds.OnlyGenerateThisFv == None and GenFds.OnlyGenerateThisFd == None and GenFds.OnlyGenerateThisCap == None:\r
514 if GenFdsGlobalVariable.FdfParser.Profile.CapsuleDict != {}:\r
515 GenFdsGlobalVariable.VerboseLogger("\n Generate other Capsule images!")\r
516 for CapsuleName in GenFdsGlobalVariable.FdfParser.Profile.CapsuleDict.keys():\r
517 CapsuleObj = GenFdsGlobalVariable.FdfParser.Profile.CapsuleDict[CapsuleName]\r
518 CapsuleObj.GenCapsule()\r
519\r
520 if GenFdsGlobalVariable.FdfParser.Profile.OptRomDict != {}:\r
521 GenFdsGlobalVariable.VerboseLogger("\n Generate all Option ROM!")\r
522 for DriverName in GenFdsGlobalVariable.FdfParser.Profile.OptRomDict.keys():\r
523 OptRomObj = GenFdsGlobalVariable.FdfParser.Profile.OptRomDict[DriverName]\r
524 OptRomObj.AddToBuffer(None)\r
525\r
526 ## GetFvBlockSize()\r
527 #\r
528 # @param FvObj Whose block size to get\r
529 # @retval int Block size value\r
530 #\r
531 def GetFvBlockSize(FvObj):\r
532 DefaultBlockSize = 0x1\r
533 FdObj = None\r
534 if GenFds.OnlyGenerateThisFd != None and GenFds.OnlyGenerateThisFd.upper() in GenFdsGlobalVariable.FdfParser.Profile.FdDict.keys():\r
535 FdObj = GenFdsGlobalVariable.FdfParser.Profile.FdDict[GenFds.OnlyGenerateThisFd.upper()]\r
536 if FdObj == None:\r
537 for ElementFd in GenFdsGlobalVariable.FdfParser.Profile.FdDict.values():\r
538 for ElementRegion in ElementFd.RegionList:\r
539 if ElementRegion.RegionType == 'FV':\r
540 for ElementRegionData in ElementRegion.RegionDataList:\r
541 if ElementRegionData != None and ElementRegionData.upper() == FvObj.UiFvName:\r
542 if FvObj.BlockSizeList != []:\r
543 return FvObj.BlockSizeList[0][0]\r
544 else:\r
545 return ElementRegion.BlockSizeOfRegion(ElementFd.BlockSizeList)\r
546 if FvObj.BlockSizeList != []:\r
547 return FvObj.BlockSizeList[0][0]\r
548 return DefaultBlockSize\r
549 else:\r
550 for ElementRegion in FdObj.RegionList:\r
551 if ElementRegion.RegionType == 'FV':\r
552 for ElementRegionData in ElementRegion.RegionDataList:\r
553 if ElementRegionData != None and ElementRegionData.upper() == FvObj.UiFvName:\r
554 if FvObj.BlockSizeList != []:\r
555 return FvObj.BlockSizeList[0][0]\r
556 else:\r
557 return ElementRegion.BlockSizeOfRegion(ElementFd.BlockSizeList)\r
558 return DefaultBlockSize\r
559\r
560 ## DisplayFvSpaceInfo()\r
561 #\r
562 # @param FvObj Whose block size to get\r
563 # @retval None\r
564 #\r
565 def DisplayFvSpaceInfo(FdfParser):\r
566 \r
567 FvSpaceInfoList = []\r
568 MaxFvNameLength = 0\r
569 for FvName in FdfParser.Profile.FvDict:\r
570 if len(FvName) > MaxFvNameLength:\r
571 MaxFvNameLength = len(FvName)\r
572 FvSpaceInfoFileName = os.path.join(GenFdsGlobalVariable.FvDir, FvName.upper() + '.Fv.map')\r
573 if os.path.exists(FvSpaceInfoFileName):\r
574 FileLinesList = linecache.getlines(FvSpaceInfoFileName)\r
575 TotalFound = False\r
576 Total = ''\r
577 UsedFound = False\r
578 Used = ''\r
579 FreeFound = False\r
580 Free = ''\r
581 for Line in FileLinesList:\r
582 NameValue = Line.split('=')\r
583 if len(NameValue) == 2:\r
584 if NameValue[0].strip() == 'EFI_FV_TOTAL_SIZE':\r
585 TotalFound = True\r
586 Total = NameValue[1].strip()\r
587 if NameValue[0].strip() == 'EFI_FV_TAKEN_SIZE':\r
588 UsedFound = True\r
589 Used = NameValue[1].strip()\r
590 if NameValue[0].strip() == 'EFI_FV_SPACE_SIZE':\r
591 FreeFound = True\r
592 Free = NameValue[1].strip()\r
593 \r
594 if TotalFound and UsedFound and FreeFound:\r
595 FvSpaceInfoList.append((FvName, Total, Used, Free))\r
596 \r
597 GenFdsGlobalVariable.InfLogger('\nFV Space Information')\r
598 for FvSpaceInfo in FvSpaceInfoList:\r
599 Name = FvSpaceInfo[0]\r
600 TotalSizeValue = long(FvSpaceInfo[1], 0)\r
601 UsedSizeValue = long(FvSpaceInfo[2], 0)\r
602 FreeSizeValue = long(FvSpaceInfo[3], 0)\r
603 if UsedSizeValue == TotalSizeValue:\r
604 Percentage = '100'\r
605 else:\r
47fea6af
YZ
606 Percentage = str((UsedSizeValue + 0.0) / TotalSizeValue)[0:4].lstrip('0.')\r
607\r
f51461c8
LG
608 GenFdsGlobalVariable.InfLogger(Name + ' ' + '[' + Percentage + '%Full] ' + str(TotalSizeValue) + ' total, ' + str(UsedSizeValue) + ' used, ' + str(FreeSizeValue) + ' free')\r
609\r
610 ## PreprocessImage()\r
611 #\r
612 # @param BuildDb Database from build meta data files\r
613 # @param DscFile modules from dsc file will be preprocessed\r
614 # @retval None\r
615 #\r
616 def PreprocessImage(BuildDb, DscFile):\r
617 PcdDict = BuildDb.BuildObject[DscFile, 'COMMON', GenFdsGlobalVariable.TargetName, GenFdsGlobalVariable.ToolChainTag].Pcds\r
618 PcdValue = ''\r
619 for Key in PcdDict:\r
620 PcdObj = PcdDict[Key]\r
621 if PcdObj.TokenCName == 'PcdBsBaseAddress':\r
622 PcdValue = PcdObj.DefaultValue\r
623 break\r
624 \r
625 if PcdValue == '':\r
626 return\r
627 \r
628 Int64PcdValue = long(PcdValue, 0)\r
629 if Int64PcdValue == 0 or Int64PcdValue < -1: \r
630 return\r
631 \r
632 TopAddress = 0\r
633 if Int64PcdValue > 0:\r
634 TopAddress = Int64PcdValue\r
635 \r
636 ModuleDict = BuildDb.BuildObject[DscFile, 'COMMON', GenFdsGlobalVariable.TargetName, GenFdsGlobalVariable.ToolChainTag].Modules\r
637 for Key in ModuleDict:\r
638 ModuleObj = BuildDb.BuildObject[Key, 'COMMON', GenFdsGlobalVariable.TargetName, GenFdsGlobalVariable.ToolChainTag]\r
639 print ModuleObj.BaseName + ' ' + ModuleObj.ModuleType\r
640\r
641 def GenerateGuidXRefFile(BuildDb, ArchList):\r
642 GuidXRefFileName = os.path.join(GenFdsGlobalVariable.FvDir, "Guid.xref")\r
643 GuidXRefFile = StringIO.StringIO('')\r
e4ac870f 644 GuidDict = {}\r
f51461c8
LG
645 for Arch in ArchList:\r
646 PlatformDataBase = BuildDb.BuildObject[GenFdsGlobalVariable.ActivePlatform, Arch, GenFdsGlobalVariable.TargetName, GenFdsGlobalVariable.ToolChainTag]\r
647 for ModuleFile in PlatformDataBase.Modules:\r
648 Module = BuildDb.BuildObject[ModuleFile, Arch, GenFdsGlobalVariable.TargetName, GenFdsGlobalVariable.ToolChainTag]\r
649 GuidXRefFile.write("%s %s\n" % (Module.Guid, Module.BaseName))\r
e4ac870f
LG
650 for key, item in Module.Protocols.items():\r
651 GuidDict[key] = item\r
652 for key, item in Module.Guids.items():\r
653 GuidDict[key] = item\r
654 for key, item in Module.Ppis.items():\r
655 GuidDict[key] = item\r
656 # Append GUIDs, Protocols, and PPIs to the Xref file\r
657 GuidXRefFile.write("\n")\r
658 for key, item in GuidDict.items():\r
659 GuidXRefFile.write("%s %s\n" % (GuidStructureStringToGuidString(item).upper(), key))\r
660\r
f51461c8
LG
661 if GuidXRefFile.getvalue():\r
662 SaveFileOnChange(GuidXRefFileName, GuidXRefFile.getvalue(), False)\r
663 GenFdsGlobalVariable.InfLogger("\nGUID cross reference file can be found at %s" % GuidXRefFileName)\r
664 elif os.path.exists(GuidXRefFileName):\r
665 os.remove(GuidXRefFileName)\r
666 GuidXRefFile.close()\r
667\r
668 ##Define GenFd as static function\r
669 GenFd = staticmethod(GenFd)\r
670 GetFvBlockSize = staticmethod(GetFvBlockSize)\r
671 DisplayFvSpaceInfo = staticmethod(DisplayFvSpaceInfo)\r
672 PreprocessImage = staticmethod(PreprocessImage)\r
673 GenerateGuidXRefFile = staticmethod(GenerateGuidXRefFile)\r
674\r
675if __name__ == '__main__':\r
676 r = main()\r
677 ## 0-127 is a safe return range, and 1 is a standard default error\r
678 if r < 0 or r > 127: r = 1\r
679 sys.exit(r)\r
680\r